2

如何生成两个组的 ggplot2 散点图,其均值与 X 和 Y 误差线一起指示,像这样?

散点图

这是一个简化的示例(dput用于重新创建 data.frame df),其中包含两组单元格和三个度量值,我想说 plot PeakagainstRisePeakagainst Decay。这很简单,但我想用 X 和 Y 误差线 (+/- sem) 添加表示组均值的点。

有没有办法在 ggplot2 中做到这一点,还是我需要先生成均值和 sem 值?这篇文章引起了我的注意,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 代码中打败了我。

4

1 回答 1

3

我倾向于将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))

在此处输入图像描述

我承认我有点失望,因为我不得不手动调整横杆高度。但仔细想想,我想实施起来可能相当具有挑战性。

于 2012-09-24T19:23:41.190 回答