This question already has an answer here:
Closed 5 years ago.
This loop creates a list of 3 ggplots, but because the arguments for x
and xend
depend on the index of the loop, dismay follows:
DF <- data.frame(column1=c(1,2,3,4,5), column2=c(4,5,6,7,8))
list_of_ggplots <- list()
for (num in seq(1:3)){
p <- ggplot()
p <- p + geom_segment(data=DF, aes(x=column1[num], xend=column2[num], y=1, yend=1))
list_of_ggplots[[num]] <- p }
list_of_ggplots
We get 3 plots being fundamentally the same plot (since at the point in time they are called, num
is 3).
What could be a better strategy to create these plots?
You can get a list without running explicit loops by using lapply
:
list_of_ggplots <- lapply(1:nrow(DF), function(i) {ggplot(DF[i,]) + aes(x=column1, xend=column2, y=1, yend=1)+geom_segment()})
you can make the list in a more "R"-like way with lapply
and then just subset DF
with num
vs trying to do so in the aesthetics. However, you should also use scale_x_continuous
and set the limits
, otherwise they'll all still "look" the same (except for the #'s on the x axis)
list_of_ggplots <- lapply(1:nrow(DF), function(num) {
p <- ggplot()
p <- p + geom_segment(data=DF[num,], aes(x=column1, xend=column2, y=1, yend=1))
p + scale_x_continuous(limits=c(0, max(DF$column2)))
})