0

I'm trying to save a plot that I create using the following code, but consistently get an empty .png file. I reuse some existing code to create the plot, and import tidyverse to access a number of functions, including ggsave(). Why doesn't ggsave() create a png file with a scatter plot and a overlaid line, both of which are visible in my Rstudio graphics window? Why does it instead but consistently create an empty .png file? What am I doing wrong?

    # Regress 10-year S&P return versus Fwd_EY and Fwd_EY^2

plot(data$Fwd_EY, data$SPRet, pch = 16, col = "blue", xlab = "E_t+1/P", ylab = "10-year Return")
fit <- lm(data$SPRet ~ data$Fwd_EY)

# Use predict to calculate predicted returns
predict_ret <- predict(fit, data) 

# abline doesn't work; plot predicted returns as a separate line
lines(data$Fwd_EY, predict_ret, col = "gold4", type = "b", cex = 0.7) 

#Now save the plot using ggsave
ggsave(filename = "C:/Temp/SP10YrVsForwardPE.png", device = png())
dev.off()

Sincerely

Thomas Philips

Thomas Philips
  • 935
  • 2
  • 11
  • 22
  • maybe you forgot to add either `plot = last_plot()` or you give your plot a *name* and exchange *last_plot()* by the *name*. You can also leave the *device* call out as long as you specify *png* in the filename. You do not need `dev.off()`. – MarBlo Jun 21 '20 at 05:14

1 Answers1

1

Try using

# Instantiate the plot object
png('C:/Temp/SP10YrVsForwardPE.png')

# Regress 10-year S&P return versus Fwd_EY and Fwd_EY^2
plot(data$Fwd_EY, data$SPRet, pch = 16, col = "blue", xlab = "E_t+1/P", ylab = "10-year Return")
fit <- lm(data$SPRet ~ data$Fwd_EY)

# Use predict to calculate predicted returns
predict_ret <- predict(fit, data) 

# abline doesn't work; plot predicted returns as a separate line
lines(data$Fwd_EY, predict_ret, col = "gold4", type = "b", cex = 0.7) 

dev.off()

which utilises the built in method instead of ggsave.

warnbergg
  • 552
  • 4
  • 14
  • Works like a charm - thanks a mill. Interestingly it both plots on my screen and writes to the file, which seems a bit mysterious. Is there a simple explanation for why it does both? – Thomas Philips Jun 21 '20 at 05:55
  • @ThomasPhilips This method is used to save the plot to disk, as is ggsave. Not sure how to achieve one or the other actually. – warnbergg Jun 21 '20 at 06:05
  • @ThomasPhilips If the answer satifies your case, please consider accepting the answer – warnbergg Jun 21 '20 at 06:36