17  Export

Author

Jarad Niemi

R Code Button

This chapter will discuss how to export graphics using the ggsave() function from the ggplot2 package. This will allow you to incorporate figure exporting into your script-based data pipeline. With that being said, you generally need to manually determine export settings that suit particular purposes, e.g. writing a report, posting on a website, etc.

library("tidyverse")
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4.9000     ✔ readr     2.1.5     
✔ forcats   1.0.0          ✔ stringr   1.5.1     
✔ ggplot2   3.5.1          ✔ tibble    3.2.1     
✔ lubridate 1.9.3          ✔ tidyr     1.3.1     
✔ purrr     1.0.2          
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

Let’s first construct a figure and save it as an R object.

# Warpbreaks default plot
g <- ggplot(warpbreaks, 
            aes(x = tension, 
                y = breaks,
                color = wool,
                shape = wool)) +
  geom_jitter(
    height = 0,
    width  = 0.1
  )

g

As a reminder, the figure will be saved to your current working directory.

# Get working directory
getwd()
[1] "/Users/niemi/git/teaching/STAT5860/chapters"

If you need to set your, use setwd().

# Change working directory
setwd("../relative/path/to/some/other/directory")

Saving the figure as an object, in this case g will allow us to use ggsave() to export that object.

Here is a default export of a png file.

# Default png export
ggsave(g, file="figure.png")
Saving 7 x 5 in image

The ggsave() function will automatically determine the figure format from the extension used. The resulting figure is a 7 x 7 in[ches] image.

Here is a default export of a jpg.

# Default jpg export
ggsave(g, file="figure.jpg")
Saving 7 x 5 in image

We may want to save the files with different settings. For example, if we want the file to have 4k resolution (3840x2160), we can set the resolution of the image in pixels.

# 4k jpg export
ggsave(g, 
       file   = "figure4k.jpg",
       width  = 3840,
       height = 2160,
       units  = "px") # pixels
# Remove all created files
unlink("figure.png")
unlink("figure.jpg")
unlink("figure4k.jpg")