views:

230

answers:

2

Here's a plot:

library(ggplot2)
ggplot(mtcars, aes(x = factor(cyl), y = hp, group = factor(am), color = factor(am))) +
    stat_smooth(fun.data = "mean_cl_boot", geom = "pointrange") +
    stat_smooth(fun.data = "mean_cl_boot", geom = "line") +
    geom_hline(yintercept = 130, color = "red") +
    annotate("text", label = "130 hp", x = .22, y = 135, size = 4)

I've been experimenting with labeling the geom_hline in a few different ways, each of which does something I want but has a problem that the other methods don't have. annotate(), used above, is nice - the text is resizeable, black, and easy to position. But it can only be placed within the plot itself, not outside the plot like the axis labels. It also makes an "a" appear in the legend, which I can't dismiss with legend = FALSE.

legend = FALSE works with geom_text, but I can't get geom_text to just be black - it seems to be getting tangled up in the line colorings.

grid.text lets me put the text anywhere I want, but I can't seem to resize it.

I can definitely accept the text being inside of the plot area, but I'd like to keep the legend clean. I feel like I'm missing something simple, but I'm just fried. Thanks in advance for your consideration.

A: 

Oh... well. I answered my own question: to make it plot like the axis labels, make it an axis label:

ggplot(mtcars, aes(x = factor(cyl), y = hp, group = factor(am), color = factor(am))) +
    stat_smooth(fun.data = "mean_cl_boot", geom = "pointrange") +
    stat_smooth(fun.data = "mean_cl_boot", geom = "line") +
    geom_hline(yintercept = 130, color = "red") +
    scale_y_continuous(breaks =  c(0, 50, 100, 130, seq(150, 400, 50)))

Please do answer if you have other thoughts.

Matt Parker
+1  A: 

Aesthetics specified in the initial ggplot() call are propagated down through all of the geoms. But if you don't like it you can specify aesthetics in any layer instead.

So, to prevent geom_text from inheriting the color aesthetic, simply remove "color" from the aes() of your ggplot() call and include a call to aes(color=factor(am)) within your two stat_smooth() calls.

Owen
That makes sense. I think I had tried to override the color from within the annotate, but just specifying it within the geoms that use it seems more appropriate. Thanks.
Matt Parker