【问题标题】:How can I place a text on a plot (ggplot2) without knowing the exact coordinates of the plot?如何在不知道绘图的确切坐标的情况下将文本放在绘图 (ggplot2) 上?
【发布时间】:2021-12-16 03:10:42
【问题描述】:

我有一个情节 g 制作的:

library(ggplot2)

g = ggplot(mtcars, aes(mpg, cyl)) +
        geom_point()

现在,我想使用annotate(或其他任何东西)在绘图中添加文本。我特别希望文本出现在绘图的左下角。

这行得通:

g + annotate("text", x = 12, y = 4, label = "Boring Label")

但是,这种方法的问题是我必须知道绘图坐标 (x = 12, y = 4) 才能将文本放置在绘图的左下角。我将为许多不同的绘图自动执行此过程,并且我想将相同的文本放置在同一位置(左下角)而不知道绘图的最小和最大坐标。例如,c(0.3, 0.1)c(x = 0.3, y = 0.1)(0 = 最小值,x 和 y 最大值为 1)会非常有用。但这不适用于annotate("text", x = 0.3, y = 0.1, label = "Boring Label")

【问题讨论】:

标签: r ggplot2 plot


【解决方案1】:

您可以尝试这种方法,按每个变量的最大值缩放位置。当然,您可以根据您希望文本所在的位置更改0.95 的值。

ggplot(mtcars, aes(mpg, cyl)) +
        geom_point() +
        annotate("text", x = max(mtcars$mpg) * 0.95, y = max(mtcars$cyl) * 0.95, label = "Boring Label")

【讨论】:

    【解决方案2】:

    您可以使用library(ggpp):以 npc 为单位指定文本位置:

    g + ggpp::geom_text_npc(aes(npcx = x, npcy = y, label=label), 
                      data = data.frame(x = 0.05, y = 0.05, label='Boring label'))
    

    【讨论】:

      猜你喜欢
      • 2013-10-30
      • 2019-08-07
      • 2013-07-24
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      相关资源
      最近更新 更多