YourEconProf YourEconProf - 11 days ago 4
R Question

ggplot only printing gray boxes to file

So SO nailed getting my graph to work, but now i can't get it to print! The end goal is that i need to automate the updating of these plots, so the ggplot and print calls need to be in a function. When i run this code, each file just contains a gray square.

toyfn <- function(plotdata){
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))



# 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")



You are saving a plot with no geoms. The plot with geoms will display on the screen, but not in the file.

Try this:

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)