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

yoy*_*sef 14 visualization r histogram ggplot2

我正在使用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")
Run Code Online (Sandbox Code Playgroud)

我怎样才能使用每个面板组的意思作为x截距?(如果您还可以使用平均值的行添加文本标签,则可以获得奖励积分.)

Ale*_*own 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)
Run Code Online (Sandbox Code Playgroud)

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

或者使用plyr(require(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)
Run Code Online (Sandbox Code Playgroud)

看起来并不令人满意的是vline没有被切割,我不知道为什么.


Edu*_*oni 9

一种方法是使用手头的平均值构造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")
Run Code Online (Sandbox Code Playgroud)