开发者

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

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开发者_JS百科 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.


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.


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)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜