Learning Objectives

  • Produce scatter plots, boxplots, and time-series plots using ggplot.
  • Set universal plot settings.
  • Describe what faceting is and apply faceting in ggplot.
  • Modify the aesthetics of an existing ggplot plot (including axis labels and color).
  • Build complex and customized plots from data in a data frame.

Getting Started

Open your Environmental Data Analysis project, and create a new script named “A8_DataVisualization”.

Next we will load the packages we will be using today. ggplot2 is included in the tidyverse package. Ignore any warning messages concerning version.

library(tidyverse)

Finally, we will import the data frame surveys_complete.csv that we created at the end of the A6 Data Wrangling workshop. If you do not still have a copy of the file, you can download the file from Brightspace and save it to your data folder.

surveys_complete <- read_csv("data/surveys_complete.csv")

Plotting with ggplot2

ggplot2 is a plotting package that makes it simple to create complex plots from data in a data frame. It provides a more programmatic interface for specifying what variables to plot, how they are displayed, and general visual properties. Therefore, we only need minimal changes if the underlying data change or if we decide to change from a bar plot to a scatter plot. This helps in creating publication quality plots with minimal amounts of adjustments and tweaking.

ggplot2 functions work best for data in the “long” format, i.e., a column for every variable, and a row for every observation. Well-structured data will save you lots of time when making figures with ggplot2.

ggplot graphics are built step by step by adding new elements. Adding layers in this fashion allows for extensive flexibility and customization of plots.

To build a ggplot, we will use the following basic template that can be used for different types of plots. (Note: This is a template for how the function works, not executable code. This will not run.)

ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) +  
  <GEOM_FUNCTION>()
  • use the ggplot() function and bind the plot to a specific data frame using the data argument
ggplot(data = surveys_complete)
  • define a mapping using the aesthetic aes() function, by selecting the variables to be plotted and specifying how to present them in the graph, e.g., as x/y positions or characteristics such as size, shape, color, etc.
ggplot(data = surveys_complete, mapping = aes(x = weight, y = hindfoot_length))
  • add “geoms,” graphical representations of the data in the plot (points, lines, bars).

ggplot2 offers many different geoms. We will use some common ones today, including:

  • geom_point() for scatter plots, dot plots, etc.
  • geom_boxplot() for…boxplots.
  • geom_line() for trend lines, time series, etc.

To add a geom to the plot, use the + operator. Because weight and hindfoot_length are both continuous variables, let’s use geom_point() to make a scatter plot first.

ggplot(data = surveys_complete, mapping = aes(x = weight, y = hindfoot_length)) +
  geom_point()

The + in the ggplot2 package is particularly useful because it allows you to modify existing ggplot objects. This means you can easily set up plot templates and conveniently explore different types of plots, so the above plot can also be generated with code like this:

# Assign plot to an object
surveys_plot <- ggplot(data = surveys_complete, 
                       mapping = aes(x = weight, y = hindfoot_length))

# Draw the plot by referencing the object and adding a geom layer
surveys_plot + 
    geom_point()

Notes

  • Anything you put in the ggplot() function can be seen by any geom layers that you add (i.e., these are universal plot settings). This includes the x- and y-axis mapping you set up in aes().
  • You can specify mappings for a given geom independently of the mappings defined globally in the ggplot() function.
  • The + sign used to add new layers must be placed at the end of the line containing the previous layer. If, instead, the + sign is added at the beginning of the line containing the new layer, ggplot2 will not add the new layer and will return an error message. The last layer of your plot must not end with a +, or ggplot will continue looking for the next line of code for your plot.
# This is the correct syntax for adding layers
surveys_plot +
  geom_point()

# This will not add the new layer and will return an error message
surveys_plot 
  + geom_point()

# This will not finish running because ggplot is looking for the next plot layer
surveys_plot +
  geom_point() +

Building your plots iteratively

Building plots with ggplot2 is typically an iterative process. We start by defining the data set we’ll use, lay out the axes, and choose a geom:

ggplot(data = surveys_complete, mapping = aes(x = weight, y = hindfoot_length)) +
    geom_point()

Then, we start modifying this plot to extract more information from it. For instance, we can add a transparency argument (alpha) to avoid overplotting:

ggplot(data = surveys_complete, mapping = aes(x = weight, y = hindfoot_length)) +
    geom_point(alpha = 0.1)

We can also add colors for all the points:

ggplot(data = surveys_complete, mapping = aes(x = weight, y = hindfoot_length)) +
    geom_point(alpha = 0.1, color = "dark green")

Or to color each species in the plot differently, you could use a vector as an input to the argument color. ggplot2 will provide a different color corresponding to different values in the vector. Here is an example where we color with species_id:

ggplot(data = surveys_complete, mapping = aes(x = weight, y = hindfoot_length)) +
    geom_point(alpha = 0.1, aes(color = species_id))

We can also specify the colors directly inside the mapping provided in the ggplot() function. This will be seen by any geom layers and the mapping will be determined by the x- and y-axis set up in aes().

ggplot(data = surveys_complete, mapping = aes(x = weight, y = hindfoot_length, color = species_id)) +
    geom_point(alpha = 0.1)

Notice that we can change the geom layer and colors will be still determined by species_id.

ggplot(data = surveys_complete, mapping = aes(x = weight, y = hindfoot_length, color = species_id)) +
    stat_smooth()

Challenge 1

Use what you have just learned to create a scatter plot with weight on the y axis and species_id on the x axis, with plot_type showing in different colors.
After your plot looks the way you want, export it using the line ggsave("Challenge1.jpg", width = 8).
Upload your plot to Challenge 1 on Brightspace.
Is this a good way to show these data? Think about how you could better display these data.

Answer
#Create scatter plot
ggplot(surveys_complete, aes(x = species_id, y = weight, color = plot_type)) +
  geom_point()

#Export scatter plot
ggsave("Challenge1.jpg", width = 8)
## Saving 8 x 5 in image

Boxplots

We can use boxplots to visualize the distribution of weight within each species:

ggplot(data = surveys_complete, mapping = aes(x = species_id, y = weight)) +
    geom_boxplot()

The boxplot shows the median (center line), middle 50% of the data distribution (box), and total range (lines), and outliers (points). Outliers are any points outside of 1.5x the interquartile range (size of the box).

By adding points to the boxplot, you can get a better idea of the number of measurements and their distribution:

ggplot(data = surveys_complete, mapping = aes(x = species_id, y = weight)) +
    geom_boxplot(alpha = 0) +
    geom_jitter(alpha = 0.3, color = "seagreen")

Notice that the boxplot layer is behind the jitter layer. What would you need to change in the code to put the boxplot in front of the points such that it’s not hidden?

Answer
ggplot(data = surveys_complete, mapping = aes(x = species_id, y = weight)) +
  geom_jitter(alpha = 0.3, color = "seagreen") +
  geom_boxplot(alpha = 0)

Challenge 2

Boxplots are useful summaries, but they hide the shape of the distribution. For example, if the distribution is bimodal, we would not see it in a boxplot. An alternative to the boxplot is the violin plot, where the shape (of the density of points) is drawn. Replace the geom_boxplot() layer with geom_violin().
You can now remove the geom_jitter() layer.
For many types of data, it is important to consider the scale of the observations. For example, it may be worth changing the scale of the axis to better distribute the observations in the space of the plot. Changing the scale of the axes is done similarly to adding/modifying other components (i.e., by incrementally adding commands). Add the layer scale_y_log10() to your plot to change the scale of the weight axis.
When you are satisfied with your plot, use the line ggsave("Challenge2.jpg") to export your plot.
Upload your plot to Challenge 2 on Brightspace.

Answer
ggplot(surveys_complete, aes(x = species_id, y = weight)) +
  geom_violin() +
  scale_y_log10()

ggsave("Challenge2.jpg")
## Saving 7 x 5 in image

Challenge 3

So far, we’ve looked at the distribution of weight within species. Make a new plot to explore the distribution of hindfoot_length within species.
Overlay a boxplot layer on a jitter layer to show actual measurements.
Add color to the jitter layer corresponding to the plot from which the sample was taken (plot_id).
Hint: Check the class for plot_id. Within the color = argument, add the function as.factor() around plot_id to change the variable from an integer to a factor. Notice how this changes the way R makes the graph.
When you are satisfied with your plot, use the line ggsave("Challenge3.jpg", width = 8) to export your plot.
Upload your plot to Challenge 3 on Brightspace.

Answer
ggplot(surveys_complete, aes(x = species_id, y = hindfoot_length)) +
  geom_jitter(alpha = 0.3, aes(color = as.factor(plot_id))) +
  geom_boxplot(alpha = 0)

ggsave("Challenge3.jpg", width = 8)
## Saving 8 x 5 in image

Plotting time series data

Let’s calculate number of counts per year for each genus. First we need to group the data and count records within each group:

yearly_counts <- surveys_complete %>%
  count(year, genus)

Time series data can be visualized as a line plot with years on the x axis and counts on the y axis:

ggplot(data = yearly_counts, mapping = aes(x = year, y = n)) +
     geom_line()

Unfortunately, this does not work because we plotted data for all the genera together. We need to tell ggplot to draw a line for each genus by modifying the aesthetic function to include group = genus:

ggplot(data = yearly_counts, mapping = aes(x = year, y = n, group = genus)) +
    geom_line()

We will be able to distinguish genera in the plot if we add colors (using color also automatically groups the data):

ggplot(data = yearly_counts, mapping = aes(x = year, y = n, color = genus)) +
    geom_line()

Faceting

ggplot2 has a special technique called faceting that allows the user to split one plot into multiple plots based on a factor included in the data set.

There are two type of facet functions:

  • facet_wrap arranges a one-dimensional sequence of panels to allow them to clearly fit on one page
  • facet_grid allows you to form a matrix of rows and columns of panels.

Both geometries allow you to specify faceting variables within vars(). For example,
facet_wrap(facets = vars(facet_variable)) OR
facet_grid(rows = vars(row_variable), cols = vars(col_variable)).

Let’s start by using facet_wrap() to make a time series plot for each species.

ggplot(data = yearly_counts, mapping = aes(x = year, y = n)) +
    geom_line() +
    facet_wrap(facets = vars(genus))

Now we would like to split the line in each plot by the sex of each individual measured. To do that we need to make counts in the data frame grouped by year, species_id, and sex:

yearly_sex_counts <- surveys_complete %>%
  count(year, genus, sex)

We can now make the faceted plot by splitting further by sex using color (within each panel):

ggplot(data = yearly_sex_counts, mapping = aes(x = year, y = n, color = sex)) +
  geom_line() +
  scale_color_manual(values = c("red", "blue")) +
  facet_wrap(facets =  vars(genus))

Note that I also added the layer scale_color_manual() to change the colors.

Now let’s use facet_grid() to control how panels are organized by both rows and columns:

ggplot(data = yearly_sex_counts, 
       mapping = aes(x = year, y = n, color = sex)) +
  geom_line() +
  scale_color_manual(values = c("red", "blue")) +
  facet_grid(rows = vars(sex), cols =  vars(genus))

You can also organize the panels only by rows (or only by columns):

# One column, facet by rows
ggplot(data = yearly_sex_counts, 
       mapping = aes(x = year, y = n, color = sex)) +
  geom_line() +
  scale_color_manual(values = c("red", "blue")) +
  facet_grid(rows = vars(genus))

# One row, facet by column
ggplot(data = yearly_sex_counts, 
       mapping = aes(x = year, y = n, color = sex)) +
  geom_line() +
  scale_color_manual(values = c("red", "blue")) +
  facet_grid(cols = vars(genus))

Note: In earlier versions of ggplot2 you needed to use an interface using formulas to specify how plots are faceted (and this is still supported in new versions). You may still see this syntax if you look up how to do these things in ggplot. The equivalent syntax is:

# facet wrap
facet_wrap(vars(genus))    # new
facet_wrap(~ genus)        # old

# grid on both rows and columns
facet_grid(rows = vars(genus), cols = vars(sex))   # new
facet_grid(genus ~ sex)                            # old

# grid on rows only
facet_grid(rows = vars(genus))   # new
facet_grid(genus ~ .)            # old

# grid on columns only
facet_grid(cols = vars(genus))   # new
facet_grid(. ~ genus)            # old

ggplot2 themes

Usually plots with white background look more readable when printed. Every single component of a ggplot graph can be customized using the generic theme() function, as we will see below. However, there are pre-loaded themes available that change the overall appearance of the graph without much effort.

For example, we can change our previous graph to have a simpler white background using the theme_bw() function:

ggplot(data = yearly_sex_counts, 
       mapping = aes(x = year, y = n, color = sex)) +
  geom_line() +
  scale_color_manual(values = c("red", "blue")) +
  facet_wrap(vars(genus)) +
  theme_bw()

In addition to theme_bw(), which changes the plot background to white, ggplot2 comes with several other themes which can be useful to quickly change the look of your visualization. The complete list of themes is available at https://ggplot2.tidyverse.org/reference/ggtheme.html. theme_minimal() and theme_light() are popular, and theme_void() can be useful as a starting point to create a new hand-crafted theme.

The ggthemes package provides a wide variety of options. The ggplot2 extensions website, https://exts.ggplot2.tidyverse.org/, provides a list of packages that extend the capabilities of ggplot2, including additional themes.

If you are going to be creating a lot of plots, you can also set a base theme using theme_set() before you begin. That theme will be inherited by all plots you create. R will continue to follow that theme set until you set a new theme or add a theme() layer to new plots.
For example, I will often run the following code near the beginning of my R scripts or R Markdown documents. It is similar to theme_minimal() but with a few tweaks that makes my plots look the way I want (including larger font sizes).

#Set theme for plots
theme_set(theme_bw(base_size = 16)+ 
            theme(panel.grid.major = element_blank(), 
                  panel.grid.minor = element_blank(), 
                  strip.background = element_blank()))

Challenge 4

Use what you just learned to create a plot that depicts how the average weight of each species changes through the years.
When you are satisfied with your plot, export using ggsave("Challenge4.jpg", width = 8)
Upload your plot to Challenge 4 on Brightspace.

Answer
# Create summary data frame, grouping by year and species id
yearly_weight <- surveys_complete %>% 
  group_by(year, species_id) %>% 
  summarize(mean_weight = mean(weight, na.rm = T))
## `summarise()` has grouped output by 'year'. You can override using the
## `.groups` argument.
#Plot changes in weight over time, facet by species_id
ggplot(yearly_weight, aes(x = year, y = mean_weight)) +
  geom_line() +
  facet_wrap(vars(species_id)) +
  theme_minimal()

ggsave("Challenge4.jpg", width = 8)
## Saving 8 x 5 in image

Customization

Take a look at the ggplot2 cheat sheet on Brightspace, and think of ways you could improve the plot.

Now, let’s change the names of axes to something more informative than “year” and “n.”

ggplot(data = yearly_sex_counts, mapping = aes(x = year, y = n, color = sex)) +
  geom_line() +
  scale_color_manual(values = c("red", "blue")) +
  facet_wrap(vars(genus)) +
  labs(x = "Year of observation",
       y = "Number of individuals") +
  theme_bw()

(Note that it is also possible to change the fonts of your plots. If you are on Windows, you may have to install the extrafont package, and follow the instructions included in the README for this package.)

After our manipulations, you may notice that the values on the x-axis are still not properly readable. Let’s change the orientation of the labels and adjust them vertically and horizontally so they don’t overlap. You can use a 90-degree angle, or experiment to find the appropriate angle for diagonally oriented labels:

ggplot(data = yearly_sex_counts, mapping = aes(x = year, y = n, color = sex)) +
  geom_line() +
  scale_color_manual(values = c("red", "blue")) +
  facet_wrap(vars(genus)) +
  labs(x = "Year of observation",
       y = "Number of individuals") +
  theme_bw() +
  theme(axis.text.x = element_text(color = "grey20", size = 12, angle = 90, 
                                   hjust = 0.5, vjust = 0.5),
        axis.text.y = element_text(color = "grey20", size = 12),
        text = element_text(size = 16))

If you like the changes you created, you can save them as an object to be able to easily apply them to other plots you may create:

# define custom theme
grey_theme <- theme(axis.text.x = element_text(colour = "grey20", size = 12, angle = 90, 
                                               hjust = 0.5, vjust = 0.5),
                    axis.text.y = element_text(colour = "grey20", size = 12),
                    text = element_text(size = 16))

# Create a boxplot with new theme
ggplot(surveys_complete, aes(x = species_id, y = hindfoot_length)) +
  geom_boxplot() +
  theme_bw() +
  grey_theme

Challenge 5

With all of this information in hand, please take another five minutes to either improve one of the plots generated in this exercise or create a beautiful graph of your own. Use the ggplot2 cheat sheet for inspiration. Here are some ideas:

* See if you can change the thickness of the lines.
* Can you find a way to change the name of the legend? What about the labels in the legend?
* Try using a different color palette (check out http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/ and https://coolors.co/).

When you are satisfied with your plot, use ggsave() to export it.
Adjust the height and width arguments in ggsave() until you are happy with your final plot.
Upload your final plot to Challenge 5 on Brightspace.

Exporting plots

Throughout this exercise we have used ggsave() to export plots. The Export tab in the Plot pane in RStudio will save your plots at low resolution, which will not be accepted by many journals and will not scale well for posters.

Instead, you should use the ggsave() function, which allows you to easily change the dimensions and resolution of your plot by adjusting the appropriate arguments (width, height, and dpi). You can also choose the type of file you wish to export by changing the file extension. For example, you may wish to save your file as a .png if you wish it to have a transparent background. Some journals may require you to submit images as a .tif.