Welcome Back

Google icon Sign in with Google
OR
I agree to abide by Pharmadaily Terms of Service and its Privacy Policy

Create Account

Google icon Sign up with Google
OR
By signing up, you agree to our Terms of Service and Privacy Policy
Instagram
youtube
Facebook

Exporting Graphs for Reports

After creating visualizations, the next important step is exporting the graphs for use in reports, presentations, or publications. In R, graphs created using the ggplot2 package can be easily saved in different file formats such as PNG, JPEG, or PDF.

Exporting graphs ensures that visualizations can be shared, printed, or included in documents without needing to recreate them each time. The most commonly used function for saving plots in ggplot2 is ggsave().

library(ggplot2)

First, create a plot and store it in a variable.

plot1 <- ggplot(data = mtcars, aes(x = wt, y = mpg)) +
  geom_point()

The plot can then be exported using the ggsave() function.

ggsave("scatter_plot.png", plot = plot1)

In this example, the scatter plot is saved as a PNG file in the current working directory.

The file format is determined by the extension used in the file name. For example, using .jpg will save the plot as a JPEG image, and using .pdf will save it as a PDF document.

ggsave("scatter_plot.jpg", plot = plot1)
ggsave("scatter_plot.pdf", plot = plot1)

The size and resolution of the exported graph can also be customized.

ggsave("scatter_plot.png",
       plot = plot1,
       width = 6,
       height = 4,
       dpi = 300)

In this example, the plot is saved with a width of 6 inches, a height of 4 inches, and a resolution of 300 dots per inch, which is suitable for high-quality reports and print materials.

Exporting graphs is an essential step in the data analysis process. It allows visualizations to be shared easily and included in professional documents, presentations,