Using a calculated Vline across plots w facet_grid

702 views
Skip to first unread message

Michael Cawthon

unread,
Oct 24, 2014, 4:48:01 PM10/24/14
to ggplot2
I've added a vline which shows the mean of the x aesthetic to a
histogram, like so:

ggplot(mtcars, aes(x=mpg))
+geom_histogram()
+ geom_vline(xintercept = mean(mtcars$mpg), color = "blue")

If I apply a facet_grid, faceting by cyl, the overall mean is plotted
across all facets:

ggplot(mtcars, aes(x=mpg))
+geom_histogram()
+ geom_vline(xintercept = mean(mtcars$mpg), color = "blue")
+ facet_grid(~ cyl)

Problem: If I wanted the mean grouped by cylinder (ie, the 4 cylinder
facet shows the mean for just that subset, and so on), is there an
easy/obvious way to do this?


Dennis Murphy

unread,
Oct 24, 2014, 5:03:00 PM10/24/14
to Michael Cawthon, ggplot2
You need to create a data frame that contains the mean of mpg by cyl
and pass that to geom_vline(). Said data frame requires the faceting
variable cyl and the xintercept aesthetic maps to the mean value. I'd
also suggest taking the aesthetic mapping out of ggplot() and place it
in geom_histogram() instead. Something like

library(plyr)
library(ggplot2)

avgmpg <- plyr::ddply(mtcars, .(cyl), summarise, mean_mpg = mean(mpg))

ggplot(mtcars) +
geom_histogram(aes(x = mpg), fill = "darkorange") +
geom_vline(data = avgmpg, aes(xintercept = mean_mpg), size = 1.2) +
facet_wrap(~ cyl)

Dennis
> --
> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> Please provide a reproducible example:
> https://github.com/hadley/devtools/wiki/Reproducibility
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
>
> --- You received this message because you are subscribed to the Google
> Groups "ggplot2" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ggplot2+u...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Michael Cawthon

unread,
Oct 24, 2014, 5:42:55 PM10/24/14
to ggp...@googlegroups.com
Thank you very much.

Could you briefly explain your comment about the appropriate location
for the aesthetic mapping being inside geom_histogram? ie, are you
simply articulating a best practice of intuitively mapping aesthetics at
the layer that most explicitly draws them?
Reply all
Reply to author
Forward
0 new messages