Rstudio Cheat Sheet Ggplot2



Learning Objectives

I’m very pleased to announce the release of ggplot2 2.0.0. I know I promised that there wouldn’t be any more updates, but while working on the 2nd edition of the ggplot2 book, I just couldn’t stop myself from fixing some long standing problems. On the scale of ggplot2 releases, this one is huge with over one hundred fixes and improvements. This might break some of your existing code.

By the end of this lesson the learner will:

Rstudio cheat sheet ggplot
  • Produce scatter plots, bloxplots, and time series plots using ggplot.
  • Set universal plot settings.
  • Modify the aesthetics of an existing ggplot plot (including axis labels and color).
  • Build complex and customized plots from data in a dataframe.
  1. RStudio Cheat Sheets. Contribute to rstudio/cheatsheets development by creating an account on GitHub.
  2. Base R Graphics Cheat Sheet David Gerard August 8, 2017. Abstract: I reproduce some of the plots from Rstudio’s ggplot2 cheat sheet using Base R graphics.
  3. Cheat Sheet RStudio® is a trademark of RStudio, Inc. CC BY RStudio. info@rstudio.com. 844-448-1212. rstudio.com Learn more at docs.ggplot2.org. ggplot2 0.9.3.1. Updated: 3/15 Geoms- Use a geom to represent data points, use the geom’s aesthetic properties to represent variables.

We start by loading the required packages.

Plotting with ggplot2

ggplot2 is a plotting package that makes it simple to create complex plots from data in a dataframe. It uses default settings, which help creating publication quality plots with a minimal amount of settings and tweaking.

ggplot graphics are built step by step by adding new elements.

To build a ggplot we need to:

  • bind the plot to a specific data frame using the data argument
  • define aesthetics (aes), by selecting the variables to be plotted and the variables to define the presentation such as plotting size, shape color, etc.,
  • add geoms – graphical representation of the data in the plot (points, lines, bars). To add a geom to the plot use + operator:
Rstudio Cheat Sheet Ggplot2

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:

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 you set up in aes().
  • You can also specify aesthetics for a given geom independently of the aesthetics defined globally in the ggplot() function.
  • The + sign used to add layers must be placed at the end of each line containing a layer; if, instead, the + sign is added in the line before the other layer, ggplot2 will not add the new layer and will return an error message.

Challenge (optional)

Scatter plots can be useful exploratory tools for small data sets. For data sets with large numbers of observations, such as the surveys_complete data set, overplotting of points can be a limitation of scatter plots. One strategy for handling such settings is to use hexagonal binning of observations. The plot space is tesselated into hexagons. Each hexagon is assigned a color based on the number of observations that fell within its boundaries. To use hexagonal binning with ggplot2, first install the R package hexbin from CRAN:

Then use geom_hex() function from the ggplot2 package.

  • What are the relative strengths and weaknesses of a hexagonal bin plot compared to a scatter plot? Examine the above scatter plot and compare it with the hexagonal bin plot that you created.

Building your plots iteratively

Building plots with ggplot is typically an iterative process. We start by defining the dataset we’ll use, lay the axes, and choose a geom.

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

We can also add colors for all the points

Or to color each species in the plot differently:

Boxplot

Visualising the distribution of weight within each species.

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

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

Challenges

Boxplots are useful summaries, but hide the shape of the distribution. For example, if there is a bimodal distribution, this would not be observed with a boxplot. An alternative to the boxplot is the violin plot (sometimes known as a beanplot), where the shape (of the density of points) is drawn.

  • Replace the box plot with a violin plot; see geom_violin()

In 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).

  • Represent weight on the log10 scale; see scale_y_log10()

  • Create boxplot for hindfoot_length.

  • Add color to the datapoints on your boxplot according to the plot from which the sample was taken (plot_id)

Hint: Check the class for plot_id. Consider changing the class of plot_id from integer to factor. Why does this change how R makes the graph?

Plotting time series data

Let’s calculate number of counts per year for each species. To do that we need to group data first and count records within each group.

Timelapse data can be visualised as a line plot with years on x axis and counts on y axis.

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

We will be able to distinguish species in the plot if we add colors.

Faceting

Rstudio cheat sheet ggplot

ggplot has a special technique called faceting that allows to split one plot into multiple plots based on a factor included in the dataset. We will use it to make one plot for a time series for each species.

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

We can now make the faceted plot splitting further by sex (within a single plot):

Usually plots with white background look more readable when printed. We can set the background to white using the function theme_bw(). Additionally you can also remove the grid.

The ggplot2 themes

In addition of theme_bw() that changes the plot background to white, ggplot2 comes with several other themes, which can be useful to quickly change the look and feel of your visualization. The complete list of themes is available at http://docs.ggplot2.org/current/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.

Ggplot2 In R

The ggthemes package provides a wide variety of options (including an Excel 2003 theme). The ggplot2 extensions website provides a list of packages that extend the capabilities of ggplot2, including additional themes.

To make the plot easier to read, we can color by sex instead of species (species are already in separate plots, so we don’t need to distinguish them further).

Challenge

Use what you just learned to create a plot that depicts how the average weight of each species changes through the years.

Rstudio Cheat Sheet Ggplot2 Free

The facet_wrap geometry extracts plots into an arbitrary number of dimensions to allow them to cleanly fit on one page. On the other hand, the facet_grid geometry allows you to explicitly specify how you want your plots to be arranged via formula notation (rows ~ columns; a . can be used as a placeholder that indicates only one row or column).

Let’s modify the previous plot to compare how the weights of male and females has changed through time.

Fantasy Football Cheat Sheet

Customization

Take a look at the ggplot2 cheat sheet (https://www.rstudio.com/wp-content/uploads/2015/08/ggplot2-cheatsheet.pdf), and think of ways to improve the plot. You can write down some of your ideas as comments in the Etherpad.

Now, let’s change names of axes to something more informative than ‘year’ and ‘n’ and add a title to this figure:

The axes have more informative names, but their readability can be improved by increasing the font size. While we are at it, we’ll also change the font family:

After our manipulations we 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.

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

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 RStudio ggplot2 cheat sheet, which we linked earlier for inspiration.

Ggplot2 Tutorial

Here are some ideas:

  • See if you can change thickness of the lines.
  • Can you find a way to change the name of the legend? What about its labels?
  • Use a different color palette (see http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/)

After creating your plot, you can save it to a file in your favourite format. You can easily change the dimension (and its resolution) of your plot by adjusting the appropriate arguments (width, height and dpi):

Rstudio ggplot2 cheat sheet

Data Carpentry, 2017.
License. Questions? Feedback? Please file an issue on GitHub.
On Twitter: @datacarpentry