2

So I have a faceted graph, and I want to be able to add lines to it that change by each facet.

Here's the code:

p <- ggplot(mtcars, aes(x=wt))+
  geom_histogram(bins = 20,aes(fill = factor(cyl)))+
  facet_grid(.~cyl)+
  scale_color_manual(values = c('red','green','blue'))+
  geom_vline(xintercept = mean(mtcars$wt))

p

So my question is, how would I get it so that the graph is showing the mean of each faceted sub-graph.

I hope that makes sense and appreciate your time regardless of your answering capability.

camille
  • 16,432
  • 18
  • 38
  • 60
L.Zingg
  • 85
  • 1
  • 10
  • Would you consider calculating means separately (summarize) and then setting `xintercept` to that? Seems like that might be reasonable. – Ben Sep 27 '19 at 22:01

1 Answers1

3

You can do this within the ggplot call by using stat_summaryh from the ggstance package. In the code below, I've also changed scale_colour_manual to scale_fill_manual on the assumption that you were trying to set the fill colors of the histogram bars:

library(tidyverse)
library(ggstance)

ggplot(mtcars, aes(x=wt))+
  geom_histogram(bins = 20,aes(fill = factor(cyl)))+
  stat_summaryh(fun.x=mean, geom="vline", aes(xintercept=..x.., y=0), 
                colour="grey40") +
  facet_grid(.~cyl)+
  scale_fill_manual(values = c('red','green','blue')) +
  theme_bw()

enter image description here

Another option is to calculate the desired means within geom_vline (this is an implementation of the summary approach that @Ben suggested). In the code below, the . is a "pronoun" that refers to the data frame (mtcars in this case) that was fed into ggplot:

ggplot(mtcars, aes(x=wt))+
  geom_histogram(bins = 20,aes(fill = factor(cyl)))+
  geom_vline(data = . %>% group_by(cyl) %>% summarise(wt=mean(wt)), 
             aes(xintercept=wt), colour="grey40") +
  facet_grid(.~cyl)+
  scale_fill_manual(values = c('red','green','blue')) +
  theme_bw()
eipi10
  • 91,525
  • 24
  • 209
  • 285