Saving a Plot in R (With Examples)
In this article, we will be looking at the approach to save plots in data objects in R Programming Language.
Using recordPlot() function
This approach is the easiest way to save any type of plot given in the data object form using the recordPlot() function. In this approach, to save the plot in the data object form user needs to all the recordPlot() functions with an object where the user needs to save the given plot, and this will automatically map the plot with the object and the given plot will be saved into the object and further, when the user needs to open the plot, the user just have to call the name of the object mapped to the particular object and the plot will be displayed on the screen.
Syntax: recordPlot(load=NULL, attach=NULL)
Parameters:
- load: If not NULL, a character vector of package names, which are saved as part of the recorded plot.
- attach: If not NULL, a character vector of package names, which are saved as part of the recorded plot.
Save Plot in R
In this example, we will be simply creating a line plot and further will be saving this plot to the data object name GFG, and then clearing the plot window and then check the saved plot in the object using the recordPlot() functions , we will be calling this object in the R programming language.
R
x = c (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
y = c (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
plot (x, y, col = "blue" , pch = 16, main = "Scatter Plot of x and y" ,
xlab = "Variable X" , ylab = "Variable Y" )
abline (h = mean (y), col = "red" , lty = 2)
text (7, 6, "Mean of Y" , col = "red" , pos = 4)
res = recordPlot ()
plot.new ()
res
|
Output:
Save Plot in R
Save plot in R Using ggsave()
with ggplot2
R
library (ggplot2)
data <- data.frame (x = 1:10, y = (1:10)^2)
p <- ggplot (data, aes (x, y)) + geom_point (color = "blue" ) +
ggtitle ( "Scatter Plot" ) + xlab ( "X" ) + ylab ( "Y" )
p
ggsave ( "output_plot.png" , plot = p, width = 6, height = 4, units = "in" )
|
Output:
Save Plot in R
After run the code the plot is save in pdf files in r local storage and after clicking on files section we can find out our pdf plot save same as the name that we have give.
Save plot in R Using recordPlot()
and replayPlot()
for Base Plot
R
plot (1:10, 1:10, col = "blue" , pch = 18, main = "Base Plot" , xlab = "X" , ylab = "Y" )
res <- recordPlot ()
replayPlot (res)
|
Output:
Save Plot in R
Save plot in R Using png()
from grDevices
for Base Plot
R
library (grDevices)
x <- 1:10
y <- x^2
plot (x, y, col = "purple" , pch = 16, main = "Scatter Plot" , xlab = "X" , ylab = "Y" )
png ( "output_plot.png" )
dev.off ()
|
Output:
Save Plot in R
After run the code the plot is save in pdf files in r local storage and after clicking on files section we can find out our pdf plot save same as the name that we have give.
Last Updated :
19 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...