简体   繁体   English

注释此ggplot2图的最佳方法是什么? [R]

[英]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. 我一直在尝试以几种不同的方式标记geom_hline,每种方式都可以实现我想要的功能,但是存在其他方法所没有的问题。 annotate() , used above, is nice - the text is resizeable, black, and easy to position. 上面使用的annotate()很不错-文本是可调整大小的,黑色的,并且易于放置。 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 . 这也会使图例中出现一个“ a”,我不能用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. legend = FALSE适用于geom_text ,但是我不能让geom_text变成黑色-似乎在线条着色中纠结了。

grid.text lets me put the text anywhere I want, but I can't seem to resize it. grid.text使我可以将文本放置在所需的任何位置,但似乎无法调整其大小。

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. 预先感谢您的考虑。

Aesthetics specified in the initial ggplot() call are propagated down through all of the geoms. 最初的ggplot()调用中指定的美学在所有几何图形中向下传播。 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. 因此,要防止geom_text继承颜色美感,只需从ggplot()调用的aes()中删除“颜色”,然后在两个stat_smooth()调用中包含对aes(color = factor(am))的调用。

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. 如果您有其他想法,请回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM