在循环中创建一个ggplots列表,使用循环的索引作为geom函数的参数 [英] Creating a list of ggplots in a loop, using the index of the loop as an argument to the geom function
问题描述
这个循环创建了3个ggplots的列表,但是因为 x
和 xend
的参数依赖于索引如下所示:
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
我们得到3个地块基本上是同一个地块(因为在他们被调用的时候, num
是3)。
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?
推荐答案
你可以用 lapply
然后只是子集 DF
与 num
vs试图在审美中这样做。但是,您还应该使用 scale_x_continuous
并设置 limits ,否则它们仍然会看上去一样除了x轴上的#)
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)))
})
这篇关于在循环中创建一个ggplots列表,使用循环的索引作为geom函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!