2

I want to display a list of text labels on a ggplot graph with the geom_text() function.

The positions of those labels are stored in a list.

When using the code below, only the second label appears.

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)

Any idea what is wrong with this code?

Ben
  • 6,321
  • 9
  • 40
  • 76

2 Answers2

8

I agree with @user2728808 answer as a good solution, but here is what was wrong with your code.

Removing the aes from your geom_text will solve the problem. aes should be used for mapping variables from the data argument to aesthetics. Using it any differently, either by using $ or supplying single values can give unexpected results.

Code

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

enter image description here

Axeman
  • 32,068
  • 8
  • 81
  • 94
4

I'm not exactly sure how geom_text can be used within a for-loop, but you can achieve the desired result by defining the text labels in advance and using annotate instead. See the code below.

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)
user2728808
  • 560
  • 3
  • 18