ggplot只打印灰色框到文件

时间:2016-10-15 21:40:09

标签: r ggplot2

所以SO确定我的图表工作,但现在我无法打印它!最终目标是我需要自动更新这些图,因此ggplot和print调用需要在函数中。当我运行此代码时,每个文件只包含一个灰色方块。

toyfn <- function(plotdata){
  library(ggplot2)
  plotS1 <- ggplot(plotdata) 
  plotS1 + geom_bar(aes(x=year,y=value,factor=variable,fill=variable, 
                        order=-as.numeric(variable)), stat="identity") +
    geom_line(data=linedata, aes(x=year,y=production))
  ggsave('testprint.png',plotS1)

  png(filename='testprint2.png')
  print(plotS1)
  dev.off()
}

library(ggplot2)
library(reshape)

# First let's make a toy dataset for our stacked plot/line plot example.
year = c(1,2,3,4,5,6)
stocks = c(2,4,3,2,4,3)
exports = stocks*2
domestic = stocks*3
production = c(15,16,15,16,15,16)

# Make 2 df's: alldata is for stacked bar chart, linedata is for plotting a line on top of it.
alldata = data.frame(year,stocks,exports,domestic)
linedata = data.frame(year,production)

# Make alldata 'long' for the stacking
melteddata = melt(alldata,id.vars="year")

toyfn(melteddata)

1 个答案:

答案 0 :(得分:1)

您正在保存没有geoms的地块。带有geoms的图表将显示在屏幕上,但不会显示在文件中。

试试这个:

toyfn <- function(plotdata){
    plotS1 <- ggplot(plotdata, aes(year, value, factor = variable, fill = variable)) + 
        geom_bar(stat="identity", aes(order = -as.numeric(variable))) +
        geom_line(data=linedata, aes(x=year,y=production))

    ggsave('testprint.png', plot = plotS1)
}