15

我正在使用 ggplot2 创建直方图面板,并且我希望能够在每个组的平均值处添加一条垂直线。但是 geom_vline() 对每个面板使用相同的截距(即全局平均值):

require("ggplot2")
# setup some sample data
N <- 1000
cat1 <- sample(c("a","b","c"), N, replace=T)
cat2 <- sample(c("x","y","z"), N, replace=T)
val <- rnorm(N) + as.numeric(factor(cat1)) + as.numeric(factor(cat2))
df <- data.frame(cat1, cat2, val)

# draws a single histogram with vline at mean
qplot(val, data=df, geom="histogram", binwidth=0.2) + 
  geom_vline(xintercept=mean(val), color="red")

# draws panel of histograms with vlines at global mean
qplot(val, data=df, geom="histogram", binwidth=0.2, facets=cat1~cat2) + 
  geom_vline(xintercept=mean(val), color="red")

我怎样才能让它使用每个面板的组平均值作为 x 截距?(如果您还可以在具有平均值的行旁边添加文本标签,则可以加分。)

4

2 回答 2

15

我想这实际上是对@eduardo 的重新设计,但在一行中。

ggplot(df) + geom_histogram(mapping=aes(x=val)) 
  + geom_vline(data=aggregate(df[3], df[c(1,2)], mean), 
      mapping=aes(xintercept=val), color="red") 
  + facet_grid(cat1~cat2)

替代文字 http://www.imagechicken.com/uploads/1264782634003683000.png

或使用plyrrequire(plyr)ggplot 的作者 Hadley 的一个包):

ggplot(df) + geom_histogram(mapping=aes(x=val)) 
  + geom_vline(data=ddply(df, cat1~cat2, numcolwise(mean)), 
      mapping=aes(xintercept=val), color="red") 
  + facet_grid(cat1~cat2)

vline 在各个方面没有被削减似乎令人不满意,我不知道为什么。

于 2010-01-29T15:21:39.053 回答
10

一种方法是事先用平均值构造 data.frame。

library(reshape)
dfs <- recast(data.frame(cat1, cat2, val), cat1+cat2~variable, fun.aggregate=mean)
qplot(val, data=df, geom="histogram", binwidth=0.2, facets=cat1~cat2) + geom_vline(data=dfs, aes(xintercept=val), colour="red") + geom_text(data=dfs, aes(x=val+1, y=1, label=round(val,1)), size=4, colour="red")
于 2009-10-29T17:05:30.047 回答