【问题标题】:Add text outside plot area在绘图区域外添加文本
【发布时间】:2019-02-19 22:50:59
【问题描述】:

示例代码

library(ggplot2)
ggplot(mtcars, aes(mpg, cyl, color = vs)) + geom_line()

如果可以在 x 轴上添加任意文本,就像使用上面的图制作的示例一样,然后我在上面写了“任意词”

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我不完全确定您要做什么,因此这可能会或可能不会很好地概括。

    也就是说,一种可能性是使用 annotatecoord_cartesian(clip = "off") 以允许在绘图区域之外显示文本。

    ggplot(mtcars, aes(mpg, cyl, color = vs)) +
        geom_line() +
        annotate("text", x = 12.5, y = 3.5, label = "Arbitrary text") +
        coord_cartesian(ylim = c(4, 8), clip = "off")
    

    【讨论】:

    • 非常感谢,这真的很接近,但是我怎样才能将它与 x 刻度线值 10 和 15 对齐,所以它在中间左右?
    • 嗨@bvowe;我认为您唯一的选择是通过在annotate 中设置xy 来手动调整位置。
    【解决方案2】:

    您可以在ggplot2 中使用tag(参见?ggplot2::labs)并在theme 中指定它的位置

    library(ggplot2)
    ggplot(mtcars, aes(mpg, cyl, color = vs)) + 
        geom_line() +
        labs(tag = "arbitrary words") +
        theme(plot.tag.position = c(0.15, 0.02))
    

    【讨论】:

    • 太好了,你拯救了我的一天
    • 可以添加多个标签吗?
    猜你喜欢
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 2015-12-16
    • 2015-11-10
    相关资源
    最近更新 更多