且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

循环中的多个绘图列表 (ggplot2) - 列表元素被覆盖

更新时间:2021-11-12 21:13:25

问题不在于每一项都被覆盖了,问题在于 ggplot() 一直等到你将绘图打印到解析 aes() 命令中的变量.循环将所有 fill= 参数分配给 D.并且 D 的值改变每个循环.然而,在循环结束时,D 将只有最后一个值.因此,列表中的每个图都将以相同的颜色打印.

The problem isn't that each item is over written, the problem is that ggplot() waits until you print the plot to resolve the variables in the aes() command. The loop is assigning all fill= parameters to D. And the value of D changes each loop. However, at the end of the loop, D will only have the last value. Thus each of the plots in the list will print with the same coloring.

这也重现了同样的问题

require(ggplot2)

#sample data
dd<-data.frame(x=1:10, y=runif(10), g1=sample(letters[1:2], 10, replace=T), g2=sample(letters[3:4], 10, replace=T))

plots<-list()
g<-dd$g1
plots[[1]]<-ggplot(data=dd, aes(x=x, y=y, color=g)) + geom_point()

g<-dd$g2
plots[[2]]<-ggplot(data=dd, aes(x=x, y=y, color=g)) + geom_point()

#both will print with the same groups.
print(plots[[1]])
print(plots[[2]])

解决此问题的一种方法(@baptiste 也提到)是使用 aes_string().这可以更快地"解析变量的值所以这应该有效

One way around this as ( @baptiste also mentioned ) is by using aes_string(). This resolves the value of the variable "more quickly" So this should work

plots<-list()
g<-"g1"
plots[[1]]<-ggplot(data=dd, aes(x=x, y=y)) + geom_point(aes_string(color=g))
g<-"g2"
plots[[2]]<-ggplot(data=dd, aes(x=x, y=y)) + geom_point(aes_string(color=g))

#different groupings (as desired)
print(plots[[1]])
print(plots[[2]])

这与 aes() 函数最直接相关,因此您设置标题的方式很好,这就是您看到不同标题的原因.

This is most directly related to the aes() function, so the way you are setting the title is just fine which is why you see different titles.