2

我想使用 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)

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

4

2 回答 2

6

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

aes从你的删除geom_text将解决问题。aes应该用于将变量从data参数映射到美学。以任何不同的方式使用它,通过使用$或提供单个值可能会产生意想不到的结果。

代码

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

在此处输入图像描述

于 2016-03-31T10:26:04.327 回答
4

我不确定如何geom_text在 for 循环中使用,但您可以通过提前定义文本标签并改为使用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)
于 2016-03-31T10:20:02.247 回答