以下面的数据为例:
- set.seed(955)
- # 构建一个含有噪声的递增数据组
- dat <- data.frame(cond = rep(c("A", "B"), each=10),
- xvar = 1:20 + rnorm(20,sd=3),
- yvar = 1:20 + rnorm(20,sd=3))
- head(dat)
- #> cond xvar yvar
- #> 1 A -4.252354 3.473157275
- #> 2 A 1.702318 0.005939612
- #> 3 A 4.323054 -0.094252427
- #> 4 A 1.780628 2.072808278
- #> 5 A 11.537348 1.215440358
- #> 6 A 6.672130 3.608111411
-
- library(ggplot2)
1、绘制带回归线的经典散点图
- ggplot(dat, aes(x=xvar, y=yvar)) +
- geom_point(shape=1) # 数据点由空心圆表示
-
- ggplot(dat, aes(x=xvar, y=yvar)) +
- geom_point(shape=1) + # 数据点由空心圆表示
- geom_smooth(method=lm) # 添加回归线
- # (默认显示95%置信区间)
-
- ggplot(dat, aes(x=xvar, y=yvar)) +
- geom_point(shape=1) + # 数据点由空心圆表示
- geom_smooth(method=lm, # 添加回归线
- se=FALSE) # 隐藏置信区间区域
- ggplot(dat, aes(x=xvar, y=yvar)) +
- geom_point(shape=1) + # 数据点由空心圆表示
- geom_smooth() # 添加局部加权回归的平滑拟合曲线
2、按变量属性设置不同的颜色/形状
- # 按照cond给数据点设置不同颜色
- ggplot(dat, aes(x=xvar, y=yvar, color=cond)) + geom_point(shape=1)
-
- # 添加不同颜色的回归线
- ggplot(dat, aes(x=xvar, y=yvar, color=cond)) +
- geom_point(shape=1) +
- scale_colour_hue(l=50) + # 调用颜色稍暗的调色板
- geom_smooth(method=lm, # 添加回归线
- se=FALSE) # 隐藏置信区间区域
-
- # 扩展回归线
- ggplot(dat, aes(x=xvar, y=yvar, color=cond)) + geom_point(shape=1) +
- scale_colour_hue(l=50) + # 调用颜色稍暗的调色板
- geom_smooth(method=lm, # 添加回归线
- se=FALSE, # 隐藏置信区间区域
- fullrange=TRUE) # 扩展回归线
- # 按照cond给数据点设置不同形状
- ggplot(dat, aes(x=xvar, y=yvar, shape=cond)) + geom_point()
-
- # 改变形状的样式
- ggplot(dat, aes(x=xvar, y=yvar, shape=cond)) + geom_point() +
- scale_shape_manual(values=c(1,2)) # 使用空心的圆和三角形
具体的颜色和形状种类可详见Colors (ggplot2))和Shapes and linetypes
3、画布溢出的处理
如果我们的数据点非常的多,或是数据集中点的分布非常离散,那么在作图时就有可能会出现数据点溢出画布,或是数据点在画布上的分布过于集中的情况。
- # 将变量xvar和yvar的值归约为离原值最近的5的倍数
- dat$xrnd <- round(dat$xvar/5)*5
- dat$yrnd <- round(dat$yvar/5)*5
-
- # 设置点的不透明度为1/4
- # 为了避免画布溢出,减少了样本点的使用量
- ggplot(dat, aes(x=xrnd, y=yrnd)) +
- geom_point(shape=19, # Use solid circles
- alpha=1/4) # 1/4 opacity
- # 使数据点分散化
- # 分散区域为长0.5个单位宽1个单位的矩形区域
- ggplot(dat, aes(x=xrnd, y=yrnd)) +
- geom_point(shape=1, # Use hollow circles
- position=position_jitter(width=1,height=.5))
以上内容来自 数析学院 ,我不生产代码,只是代码的搬用工