Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I want to save a plot that has been created using the following code however I am consistently getting an empty .png file. Kindly correct the code.

The code that I have implemented:

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

1 Answer

0 votes
by (107k points)

I think you can use the built-in method instead of ggsave, like the below code:

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

If you are a beginner and want to know more about R then do refer to the R programming course

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...