将静态ggplot存储为R中的变量值

时间:2015-03-31 14:23:00

标签: r ggplot2

我在for循环中创建多个ggplots,将它们存储在列表中。 我的问题是,我传递给ggplot的“data”参数在每次迭代时都会发生变化,因此当我稍后打印这些图时,它们都会打印出“data”数据帧的最后一个版本。

我想要做的是将ggplot静态保存到变量(按值),以便不会重新评估打印的“数据”。 任何想法?

举个例子,如果我将查看列表中的每个ggplot,它将使用'scaleBounds'的最后一个版本(来自最后一次迭代)是ggplot的'data'。

我的代码:

scalePlotList <- list()
for (i in 1:number_of_scales)
  {
    plot.new()
    row <- df[i,]

    min <- row$min
    max <- row$max
    you <- max(min(row$your_business,max),min)
    pinSeq <- seq(from=min,to=max,length.out=6)

    scaleBounds <-data.frame(x=c(pinSeq[1],pinSeq[2],pinSeq[2],pinSeq[1],pinSeq[2],pinSeq[3],pinSeq[3],pinSeq[2],pinSeq[3],pinSeq[4],pinSeq[4], pinSeq[3],pinSeq[4],pinSeq[5],pinSeq[5],pinSeq[4],pinSeq[5], pinSeq[6], pinSeq[6], pinSeq[5]),
                            y=c( 0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1 ),
                            t=c( 1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4, 5,5,5,5 ))

    currentPlot <- ggplot() + 
      geom_polygon(data=scaleBounds, mapping=aes(x=x,y=y,group=t,fill=-t)) + 
      scale_colour_brewer() +
      labs(x="",y="") +
      ylim(0,1.5) +
      geom_segment(aes(x=you,y=0,xend=you,yend=1.2), colour="#3d3d3d", size=3, lineend = "round") +
      geom_text(label="min", aes(x=pinSeq[1], y=0), size=5, colour="#fcfcfc", fontface="bold", hjust=-0.1, vjust=-.7) + 
      geom_text(label="max", aes(x=pinSeq[6], y=0), size=5, colour="#fafafa", fontface="bold", hjust=1.1, vjust=-.7) +
      geom_text(label="you", aes(x=you, y=.5), size=8, colour="#fafafa", fontface="bold", hjust=-0.1) +
      theme_nothing()

      scalePlotList[[length(scalePlotList)+1]] <- currentPlot

    }

0 个答案:

没有答案
相关问题