How to custom add vertical lines to ggplot facet function?

浪子不回头ぞ 提交于 2021-02-08 03:00:56

问题


I have a dataset where each species was mixed with a certain density (numeric) and type (numeric) of another species. I want to add two types of vertical lines to each of my facet_grid panels in ggplot: (a) A fixed line which dives the density/ type. e.g. 1000/1 = 1000, 1000/6 = 166.7, 10000/1 = 10000, 10000/6 = 1666.7

(b) The bootstrapped mean AND confidence interval for each treatment overlayed on the histogram. I tried adding the mean using geom_vline but it doesn't seem right. It looks like all the means are identical

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)

回答1:


I'm not sure why this is the default behaviour on faceting, but I think the way round it is to pass summarised data to geom_vline. One way is as follows (changes to your code in the final term)...

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)

(I've reinstated the grid lines so that you can see that the line does move a little bit!)



来源:https://stackoverflow.com/questions/64228622/how-to-custom-add-vertical-lines-to-ggplot-facet-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!