【问题标题】:Using geom_text in a for loop with ggplot2在 ggplot2 的 for 循环中使用 geom_text
【发布时间】:2016-07-19 15:52:42
【问题描述】:

我想使用 geom_text() 函数在 ggplot 图上显示文本标签列表。

这些标签的位置存储在一个列表中。

使用下面的代码时,只出现第二个标签。

x <- seq(0, 10, by = 0.1)
y <- sin(x)
df <- data.frame(x, y)
g <- ggplot(data = df, aes(x, y)) + geom_line()

pos.x <- list(5, 6)
pos.y <- list(0, 0.5)

for (i in 1:2) {
  g <- g + geom_text(aes(x = pos.x[[i]], y = pos.y[[i]], label = paste("Test", i)))
}

print(g)

知道这段代码有什么问题吗?

【问题讨论】:

    标签: r ggplot2 geom-text


    【解决方案1】:

    我同意@user2728808 的回答是一个很好的解决方案,但这是您的代码有问题的地方。

    从您的geom_text 中删除aes 将解决问题。 aes 应该用于将变量从 data 参数映射到美学。以任何不同的方式使用它,无论是使用$ 还是提供单个值都会产生意想不到的结果。

    代码

    for (i in 1:2) {
      g <- g + geom_text(x = pos.x[[i]], y = pos.y[[i]], label = paste("Test", i))
    }
    

    【讨论】:

    • 这是一个很好的答案,因为它专门处理问题的循环方面。
    【解决方案2】:

    我不确定如何在 for 循环中使用 geom_text,但您可以通过提前定义文本标签并改用 annotate 来获得所需的结果。请参阅下面的代码。

    library(ggplot2)
    x <- seq(0, 10, by = 0.1)
    y <- sin(x)
    df <- data.frame(x, y)
    
    pos.x <- c(5, 6)
    pos.y <- c(0, 0.5)
    titles <- paste("Test",1:2)
    ggplot(data = df, aes(x, y)) + geom_line() + 
    annotate("text", x = pos.x, y = pos.y, label = titles)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多