Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I overlay by-group plot elements to ggplot2 facets?
    text
    copied!<p>My question has to do with facetting. In my example code below, I look at some facetted scatterplots, then try to overlay information (in this case, mean lines) on a per-facet basis.</p> <p>The tl;dr version is that my attempts fail. Either my added mean lines compute across all data (disrespecting the facet variable), or I try to write a formula and R throws an error, followed by incisive and particularly disparaging comments about my mother.</p> <pre><code>library(ggplot2) # Let's pretend we're exploring the relationship between a car's weight and its # horsepower, using some sample data p &lt;- ggplot() p &lt;- p + geom_point(aes(x = wt, y = hp), data = mtcars) print(p) # Hmm. A quick check of the data reveals that car weights can differ wildly, by almost # a thousand pounds. head(mtcars) # Does the difference matter? It might, especially if most 8-cylinder cars are heavy, # and most 4-cylinder cars are light. ColorBrewer to the rescue! p &lt;- p + aes(color = factor(cyl)) p &lt;- p + scale_color_brewer(pal = "Set1") print(p) # At this point, what would be great is if we could more strongly visually separate # the cars out by their engine blocks. p &lt;- p + facet_grid(~ cyl) print(p) # Ah! Now we can see (given the fixed scales) that the 4-cylinder cars flock to the # left on weight measures, while the 8-cylinder cars flock right. But you know what # would be REALLY awesome? If we could visually compare the means of the car groups. p.with.means &lt;- p + geom_hline( aes(yintercept = mean(hp)), data = mtcars ) print(p.with.means) # Wait, that's not right. That's not right at all. The green (8-cylinder) cars are all above the # average for their group. Are they somehow made in an auto plant in Lake Wobegon, MN? Obviously, # I meant to draw mean lines factored by GROUP. Except also obviously, since the code below will # print an error, I don't know how. p.with.non.lake.wobegon.means &lt;- p + geom_hline( aes(yintercept = mean(hp) ~ cyl), data = mtcars ) print(p.with.non.lake.wobegon.means) </code></pre> <p>There <em>must</em> be some simple solution I'm missing.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload