Thomas Philips
Thomas Philips

Reputation: 1089

ggsave creates an empty png file

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

Upvotes: 0

Views: 1401

Answers (1)

warnbergg
warnbergg

Reputation: 552

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.

Upvotes: 1

Related Questions