分配循环不适用于情节 [英] assign loop not working for plot
问题描述
循环的每次迭代都会创建一个新的plotx.当我运行print(plotx)时,它会生成不同的图形,因此效果很好.
Each iteration of the loop creates a new plotx. This works fine as when I run print(plotx) it produces a different graph.
然后,我使用assign调用每个图"plotx1","plotx2"等.以将每个图另存为单独的名称.然后,当我绘制名称图时,它们都与Y = c相同,但是y轴正确标记了循环的原始Y!这是怎么回事?我该如何纠正?
I then used assign to call each plot "plotx1","plotx2" etc..to save each plot as a separate name. When I then plot the names plots they are all identical to Y=c BUT the y axis is correctly labelled with the original Y for the loop! Whats going on? How do I correct this?
dat = data.frame("d"= rep(c("bla1","bla2","bla3"),3),"a" = c(1:9), "b"=
c(19:11), "c"=rep(c(3,2,2),3))
X = "d"
listY = c("a","b","c")
z= 0
for (Y in listY){
z= z+1
plotx= ggplot(dat,
aes(x = dat[[X]], y = dat[[Y]])) +
geom_boxplot() +
scale_x_discrete(X) +
scale_y_continuous(Y)+
theme_bw()
print(plotx)
plot_name = paste0("plotx",z)
assign(plot_name , plotx)
}
plotx1
plotx2
plotx3
推荐答案
此行为的原因由@Roland解释.如果您以后想访问它们,则应该使用列表来存储它们.另外,在传递 x
和 y
的字符串时,应该使用 aes_string
而不是 aes
.这是一个工作代码:
The reason for this behavior is explained by @Roland. You should use a list to store the plots if you want to access them later. In addition, you should be using aes_string
instead of aes
as you are passing strings for x
and y
. Here is a working code:
dat = data.frame("d"= rep(c("bla1","bla2","bla3"),3),"a" = c(1:9), "b"=
c(19:11), "c"=rep(c(3,2,2),3))
X = "d"
listY = c("a","b","c")
z= 0
plots <- list()
for (Y in listY){
z= z+1
plotx <- ggplot(dat,
aes_string(x = dat[[X]], y = dat[[Y]])) +
geom_boxplot() +
scale_x_discrete(X) +
scale_y_continuous(Y)+
theme_bw()
plot_name <- paste0("plotx",z)
plots[[plot_name]] <- plotx
}
然后,您可以使用 plots ["plotx1"]
这篇关于分配循环不适用于情节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!