首页 文章

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

提问于
浏览
2

这是一个情节:

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)

我有'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' . annotate() ,上面使用的很好 - 文本可调整大小,黑色,易于定位 . 但它只能放在绘图本身内,而不是像轴标签那样位于绘图之外 . 它也会使"a"出现在图例中,我无法用 legend = FALSE 解雇 .

legend = FALSEgeom_text 一起使用,但是我不能让geom_text变成黑色 - 它似乎在线条色彩中纠缠不清 .

grid.text 让我把文字放在我想要的任何地方,但我似乎无法调整大小 .

我绝对可以接受在情节区域内的文字,但我想保持传说清洁 . 我觉得我错过了一些简单的东西,但我只是在炒 . 在此先感谢您的考虑 .

2 回答

  • 2

    初始ggplot()调用中指定的美学向下传播到所有geom . 但如果你不喜欢它,你可以在任何层中指定美学 .

    因此,为了防止geom_text继承颜色审美,只需从ggplot()调用的aes()中删除“color”,并在两个stat_smooth()调用中包含对aes(color = factor(am))的调用 .

  • 4

    那好吧 . 我回答了我自己的问题:要使其像轴标签一样绘制,使其成为轴标签:

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

    如果您有其他想法,请回答 .

相关问题