(Very much a novice, so please excuse any confusion/obvious mistakes)
Goal: A loop that allows me to plot multiple maps, displaying density data (D
) for
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.
This also reproduces the same problem
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]])
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]])
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.