Hello, readers! In this article, we will learn how to save graphs to files in R in detail. So, let us begin! 🙂
With R programming, we can export our data to various viewable formats. By this, the result of our analysis can be shared or exported for understanding purposes.
Steps to save graphs to files in R
In the context of this topic, we will use the below ways save graphs to files by exporting-
- Exporting graphs to PNG format.
- Exporting graphs to JPEG format.
- Graphs to PDF format.
- The EXPORT option in R studio
1. Save R graph to PDF
With R programming, we can have our data in the form of visualization being stored in a PDF format. For the same, R pdf() function helps us out with the same.
Steps to save R graph as a PDF-
- Use the pdf() function and define the name of the pdf as a parameter to the function with .pdf extension.
- Perform the plotting of the graph. In our case, we have plotted a boxplot using boxplot() method.
- Use dev.off() function to shut down the processing of the current cycle on the device.
pdf("boxplot.pdf") boxplot(dta[,numeric_col]) dev.off()
As a result, the pdf form of the graph gets saved at the current directory being in use. You can check the current directory using getwd() function.
2. Save a graph in PNG file format
Apart from the PDF format, we can save the graph in PNG format using png() function.
At first, we frame a name for the graph to be stored as an image. Then, we plot the image and stop the process using dev.off() function.
png("boxplot.png") boxplot(dta[,numeric_col]) dev.off()
3. Save the graph to file in JPEG format
In order to save the graph into the JPEG format, we need to use jpeg() function to create and save the graph with .jpeg extension. Then, we plot the graph and that gets saved to the file which we created using jpeg() function.
jpeg("boxplot.jpeg") boxplot(dta[,numeric_col]) dev.off()
4. Export R graph to file
Using RStudio as an IDE to execute the R programs, it provides us an option to have the graphs exported.
As soon as you plot the graph, you see the graph on the right panel of the screen. Above the graph, we can find an export button. Click on the export button and we would find the three options–
- Save as Image
- Save as PDF
- Copy to Clipboard
Click on your preferred choice. We clicked on Save as Image, after which the below screen appears.
It provides us option to choose the format of Image such as PNG, JPEG, etc from the drop-down list.
Further, we can rename the Image to appropriate name using File name field. Even the Width and Height of the image can be customized.
Feel free to comment below, in case you come across any question. For more such posts related to R programming, Stay tuned with us. Till then, Happy Learning!! 🙂