我想使用 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)
知道这段代码有什么问题吗?
最佳答案
我同意@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))
}
关于r - 在 ggplot2 的 for 循环中使用 geom_text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36329246/