注释这个 ggplot2 图的最佳方法是什么? [R]
这是一个情节:
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)
我一直在尝试以几种不同的方式标记 geom_hline,每种方式都可以完成我想要的事情,但都存在其他方法没有的问题。上面使用的 annotate()
很好 - 文本可以调整大小,黑色,并且易于定位。但它只能放置在绘图本身内,而不能像轴标签一样放置在绘图之外。它还使图例中出现一个“a”,我无法使用 legend = FALSE
将其忽略。
legend = FALSE
与 geom_text
一起使用,但我无法让 geom_text 只是黑色 - 它似乎与线条颜色纠缠在一起。
grid.text 允许我将文本放置在我想要的任何位置,但我似乎无法调整它的大小。
我绝对可以接受绘图区域内的文本,但我想保持图例干净。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
初始 ggplot() 调用中指定的美学会向下传播到所有几何图形。但如果您不喜欢它,您可以在任何图层中指定美观性。
因此,为了防止 geom_text 继承颜色美感,只需从 ggplot() 调用的 aes() 中删除“color”,并在两个 stat_smooth() 调用中包含对 aes(color=factor(am)) 的调用。
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: