List for Multiple Plots from Loop (ggplot2) - List elements being overwritten

后端 未结 1 1122
清歌不尽
清歌不尽 2020-11-30 12:12

(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

相关标签:
1条回答
  • 2020-11-30 12:48

    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.

    0 讨论(0)
提交回复
热议问题