在ggplot2中为每个面板添加具有不同截距的垂直线

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轴截距?(如果您还可以在线条旁边添加一个文本标签,显示均值的值,则可获得额外的积分。)

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)

alt text http://www.imagechicken.com/uploads/1264782634003683000.png

或者使用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没有在图形的分面上被截断,我不确定原因。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接