[英]Scatter plot that shows all points with the same value
我如何在R中创建散点图,以便即使在某些类别中具有相同的值,也可以在此处显示所有点。 除了数据点,我想在每个类别中都取平均值。
例如,如果我有两个变量的数据集 ,而其中一个变量(棉花重量百分比)是因子:
dat <- structure(list(`Tensile Strength` = c(12L, 19L, 17L, 7L, 25L,
7L, 14L, 12L, 18L, 22L, 18L, 7L, 18L, 18L, 15L, 10L, 11L, 19L,
11L, 19L, 15L, 19L, 11L, 23L, 9L), `Cotton weight percent` = c(20L,
30L, 20L, 35L, 30L, 15L, 25L, 20L, 25L, 30L, 20L, 15L, 25L, 20L,
15L, 35L, 35L, 25L, 15L, 25L, 35L, 30L, 35L, 30L, 15L)), .Names = c("Tensile Strength",
"Cotton weight percent"), class = "data.frame", row.names = c(NA,
-25L))
我如何制作这样的散点图:
在此,实心点是单个观察值,空心圆是观察到的平均拉伸强度。
这可以在ggplot2中使用geom_jitter
和stat_summary
。 具体来说, geom_jitter
将为您提供图形上的黑点:
library(ggplot2)
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_jitter(position = position_jitter(width = .1))
p
(“抖动”是在x轴上添加一些噪声,如您的示例所示)。
然后, stat_summary
层使您可以为每个x值的平均值添加一个点(我将其stat_summary
大号和红色):
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_jitter(position = position_jitter(width = .1)) +
stat_summary(fun.y = "mean", geom = "point", color = "red", size = 3)
使用本地R:
plot(dat[,1]~dat[,2],ylab="Tensile Strength",xlab="Cotton weight percent",cex=1.5)
points(sort(unique(dat[,2])),tapply(dat[,1],dat[,2],mean),pch=16,col=3,cex=1.5)
如果要显示重复的案例,可以执行以下操作:
cwp=sort(unique(dat[,2]))
ta=tapply(1:nrow(dat),list(dat[,2],dat[,1]),length)
ft=function(v,x){#
nm=as.numeric(colnames(v))
do.call(rbind,lapply(1:length(nm),function(zv)if(v[zv]>1)
cbind(rep(x,v[zv])+seq(.6,1.4,length.out=v[zv])-1,nm[zv]) else c(x,nm[zv])))
}
fd=lapply(1:nrow(ta),function(z)ft(t(ta[z,!is.na(ta[z,])]),cwp[z]))
datf=do.call(rbind,fd)
plot(datf[,2]~datf[,1],ylab="Tensile Strength",xlab="Cotton weight percent",cex=1.5)
points(sort(unique(dat[,2])),tapply(dat[,1],dat[,2],mean),pch=16,col=3,cex=1.5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.