15  Exporting Visualizations and Data

Today we focus on the practice of exporting completed visualizations

In order to communicate using visualization, one usually needs to save it to a form that can be used to communicate. Today will focus on static images but there are options for interactive formats like HTML or Shiny that embed interactivity.

15.1 Load libraries

── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.2     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.2     ✔ tibble    3.2.1
✔ lubridate 1.9.2     ✔ tidyr     1.3.0
✔ purrr     1.0.1     
── 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
Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE

15.2 Import data

Load SoCalEJ for the demonstration.

URL.path <- 'https://raw.githubusercontent.com/RadicalResearchLLC/EDVcourse/main/CalEJ4/CalEJ.geoJSON'
SoCalEJ <- st_read(URL.path) %>% 
  st_transform("+proj=longlat +ellps=WGS84 +datum=WGS84")
Reading layer `CalEJ' from data source 
  `https://raw.githubusercontent.com/RadicalResearchLLC/EDVcourse/main/CalEJ4/CalEJ.geoJSON' 
  using driver `GeoJSON'
Simple feature collection with 3747 features and 66 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: 97418.38 ymin: -577885.1 xmax: 539719.6 ymax: -236300
Projected CRS: NAD83 / California Albers

15.3 Transform data for ggplot group & facet visualization

SoCal_narrow <- SoCalEJ %>% 
  st_set_geometry(value = NULL) %>% 
  pivot_longer(cols = c(5:66), names_to = 'variable', values_to = 'value') %>% 
  filter(value >=0)

15.4 Create a ggplot visualization

I will start with one of our pretty ggplot examples from Chapter 11. Let’s remix the racial and ethnic population percentage by census tract and county. Figure 15.1 shows the figure.

SoCal_narrow %>% 
  filter(variable %in% c('Hispanic', 'White', 'AfricanAm',
                         'NativeAm', 'OtherMult', 'AAPI')) %>% 
  ggplot(aes(x = variable, y = value, fill= County)) +
  geom_boxplot() +
  theme_bw() + 
  labs(x = '', y = 'Percent of population')

Figure 15.1: Racial and ethnic population distribution by county in SoCal census tracts.

15.5 Exporting Visualizations

15.5.1 Option 1 - Point and Click

The point and click option is available after one creates a visualization.

  1. Go to the files, plots, and packages panel of RStudio.
  2. Click on the Plots tab.
  3. Click on the Export button as shown in Figure 15.2
  4. Choose whether to Save as Image or Save as PDF.
  5. Rename file save to something more descriptive than RPlot
  6. Click Save
  7. File should now be saved to your working directory - getwd() will identify that path, and it should be accessible through the Files tab of the

Figure 15.2: Export button is here on my machine

15.5.2 Option 2. For ggplot() files, use ggsave()

This is pretty straightforward and a bit more reproducible and customizable than the manual point and click process. A minimal example of a .png export is shown below.

ggsave(filename = 'boxplot.png')
Saving 7 x 5 in image

One can then go to the Files panel, sort by modified and there should be a file named boxplot.png. Note that ggsave() defaults to saving the last image created.

One can save files as a variety of image formats, with specified dimensions.

ggsave(filename = 'boxplot.jpg', width = 5, height = 4, units = 'in')

There are a number of export options within ggsave(), but the defaults should be pretty good for now.

Lastly, it can sometimes be important to directly save a ggplot within R. Then one can manually assign the exact image file to export. The code below demonstrates this, and is most important when automating exporting many (e.g., 100s) of images.

Vis <- SoCal_narrow %>% 
  filter(variable %in% c('Hispanic', 'White', 'AfricanAm',
                         'NativeAm', 'OtherMult', 'AAPI')) %>% 
  ggplot(aes(x = variable, y = value, fill= County)) +
  geom_boxplot() +
  theme_bw() + 
  labs(x = '', y = 'Percent of population')

ggsave('boxplot.pdf', plot = Vis)
Saving 7 x 5 in image

In this third example, we assign the image to the pointer Viz. Then the ggsave() option plot = is used to assign the image to save the file Viz to a .pdf export.

15.6 Leaflet Visualization - Static

First, I am going to map Diesel PM for the SoCalEJ dataset in Leaflet. Figure 15.3 is the result.

palDPM <- colorNumeric(palette = 'YlOrBr', domain = SoCalEJ$DieselPM_P)

leaflet(data = SoCalEJ) %>% 
  addTiles() %>% 
  setView(lat = 33.8, lng = -117.60, zoom = 9) %>% 
  addPolygons(stroke = FALSE,
              fillColor = ~palDPM(DieselPM_P),
              fillOpacity = 0.5) %>% 
  addLegend(pal = palDPM, 
            title = 'Diesel PM (%)', 
            values = ~DieselPM_P)

Figure 15.3: Diesel PM percentiles in SoCal

15.6.1 Option 1. Point and Click.

Repeat similar steps as shown in Section 15.5.1. Here are the steps for exporting an interactive HTML map manually.

  1. Go to the files, plots, and packages panel of RStudio.
  2. Click on the Plots tab.
  3. Click on the Export button as shown in Figure 15.2
  4. Choose to Save as Web Page.
  5. Rename file save to something more descriptive than RPlot
  6. Click Save
  7. File should now be saved to your working directory - getwd() will identify that path, and it should be accessible through the Files tab. On my machine it also loads directly into my default web browser.

15.6.2 Option 2. htmlwidgets package for exports

As always, there is a package to do a specific thing that be done point and click style. htmlwidgets provides the saveWidget() function for exporting leaflet maps as HTML.

15.6.2.1 Install the package and load it.

install.packages('htmlwidgets')

15.6.2.2 Save Leaflet as a Static Image

First, the map needs to be assigned a name. In this case, it is assigned the name DPM_map.

DPM_map <- leaflet(data = SoCalEJ) %>% 
  addTiles() %>% 
  setView(lat = 33.8, lng = -117.60, zoom = 9) %>% 
  addPolygons(stroke = FALSE,
              fillColor = ~palDPM(DieselPM_P),
              fillOpacity = 0.5) %>% 
  addLegend(pal = palDPM, 
            title = 'Diesel PM (%)', 
            values = ~DieselPM_P)

Look at the Environment panel and DPM_map is now an environmental data of type Large leaflet (8 elements, 11.6 MB).

Now the map can be saved using saveWidgets()

saveWidget(widget = DPM_map, file = 'DPM_map.html')

And that’s it. Check in Files and we have the DPM_map.html.

You are now experts!