ggplot两组的散点图,叠加均值为X和Y误差条

时间:2012-09-24 18:34:47

标签: r ggplot2

如何生成两组的ggplot2散点图,其中包含指示的方法以及X和Y错误条,如下所示?

Scatter plot

以下是一个简化示例(使用dput重新创建data.frame df),其中包含两组单元格和三个度量,我想说一下Peak Rise,或Peak针对Decay。这很简单,但我想添加一些点,表明该组意味着X和Y误差条(+/- sem)。

有没有办法在ggplot2中执行此操作,还是需要先生成均值和sem值? This帖子引起我的注意geom_errorbarh,但我仍然不确定最好的方法。

library(ggplot2)

df<-structure(list(Group = c("A", "A", "A", "A", "A", "A", "A", 
"A", "B", "B", "B", "B", "B", "B", "B", "B"), Peak = c(102.975, 
37.805, 64.996, 66.36, 199.354, 7.425, 34.137, 366.59, 10.165, 
14.833, 702.525, 39.086, 8.286, 122.783, 105.762, 37.018), Rise = c(0.346855, 
0.24165, 0.24028, 0.461548, 0.194016, 0.164047, 0.484375, 0.307861, 
0.438538, 0.488083, 0.549423, 0.365448, 0.511551, 0.33596, 0.331467, 
0.270096), Decay = c(1.3874, 1.07407, 1.88787, 2.64408, 1.1462, 
0.615963, 4.04641, 1.48701, 3.61397, 4.1838, 1.92746, 3.64329, 
4.21354, 0.812695, 1.14611, 1.28279)), .Names = c("Group", 
"Peak", "Rise", "Decay"), class = "data.frame", row.names = c(NA, 
-16L))

ggplot(df, aes(Peak, Rise)) + 
  geom_point(aes(colour=Group)) +
  theme_bw(14)

我尝试过类似的事情:

library(doBy)

sem <- function(x) sqrt(var(x)/length(x))
z<-summaryBy(Peak+Rise+Decay~Group, data=df, FUN=c(mean,sem))
z

获取值,但很容易(并且灵活地)将它们合并到ggplot代码中会让我失望。

1 个答案:

答案 0 :(得分:2)

我倾向于使用 plyr 来进行这些摘要:

z <- ddply(df,.(Group),summarise,
            Peak = mean(Peak),
            Rise = mean(Rise),
            PeakSE = sqrt(var(Peak))/length(Peak),
            RiseSE = sqrt(var(Rise))/length(Rise))

ggplot(df,aes(x = Peak,y = Rise)) + 
    geom_point(aes(colour = Group)) + 
    geom_point(data = z,aes(colour = Group)) +
    geom_errorbarh(data = z,aes(xmin = Peak - PeakSE,xmax = Peak + PeakSE,y = Rise,colour = Group,height = 0.01)) + 
    geom_errorbar(data = z,aes(ymin = Rise - RiseSE,ymax = Rise + RiseSE,x = Peak,colour = Group))

enter image description here

我承认我有点失望,我必须手动调整横杆高度。但是考虑一下,我想这可能是相当具有挑战性的。