Rspacer
Rspacer

Reputation: 2429

How to custom add vertical lines to ggplot facet function?

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)

Upvotes: 2

Views: 1303

Answers (1)

Andrew Gustar
Andrew Gustar

Reputation: 18425

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

enter image description here

Upvotes: 2

Related Questions