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.
We start with the the quick setup and a default plot followed by a range of adjustments below.
- Quick-setup: The dataset
- A default plot in ggplot2
- Working with the title
- Add a title (ggtitle() or labs())
- Make title bold and add a little space at the baseline (face, vjust)
- Use a non-traditional font in your title (family)
- Change spacing in multi-line text (lineheight)
- Working with axes
- Add x and y axis labels (labs(), xlab())
- Get rid of axis tick and labels (theme(), axis.ticks.y)
- Change size of tick text (axis.text.x)
- Move the labels away from the plot (and add color) (theme(), axis.title.x)
- Limit an axis to a range (ylim, scale_x_continuous(), coord_cartesian())
- If you want the axes to be the same (coord_equal())
- Working with the legend
- Turn off the legend title (legend.title)
- Change the styling of the legend title (legend.title)
- Change the title of the legend (name)
- Change the background boxes in the legend (legend.key)
- Change the size of the symbols in the legend only (guides(), guide_legend)
- Leave a layer off the legend (show_guide)
- Manually adding legend items (guides(), override.aes)
- Working with the background colors
- Change the panel color (panel.background)
- Change the grid lines (panel.grid.major)
- Change the plot background (not the panel) color (plot.background)
- Working with multi-panel plots
- Create a single row of plots based on one variable (facet_wrap())
- Create a matrix of plots based on one variable (facet_wrap())
- Allow scales to roam free (scales)
- Create a grid of plots using two variables (facet_grid())
- Put two (potentially unrelated) plots side by side (pushViewport())
- Working with themes
- Use a new theme (theme_XX())
- Tip on creating a custom theme
- Working with colors
- Categorical variables: manually select the colors (scale_color_manual)
- Categorical variables: try a built-in palette (based on colorbrewer2.org) (scale_color_brewer):
- Color choice with continuous variables (scale_color_gradient(), scale_color_gradient2())
- Working with annotation
- Add text annotation in the top-right, top-left etc. (annotation_custom() and textGrob())
Working with coordinates - Flip a plot on it’s side (coord_flip())
- Add text annotation in the top-right, top-left etc. (annotation_custom() and textGrob())
- Working with plot types
- Alternatives to the box plot (geom_jitter() and geom_violin())
- Create a ribbon (geom_ribbon())
- Create interactive, online versions of your plots (easier than you think)