2015-06-27 118 views
1

如何在R中创建散点图,以便所有点都显示在那里,即使我在某些类别中具有相同的值。除了数据点之外,我想在每个类别中都有平均值。散点图显示具有相同值的所有点

举例来说,如果我有两个变量,在那里他们(棉重量百分比)一个是因素data set

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)) 

我怎样才能让一个散点图像这样的:enter image description here

这里,实心点是单独的观察值,空心圆是观察到的平均拉伸强度。

回答

5

这可以在ggplot2中用geom_jitterstat_summary完成。具体而言,将geom_jitter给你的黑点上的曲线图:

library(ggplot2) 
ggplot(mtcars, aes(factor(cyl), mpg)) + 
    geom_jitter(position = position_jitter(width = .1)) 
p 

(其中“抖动”是在x轴而言添加一些噪声,如在你的例子发生时)。

然后stat_summary层可以让你添加一个点平均每个x值的(我做了又大又红):

ggplot(mtcars, aes(factor(cyl), mpg)) + 
    geom_jitter(position = position_jitter(width = .1)) + 
    stat_summary(fun.y = "mean", geom = "point", color = "red", size = 3) 

enter image description here

+0

@Legalize很好,你是如何得到棉重量百分比的? (手动?) –

+0

@LegalizeIt我错过了OP发布数据集,谢谢! –

+0

谢谢!我在我的数据集上试了一下,它工作。它与我附加的散点图相媲美,但有一件事情我想要改进 - 相同值的点不会仅由x轴移动,而且也会由y轴移动。我希望他们在y轴上的价值相同,但只在x轴上分开。你知道我该怎么做? – user23709

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) 

enter image description here

如果你想显示重复的情况下,你可以这样做:

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) 

enter image description here

+0

谢谢。这是我知道该怎么做的,但并不显示所有数据点(具有相同值的数据点)。 – user23709

+0

有点小事,看看编辑吧! – Robert

相关问题