【问题标题】:How to custom add vertical lines to ggplot facet function?如何自定义将垂直线添加到 ggplot facet 函数?
【发布时间】:2021-01-21 11:59:40
【问题描述】:

我有一个数据集,其中每个物种都与另一个物种的一定密度(数字)和类型(数字)混合。我想在 ggplot 中的每个 facet_grid 面板中添加两种类型的垂直线: (a) 一条划分密度/类型的固定线路。例如1000/1 = 1000, 1000/6 = 166.7, 10000/1 = 10000, 10000/6 = 1666.7

(b) 叠加在直方图上的每个处理的自举平均 AND 置信区间。 我尝试使用 geom_vline 添加平均值,但它似乎不正确。看起来所有的手段都是一样的

set.seed(111)
count <- rbinom(500,100,0.1) 
species <- rep(c("A","B"),time = 250)
density <- rep(c("1000","10000","1000","10000"),time = 125)
type <- rep(c("1","1","6","6"),time = 125)
df <- data.frame(species, density, type, count) # I feel too naiive, but I'm not able to get all the treatments filled. Gah.

ggplot(df, aes(x= count, colour = species, fill = species)) + 
   geom_histogram(position="identity", alpha=0.5) + 
   theme_bw() + ylab("Frequency") + 
   facet_grid(species ~ type + density) + 
   theme(panel.grid.major = element_blank(),
         panel.grid.minor = element_blank()) +
   theme(legend.position = "none") + theme(aspect.ratio = 1.75/1) + 
   geom_vline(aes(xintercept=mean(count)),color="blue", linetype="dashed", size=1)

【问题讨论】:

    标签: r ggplot2 mean confidence-interval


    【解决方案1】:

    我不确定为什么这是分面的默认行为,但我认为解决方法是将汇总数据传递给geom_vline。一种方式如下(在期末修改你的代码)...

    ggplot(df, aes(x= count, colour = species, fill = species)) + 
      geom_histogram(position="identity", alpha=0.5) + 
      theme_bw() + ylab("Frequency") + 
      facet_grid(species ~ type + density) + 
      theme(legend.position = "none") + theme(aspect.ratio = 1.75/1) + 
      geom_vline(data = function(x) x %>% 
                   group_by(species, type, density) %>% 
                   summarise(meancount = mean(count)),
                 aes(xintercept=meancount),color="blue", linetype="dashed", size=1)
    

    (我已经恢复了网格线,以便您可以看到线条确实移动了一点!)

    【讨论】:

      猜你喜欢
      • 2019-05-05
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 2012-06-28
      • 1970-01-01
      相关资源
      最近更新 更多