What's the best way to annotate this ggplot2 plot? [R]

Here's the 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 experimented with the geom_hline tag in several ways, each of which does something I want, but has a problem that other methods don't. annotate()

used above is good - the text is resizable, black and easy to place. But it can only be placed inside the plot, and not outside the plot like axis labels. It also makes the "a" appear in the legend, which I can't dismiss with legend = FALSE

.

legend = FALSE

works with geom_text

, but I can't get the geom_text to just be black - it seems to get confused about the line coloring.

grid.text

allows me to place text anywhere, but I cannot resize it.

I can definitely accept text within the plot area, but I would like to keep the legend clean. I feel like I'm missing something simple, but I'm just fired up. Thank you in advance for your attention.

+2


a source to share


2 answers


The aesthetics specified in the initial call to ggplot () are propagated across all geoms. But if you don't like it, you can specify the aesthetics on any layer.



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

+4


a source


Oh ... well. I answered my own question, to make it sketch like an axis label, 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 answer if you have any other thoughts.

+2


a source







All Articles