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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is a nice answer, as it deals specifically with the loop aspect of the question.
5

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.