Add a vertical line with different intercept for each panel in ggplot2

前端 未结 2 1863
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 12:32

I\'m using ggplot2 to create panels of histograms, and I\'d like to be able to add a vertical line at the mean of each group. But geom_vline() uses the same intercept for each

相关标签:
2条回答
  • 2021-02-05 12:51

    One way is to construct the data.frame with the mean values before hand.

    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")
    
    0 讨论(0)
  • 2021-02-05 12:53

    I guess this is a reworking of @eduardo's really, but in one line.

    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

    or using plyr (require(plyr) a package by the author of 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)
    

    It seems unsatisfying that vline isn't cut on the facets, I'm not sure why.

    0 讨论(0)
提交回复
热议问题