问题描述:

(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 grid cells, across multiple months and seasons. The data for each month, season, etc., are in 8 separate columns; the loop would run through the columns of the data frame (DF)

Tried: Adding the plot from each iteration of the loop to a list so all plots can be called up to be displayed in a multipanel figure.

out <- NULL

for(i in 1:8){

D <- DF[,i]

x <- names(DF)[i]

p <-ggplot() + geom_polygon(data=DF, aes(x=long, y=lat, group=Name, fill=D), colour = "lightgrey") +labs(title=x)

out[[i]]<- p

print(p)

}

Problem: Even though the "print(p)" yields the correct plot for each iteration, the plots in the list "out" display the data from the final loop only.

So, when I try to use grid.arrange with plots in "out", all plots show the same data (from the 8th column); however, the plots do retain the correct title. When I try to call up each plot - e.g., print(out[[1]]), shows the same plot - except for the title label - as print(out[[8]]).

It seems that the previous elements in the list are being overwritten with each loop? However, the title of the plots seem to display correctly.

Is there something obviously wrong with how I'm constructing the "out" list? How can I avoid having each previous plot overwritten? Many thanks in advance!

网友答案:

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.

相关阅读:
Top