We learn to save the plots today.
Welcome to Day 2 of Week 3 and the 16th Day Overall in the Series!
Goals for today: We are going to learn how to save the plots we create.
Learning to save the plots we make is an essential skill in data visualization, especially when we want to export plots for use in a presentation or a paper. Sometimes, we are okay with a simple JPEG format, but journals might require a specific format like PNG, TIFF, or PDF.
Today, I’ll walk you through saving your plots in various formats.
Let’s start by drawing a plot from yesterday:
library(palmerpenguins)
library(tidyverse)
penguins %>%
ggplot(aes(x = species, y = body_mass_g)) +
geom_boxplot() +
labs(x = "Species", y = "Body Mass (g)") +
theme_minimal()
Right now, the plot we generate is available only in the Plot pane in RStudio.
To export it, we can use the function ggsave()
, which allows us to save plots in a variety of formats.
First, let’s name the plot as an object and then save it:
p <- penguins %>%
ggplot(aes(x = species, y = body_mass_g)) +
geom_boxplot() +
labs(x = "Species", y = "Body Mass (g)") +
theme_minimal()
Now, p is stored in the environment
But we need to save it to a file on your PC/desktop or working directory. To do that, we use ggsave()
and specify the desired file format
# Save as PNG
ggsave("plot.png", plot = p)
Now I want you to open the image you saved and check if it looks good. If you are happy with the quality, you can move on to saving it in other formats.
Mine looked like this:
I added a background color with the argument bg=
to the plot and saved it again:
ggsave("plot.png", plot = p, bg = "white")
This time, the plot looked like this:
Similarly we can use the following code to save the plot in different formats:
If you don’t want to assign the plot to an object, you can simply save the last plot generated by using last_plot()
Remember, the plot we need to save should be the last one we generated to correctly use last_plot()
.
By default, they are saved in the root folder, which is the parent directory of your R project. If you’re not using R projects, this could lead to confusion about where your files are saved.
To save plots in a designated folder, I recommend using the here() package. It helps create paths relative to your project directory. You can read more about this in my previous blog post on the here package.
Happy plotting!
For attribution, please cite this work as
Soundararajan (2024, Oct. 16). My R Space: Day 16 of viz with me. Retrieved from https://github.com/soundarya24/SoundBlog/posts/2024-10-16-day-16-of-viz-with-me/
BibTeX citation
@misc{soundararajan2024day, author = {Soundararajan, Soundarya}, title = {My R Space: Day 16 of viz with me}, url = {https://github.com/soundarya24/SoundBlog/posts/2024-10-16-day-16-of-viz-with-me/}, year = {2024} }