Beautiful plotting in R: A ggplot2 cheatsheet

Even the most experienced R users need help creating elegant graphics. The ggplot2 library is a phenomenal tool for creating graphics in R but even after many years of near-daily use we still need to refer to our Cheat Sheet. Up until now, we’ve kept these key tidbits on a local PDF. But for our own benefit (and hopefully yours) we decided to post the most useful bits of code.

* Last updated January 20, 2016 (with ggplot2 2.0 replace vjust with margin for title text)

Quick-setup: The dataset

We’re using data from the National Morbidity and Mortality Air Pollution Study (NMMAPS). To make the plots manageable we’re limiting the data to Chicago and 1997-2000. For more detail on this dataset, consult Roger Peng’s book Statistical Methods in Environmental Epidemiology with R.

Working with the title

Add a title (ggtitle() or labs())

Make title bold and add a little space at the baseline (face, margin)

In ggplot2 versions before 2.0 I used the vjust argument to move the title away from the plot. With 2.0 this no longer works and a blog comment (below) helped me identify an alternative using this link. The margin argument uses the margin function and you provide the top, right, bottom and left margins (the default unit is points).

If you want the axes to be the same (coord_equal())

There must be a better way than this. In the example, I’m plotting temperature against temperature with some random noise (for demonstration purposes) and I want both axes to be the same scale/same range.

Change the size of the symbols in the legend only (guides(), guide_legend)

Leave a layer off the legend (show_guide)

Let’s say you have a point layer and you add label text to it. By default, both the points and the label text end up in the legend like this (again, who would make a plot like this? It’s for demonstration purposes):

g+geom_text(data=nmmaps, aes(date, temp, label=round(temp)), size=4)

You can use show_guide=FALSE to turn a layer off in the legend. Useful!

Manually adding legend items (guides(), override.aes)

ggplot2 will not add a legend automatically unless you map aethetics (color, size etc) to a variable. There are times, though, that I want to have a legend so that it’s clear what you’re plotting. Here is the default:

# here there is no legend automatically
ggplot(nmmaps, aes(x=date, y=o3))+geom_line(color="grey")+geom_point(color="red")

We can force a legend by mapping to a “variable”. We are mapping the lines and the points using aes and we are mapping not to a variable in our dataset but to a single string (so that we get just one color for each).

Tantalizingly close! But we don’t want a line with a point for both. Line=grey and point=red. The final step is to override the aesthetics in the legend. The guide() function allows us to control guides like the legend:

Change the plot background (not the panel) color (plot.background)

Working with margins

Changing the plot margin (plot.margin)

I sometimes find that I need to add a little space to one margin of my plot. Similar to the previous examples we can use an argument to the theme() function. In this case the argument is plot.margin. In order to illustrate I’m going to add a background color using plot.background so you can see the default:

Now let’s add extra space to both the left and right. The argument, plot.margin, can handle a variety of different units (cm, inches etc) but it requires the use of the function unit from the package grid to specify the units. Here I’m using a 6 cm margin on the right and left.

Creating multi-panel plots

The ggplot2 package has two nice functions for creating multi-panel plots. They are related but a little different facet_wrap creates essentially a ribbon of plots based on a single variable while facet_grid can take two variables.

Create a matrix of plots based on one variable (facet_wrap())

Allow scales to roam free (scales)

The default for multi-panel plots in ggplot2 is to use equivalent scales in each panel. But sometimes you want to allow a panel’s own data to determine the scale. This is not often a good idea since it may give your user the wrong impression about the data but to do this you can set scales="free" like this:

Working with themes

You can change the entire look of the plots by using custom theme. As an example, Jeffrey Arnold has put together the library ggthemes with several custom themes. For a list you can visit the ggthemes site. Here is an example:

Change the size of all plot text elements

Personally, I find default size of the tick text, legends and other elements to be a little too small. Luckily it’s incredibly easy to change the size of all the text elements at once. If you look below at the section on creating a custom theme you’ll notice that the sizes of all the elements are relative (rel()) to the base_size. As a result, you can simply change the base_size and you’re done. Here is the code:

Tip on creating a custom theme

If you want to change the theme for an entire session you can use theme_set as in theme_set(theme_bw()). The default is called theme_gray. If you wanted to create your own custom theme, you could extract the code directly from the gray theme and modify. Note that the rel() function change the sizes relative to the base_size.

Working with colors

For simple applications working with colors is straightforward in ggplot2 but when you have more advanced needs it can be a challenge. For a more advaned treatment of the topic you should probably get your hands on Hadley’s book which has nice coverage. There are a few other good sources including the R Cookbook and the ggplot2 online docs. Tian Zheng at Columbia has created a useful PDF of R colors.

In order to use color with your data, most importantly, you need to know if you’re dealing with a categorical or continuous variable.

In our example we will change the color variable to ozone, a continuous variable that is strongly related to temperature (higher temperature = higher ozone). The function scale_color_gradient() is a sequential gradient while scale_color_gradient2() is diverging.

Working with annotation

I often have trouble figuring out the best way to add text to a plot in say, the top left corner, without using hard-coded coordinates. With ggplot2 you can set annotation coordinates to Inf but I find this only moderately useful. Here is an example (based on code from here) using the library grid that allows you to specify the location based on scaled coordinates where 0 is low and 1 is high.

The grobTree function (from grid) creates a grid graphical object and textGrob creates the text graphical object. The annotation_custom() function comes from ggplot2 and is designed to use a grob as input.

‘Big deal’ you say!? It is a big deal. The value here is particularly evident when you have multiple plots with different scales. In the plot below you see that the axis scales vary yet the same code as above can be used to put the annotation is the same place on each facet. Nice!

Alternative to a box plot: plot of points

Not only boring but uninformative, you could add transparency to deal with overplotting, but this is not good either. Let’s try something else.

Alternative to a box plot: jitter the points (geom_jitter())

Try adding a little jitter to the data. I like this for in-house visualization but be careful using jittering because you’re purposely adding noise to your data and this can result in misinterpretation of your data.

This is nice and I like it. But be wary of using unusual plot types, they take more time for your users to understand. Sometimes the simplest and most conventional plot type is your best bet when sharing with others. Box plots may be boring but people know how to interpret them immediately.

Add a ribbon to your plot (geom_ribbon())

This is not the perfect dataset for this, but using ribbon can be useful. In this example we will create a 30-day running average using the filter() function so that our ribbon is not too noisy.

Create a tiled correlation plot (geom_tile())

I’ll admit that I find creating tiled correlation plots a bit cumbersome, I always have to copy and paste code from a previous project. Nevertheless, it’s a useful plot type so I’m posting the code here.

First step is to create the correlation matrix. I’m using Pearson because all the variables are fairly normally distributed – you may want to consider Spearman if your variables follow a different pattern. Note that since a correlation matrix has redundant information I’m setting half of it to NA.

Working with smooths

You’ve likely already learned how amazingly easy it is to add a smooth to your data using ggplot2. You can simply use stat_smooth() which will add a LOESS smooth if you have fewer than 1000 points or a GAM otherwise. Since we have more than 1000 points the smooth is a GAM.

Convert your plots to online, interactive graphics using Plot.ly

Plot.ly is a great tool for easily creating online, interactive graphics directly from your ggplot2 plots. The process is surprisingly easy, and can be done from within R, but there are enough steps that I describe how to create graphics like the one below in a separate post.

Note that I have been using a free plot.ly account for this one plot which limits to 500 views per day. After 500 views plot.ly sends an incredible number of e-mails about the exceedance (sometimes more than 15 per day). So for now I have turned off the plot below and you’ll have to imagine it!

This post created in RStudio using knitr. R version 3.0.2 (2013-09-25) and ggplot2 version 0.9.3.1.

55 responses

Awesome job! One of the most comprehensive tutorials on ggplot2 I’ve ever come through. By the way, how can you increase the size of x- & y-axis legend? Sorry if I missed it in your post. Thank you so much!

I have ~ 14,000 points for my XY scatter, so I have to necessarily use low alpha=0.025 or it will become too dark. However, when I want to display just 7 points of interest, they are not visible because of the low alpha. I am assuming that it is possible to retain alpha for the XY scatter points, and change alpha for just my points of interest? I just dont know how though, could you help please? Thanks!
My syntax so far, using the awesome examples on your website, looks like this:
>input=read.table(“PfamAseeds_SeqIdnty_Stats_R_Annotated_ScatterPlot.txt”,sep=”\t”,header=TRUE)
> df=as.data.frame(input)
> summary(df)
PfamA_ID SeqIdentityMean SeqIdentityStdDev
:14823 Min. :0.0718 Min. :0.00000
PF00646.28: 1 1st Qu.:0.2510 1st Qu.:0.02910
.
.
.
(Other) : 3
> trial trial

If you look at the help for scale_color_grey() you’ll see that there are arguments for start and end. So scale_color_grey(start=0.8, end=0.2) will give you light to dark. Regarding scale_color_brewer() those are pre-built scales so if you want to drop a color you’d likely need to use scale_color_manual() after figuring out the colors. To figure out the colors:

Helpful, thanks. I find it useful to look at the default text margins to take as a starting point when adjusting. For example, the default plot.title margin (see theme_grey function) is margin = margin(b = half_line * 1.2), where half_line is half the base_size font, or in short the bottom title margin is .5*11*1.2 = 6.6 pt.

Is there any way to customize where the tick marks are along the x-axis? I have a time series, and I’d like to have major tick marks every January, then minor tick marks every quarter (every April, July and October). Preferably, I’d also like the labels to read “Jan 2012”, “Apr 2012”, etc instead of just the numeric year.

I inserted minor ticks in the y-axis of my ggplot graph without labels and I wanted it to be shorter than the tick marks with labels. Wondering how this is done in r or I am looking for a r code to do it. Thanks a lot.

I have a small dataset (2 variables x and y, 15 instances), and would like a matrix of scatterplots y vs. x, y vs. log(x), y vs. sqrt(x), y vs. I(1/x), log(y) vs. x, log(y) vs. sqrt(x), …, I(1/y) vs. I(1/x). The ‘pairs’ command in basic R gives too much (I only want y or some function of y on the vertical axis). How can I get this matrix of 16 scatterplots using ggplot2? Such a plot is useful in searching for transformations of x and y so that the relationship is linear with constant variance (for an analysis using simple linear regression). Thanks!

Yes, how to do it depends on what you’re trying to do. Probably the easiest thing is to have a new dataset that has the same variable you’re using to break on facets with the text you want. But, again, really depends on what you’re trying to do. At this link (https://gist.github.com/kdauria/524eade46135f6348140) is an example of how to add a custom linear regression formula.

This is an excellent resource. Thank you for posting. I have a question about facet_grid(). I am using it to plot 43 histograms. Everything works nicely, but all the histograms are printed next to each other in one long line. Is there a way to get them to print in 2 or 3 rows.