瑞德学习R语言day05

2021-06-07  本文已影响0人  __method__

散点图

特性: 两个变量之间的关系分布图

plot(mtcars$wt, mtcars$mpg)

精细化

 plot(mtcars$wt, mtcars$mpg, xlab = "Car weight", ylab = "Miles per Gallon", col="red", pch=17)

数据拟合

 plot(mtcars$wt, mtcars$mpg, xlab = "Car weight", ylab = "Miles per Gallon", col="red", pch=17)
abline(lm(mtcars$mpg~mtcars$wt))
# lm 是线性模型的意思    

简单说一下 lm 函数

Usage
lm(formula, data, subset, weights, na.action,
   method = "qr", model = TRUE, x = FALSE, y = FALSE, qr = TRUE,
   singular.ok = TRUE, contrasts = NULL, offset, ...)

-formula:指要拟合的模型形式,

lm(mtcars$mpg~mtcars$wt) 对 mpg和wt进行线性模型分析, 中间用~

abline 函数的作用是在一张图表上添加直线(参考线), 可以是一条斜线,通过x或y轴的交点和斜率来确定位置;也可以是一条水平或者垂直的线,只需要指定与x轴或y轴交点的位置就可以了


plot

 plot(mtcars)

成对关系图更好看出两个变量之间的 关系

pairs(mtcars)
plot(~mpg+disp+drat+wt,data = mtcars)

ggplot散点图

library(ggplot2)
p = ggplot(mtcars, aes(wt, mpg))
> p + geom_point()
p = ggplot(mtcars, aes(wt, mpg))
p + geom_point(aes(colour = factor(cyl)))

传入的不是因子

p = ggplot(mtcars, aes(wt, mpg))
p + geom_point(aes(colour = cyl))
p = ggplot(mtcars, aes(wt, mpg))
p + geom_point(aes(colour = factor(gear)))

下面几个颜色绘制方法等价
aes(col = x)
aes(fg = x)
aes(color = x)
aes(colour = x)

p = ggplot(mtcars, aes(wt, mpg))
p + geom_point(aes(shape = factor(cyl)))
p + geom_point(aes(shape = factor(cyl))) + scale_shape(solid = FALSE)
p = ggplot(mtcars, aes(wt, mpg))
p + geom_point(aes(size=qsec))
p = ggplot(mtcars, aes(wt, mpg))
p + geom_point(aes(color=cyl)) + scale_colour_gradient(low = "red")
p = ggplot(mtcars, aes(wt, mpg))
 p + geom_point(aes(color=cyl, size=qsec)) + scale_colour_gradient(low = "red")

plotly

install.packages("plotly")
p = plot_ly(mtcars, x=~mpg, y=~wt, type="scatter")
print(p)
上一篇下一篇

猜你喜欢

热点阅读