R Ggplot Cheat Sheet



  1. R Studio Cheat Sheet Ggplot
  2. Rstudio Ggplot2 Cheat Sheet
  3. Rstudio Ggplot2
  4. R Ggplot Cheat Sheet
  5. Ggplot2 Cheat Sheet Pdf
  • Create plots with {ggplot2}
    • Further personalization

R is known to be a really powerful programming language when it comes to graphics and visualizations (in addition to statistics and data science of course!).

This tidyverse cheat sheet will guide you through the basics of the tidyverse, and 2 of its core packages: dplyr and ggplot2! The tidyverse is a powerful collection of R packages that you can use for data science.

  • Learning ggplot2. Esquisse is awesome, but eventually you’ll want to learn ggplot. Here are a few learning tips. PRO TIP 1 – Use my Cheat Sheet. I’ve added the Tidyverse to my Ultimate R Cheatsheet (see page 1). Click the “CS” next to ggplot to get the ggplot2 Cheat Sheet.
  • 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.

To keep it short, graphics in R can be done in three ways, via the:

  1. {graphics} package (the base graphics in R, loaded by default)
  2. {lattice} package which adds more functionalities to the base package
  3. {ggplot2} package (which needs to be installed and loaded beforehand)

The {graphics} package comes with a large choice of plots (such as plot, hist, barplot, boxplot, pie, mosaicplot, etc.) and additional related features (e.g., abline, lines, legend, mtext, rect, etc.). It is often the preferred way to draw plots for most R users, and in particular for beginners to intermediate users.

Since its creation in 2005 by Hadley Wickham, {ggplot2} has grown in use to become one of the most popular R packages and the most popular package for graphics and data visualizations. The {ggplot2} package is a much more modern approach to creating professional-quality graphics. More information about the package can be found at ggplot2.tidyverse.org.

In this article, we will see how to create common plots such as scatter plots, line plots, histograms, boxplots, barplots, density plots in R with this package. If you are unfamiliar with any of these types of graph, you will find more information about each one (when to use it, its purpose, what does it show, etc.) in my article about descriptive statistics in R.

To illustrate plots with the {ggplot2} package we will use the mpg dataset available in the package. The dataset contains observations collected by the US Environmental Protection Agency on fuel economy from 1999 to 2008 for 38 popular models of cars (run ?mpg for more information about the data):

Before going further, let’s transform the cyl, drv, fl, year and class variables in factor with the transform() function:

For the interested reader, see more data manipulation techniques in R.

The {ggplot2} package is based on the principles of “The Grammar of Graphics” (hence “gg” in the name of {ggplot2}), that is, a coherent system for describing and building graphs. The main idea is to design a graphic as a succession of layers.

The main layers are:

  1. The dataset that contains the variables that we want to represent. This is done with the ggplot() function and comes first.
  2. The variable(s) to represent on the x and/or y-axis, and the aesthetic elements (such as color, size, fill, shape and transparency) of the objects to be represented. This is done with the aes() function (abbreviation of aesthetic).
  3. The type of graphical representation (scatter plot, line plot, barplot, histogram, boxplot, etc.). This is done with the functions geom_point(), geom_line(), geom_bar(), geom_histogram(), geom_boxplot(), etc.
  4. If needed, additional layers (such as labels, annotations, scales, axis ticks, legends, themes, facets, etc.) can be added to personalize the plot.

To create a plot, we thus first need to specify the data in the ggplot() function and then add the required layers such as the variables, the aesthetic elements and the type of plot:

  • data in ggplot() is the name of the data frame which contains the variables var_x and var_y.
  • The + symbol is used to indicate the different layers that will be added to the plot. Make sure to write the +symbol at the end of the line of code and not at the beginning of the line, otherwise R throws an error.
  • The layer aes() indicates what variables will be used in the plot and more generally, the aesthetic elements of the plot.
  • Finally, x in geom_x() represents the type of plot.
  • Other layers are usually not required unless we want to personalize the plot further.

Note that it is a good practice to write one line of code per layer to improve code readability.

In the following sections we will show how to draw the following plots:

  • scatter plot
  • line plot
  • histogram
  • density plot
  • boxplot
  • barplot

In order to focus on the construction of the different plots and the use of {ggplot2}, we will restrict ourselves to drawing basic (yet beautiful) plots without unnecessary layers. For the sake of completeness, we will briefly discuss and illustrate different layers to further personalize a plot at the end of the article (see this section).

Note that if you still struggle to create plots with {ggplot2} after reading this tutorial, you may find the {esquisse} addin useful. This addin allows you to interactively (that is, by dragging and dropping variables) create plots with the {ggplot2} package. Give it a try!

Scatter plot

We start by creating a scatter plot using geom_point. Remember that a scatter plot is used to visualize the relation between two quantitative variables.

  1. We start by specifying the data:
  1. Then we add the variables to be represented with the aes() function:
  1. Finally, we indicate the type of plot:

You will also sometimes see the aesthetic elements (aes() with the variables) inside the ggplot() function in addition to the dataset:

This second method gives the exact same plot than the first method. I tend to prefer the first method over the second for better readability, but this is more a matter of taste so the choice is up to you.

Line plot

Line plots, particularly useful in time series or finance, can be created similarly but by using geom_line():

Combination of line and points

An advantage of {ggplot2} is the ability to combine several types of plots and its flexibility in designing it. For instance, we can add a line to a scatter plot by simply adding a layer to the initial scatter plot:

Histogram

A histogram (useful to visualize distributions and detect potential outliers) can be plotted using geom_histogram():

By default, the number of bins is equal to 30. You can change this value using the bins argument inside the geom_histogram() function:

Here I specify the number of bins to be equal to the square root of the number of observations (following Sturge’s rule) but you can specify any numeric value.

Density plot

Density plots can be created using geom_density():

Combination of histogram and densities

We can also superimpose a histogram and a density curve on the same plot:

Or superimpose several densities:

The argument alpha = 0.25 has been added for some transparency. More information about this argument can be found in this section.

Boxplot

A boxplot (also very useful to visualize distributions and detect potential outliers) can be plotted using geom_boxplot():

It is also possible to plot the points on the boxplot with geom_jitter(), and to vary the width of the boxes according to the size (i.e., the number of observations) of each level with varwidth = TRUE:

The geom_jitter() layer adds some random variation to each point in order to prevent them from overlapping (an issue known as overplotting).1 Moreover, the alpha argument adds some transparency to the points (see more in this section) to keep the focus on the boxes and not on the points.

Finally, it is also possible to divide boxplots into several panels according to the levels of a qualitative variable:

For a visually more appealing plot, it is also possible to use some colors for the boxes depending on the x variable:

In that case, it best to remove the legend as it becomes redundant. See more information about the legend in this section.

If you are unhappy with the default colors provided in {ggplot2}, you can change them manually with the scale_fill_manual() layer:

Barplot

A barplot (useful to visualize qualitative variables) can be plotted using geom_bar():

By default, the heights of the bars correspond to the observed frequencies for each level of the variable of interest (drv in our case).

Again, for a more appealing plot, we can add some colors to the bars with the fill argument:

We can also create a barplot with two qualitative variables:

In order to compare proportions across groups, it is best to make each bar the same height using position = 'fill':

To draw the bars next to each other for each group, use position = 'dodge':

Further personalization

Title and axis labels

The first things to personalize in a plot is the labels to make the plot more informative to the audience. We can easily add a title, subtitle, caption and edit axis labels with the labs() function:

As you can see in the above code, you can save one or more layers of the plot in an object for later use. This way, you can save your “main” plot, and add more layers of personalization until you get the desired output. Here we saved the main scatter plot in an object called p and we will refer to it for the subsequent personalizations.

You can also edit the alignment, the size and the shape of the title and subtitle via the theme() layer and the element_text() function:

If the title or subtitle is long and you want to divide it into multiple lines, use n:

Axis ticks

Axis ticks can be adjusted using scale_x_continuous() and scale_y_continuous() for the x and y-axis, respectively:

Log transformations

In some cases, it is useful to plot the log transformation of the variables. This can be done with the scale_x_log10() and scale_y_log10() functions:

Limits

The most convenient way to control the limits of the plot is to use again the scale_x_continuous() and scale_y_continuous() functions in addition to the limits argument:

It is also possible to simply take a subset of the dataset with the subset() or filter() function. See how to subset a dataset if you need a reminder.

Scales for better axis formats

Depending on your data, it is possible to format axes in a certain way with the {scales} package. The formats I use the most are comma and label_number_si() which format large numbers in a more-readable way.

For this example, we multiply both variables by 1000 to have larger numbers and then we apply a different format to each axis:

As you can see, numbers on the y-axis are automatically labeled with the best SI prefix (“K” for values (ge) 10e3, “M” for (ge) 10e6, “B” for (ge) 10e9, and “T” for (ge) 10e12) and numbers on the x-axis are displayed as 2,000, 3,000, etc. instead of 2000, 3000, etc.

These two formats make large numbers easier to read. Other formats are possible such as using dollar signs, percentage signs, dates etc. See more information in the package’s documentation.

Legend

By default, the legend is located to the right side of the plot (when there is a legend to be displayed of course). To control the position of the legend, we need to use the theme() function in addition to the legend.position argument:

Replace 'top' by 'left' or 'bottom' to change its position and by 'none' to remove it.

The title of the legend can be edited with the labs() layer:

Note that the argument inside labs() must match the one inside the aes() layer (in this case: color).

The title of the legend can also be removed with legend.title = element_blank() inside the theme() layer:

The legend now appears at the bottom of the plot, without the legend title.

Shape, color, size and transparency

There are a very large number of options to improve the quality of the plot or to add additional information. These include:

  • shape,
  • size,
  • color, and
  • alpha (transparency).

We can for instance change the shape of all points in a scatter plot by adding shape to geom_point(), or vary the shape according to the values taken by another variable (in that case, the shape argument must be inside aes()):2

Following the same principle, we can modify the color, size and transparency of the points based on a qualitative or quantitative variable. Here are some examples:

We can of course mix several options (shape, color, size, alpha) to build more complex graphics:

If you are unhappy with the default colors, you can change them manually with the scale_colour_manual() layer (for qualitative variables) and the scale_coulour_gradient2() layer (for quantitative variables):

Text and labels

To add a label on a point (for example the row number), we can use the geom_text() and aes() functions:

To add text on the plot, we use the annotate() function:

Read the article on correlation coefficient and correlation test in R to see how I computed the correlation coefficient (rho) and the p-value of the correlation test.

Smooth and regression lines

In a scatter plot, it is possible to add a smooth line fitted to the data:

In the context of simple linear regression, it is often the case that the regression line is displayed on the plot. This can be done by adding method = lm (lm stands for linear model) in the geom_smooth() layer:

It is also possible to draw a regression line for each level of a categorical variable:

The se = FALSE argument removes the confidence interval around the regression lines.

Facets

facet_grid allows you to divide the same graphic into several panels according to the values of one or two qualitative variables:

It is then possible to add a regression line to each facet:

facet_wrap() can also be used, as illustrated in this section.

Themes

Pdf

Several functions are available in the {ggplot2} package to change the theme of the plot. The most common themes after the default theme (i.e., theme_gray()) are the black and white (theme_bw()), minimal (theme_minimal()) and classic (theme_classic()) themes:

I tend to use the minimal theme for most of my R Markdown reports as it brings out the patterns and points and not the layout of the plot, but again this is a matter of personal taste. See more themes at ggplot2.tidyverse.org/reference/ggtheme.html and in the {ggthemes} package.

In order to avoid having to change the theme for each plot you create, you can change the theme for the current R session using the theme_set() function as follows:

Interactive plot with {plotly}

You can easily make your plots created with {ggplot2} interactive with the {plotly} package:

You can now hover over a point to display more information about that point. There is also the possibility to zoom in and out, to download the plot, to select some observations, etc. More information about {plotly} for R can be found here.

Combine plots with {patchwork}

There are several ways to combine plots made in {ggplot2}. In my opinion, the most convenient way is with the {patchwork} package using symbols such as +, / and parentheses.

We first need to create some plots and save them:

Now that we have 3 plots saved in our environment, we can combine them. To have plots next to each other simply use the + symbol:

To display them above each other simply use the / symbol:

And finally, to combine them above and next to each other, mix +, / and parentheses:

See more ways to combine plots with:

  • grid.arrange() from the {gridExtra} package
  • plot_grid() from the {cowplot} package

Flip coordinates

Flipping coordinates of your plot is useful to create horizontal boxplots, or when labels of a variable are so long that they overlap each other on the x-axis. See with and without flipping coordinates below:

This can be done with many types of plot, not only with boxplots. For instance, if a categorical variable has many levels or the labels are long, it is usually best to flip the coordinates for a better visual:

Save plot

The ggsave() function will save the most recent plot in your current working directory unless you specify a path to another folder:

You can also specify the width, height and resolution (dpi) as follows:

Managing dates

If the time variable in your dataset is in date format, the {ggplot2} package recognizes the date format and automatically uses a specific type for the axis ticks.

There is no time variable with a date format in our dataset, so let’s create a new variable of this type thanks to the as.Date() function:

See the first 6 observations of this date variable and its class:

The new variable date is correctly specified in a date format.

Most of the time, with a time variable, we want to create a line plot with the date on the X-axis and another continuous variable on the Y-axis, like the following plot for example:

As soon as the time variable is recognized as a date, we can use the scale_x_date() layer to change the format displayed on the X-axis. The following table shows the most frequent date formats:

Run ?strptime() to see many more date formats available in R.

For this example, let’s add the year in addition to the unabbreviated month:

It also possible to control the breaks to display on the X-axis with the date_breaks argument. For this example, let’s say we want to display the day as number and the abbreviated month for each interval of 10 days:

If labels displayed on the X-axis are unreadable because they overlap each other, you can rotate them with the theme() layer and the angle argument:

I recently learned a tip very useful when drawing plots with {ggplot2}. If like me, you often comment and uncomment some lines of code in your plot, you know that you cannot transform the last line into a comment without removing the + sign in the line just above.

Adding a line NULL at the end of your plots will avoid an error if you forget to remove the + sign in the last line of your code. See with this basic example:

This trick saves me a lot of time as I do not need to worry about making sure to remove the last + sign after commenting some lines of code in my plots.

If you find this trick useful, you may like these other tips and tricks in RStudio and R Markdown.

By now you have seen that {ggplot2} is a very powerful and complete package to create plots in R. This article illustrated only the tip of the iceberg, and you will find many tutorials on how to create more advanced plots and visualizations with {ggplot2} online. If you want to learn more than what is described in the present article, I highly recommend starting with:

  • the chapters Data visualisation and Graphics for communication from the book R for Data Science from Garrett Grolemund and Hadley Wickham
  • the book ggplot2: Elegant Graphics for Data Analysis from Hadley Wickham
  • the book R Graphics Cookbook from Winston Chang
  • the ggplot2 extensions guide which lists many of the packages that extend {ggplot2}
  • the {ggplot2} cheat sheet

Thanks for reading. I hope this article helped you to create your first plots with the {ggplot2} package. As a reminder, for simple graphs, it is sometimes easier to draw them via the {esquisse} addin. After some time, you will quickly learn how to create them by yourselves and in no time you will be able to build complex and sophisticated data visualizations.

As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.

  1. Use the geom_jitter() layer with caution because, although it makes a plot more revealing at large scales, it also makes it slightly less accurate at small scales since some randomness is added to the points.↩︎

  2. There are (at the time of writing) 26 shapes accepted in the shape argument. See this documentation for all available shapes.↩︎


Related articles


Liked this post?

Get updates every time a new article is published.
No spam and unsubscribe anytime.Share on:

Learning Objectives

  • Understand the “grammar of graphics”
  • Produce scatter plots, boxplots, bar graphs, 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 data frame.

We start by loading the required packages. ggplot2 is included in the tidyverse package, and is the current standard for data visualization in R. Authored by Hadley Wickham, gg stands for “Grammar of Graphics.” In learning ggplot2, you may find the following cheat sheet to be a helpful reference.

Overview

Basic grammar

Hadley’s Grammar of Graphics is outlined in detail in this article. Here, he illustrates his principles using a small data set similar to the following:

To visualize any data set using the Grammar of Graphics, it helps to understand the 3 components of which any graph is comprised:

  1. Geoms
  2. Scales
  3. Data columns

Geoms are the visual entities that we see on a graph. In the image below, we see three examples of geoms: a circular point, a bar, and a line:

Scales control how the data columns map to the aesthetic attributes of the geoms. For example, is the point geom yellow or blue? Is it large or small? Is it high or low? Left or right? These aesthetic attributes are respectively controlled by the color, size, y, and x scales:

Additional scales in ggplot2 are:

  • shape
  • linetype (for the line geom)
  • fill (for the bar and point geoms)

Any plot created with ggplot2 requires these ingredients. To create a plot, one must specify the desired geom; which data variables are to be aesthetically mapped to the geom; and the scales to use to control the mapping. The skeleton of any ggplot2 command is as follows; parts in italics are to be replaced with specific data variable names, geoms, and scales:

ggplot(data = nameofdata) + geom_nameofgeom(aes(scale1 = variable1, scale2 = variable2))

At a minimum, most geoms require the x scale.

Let’s begin by mapping A and B to the point geom on a Cartesian plane. Note in ?geom_point that two scales are required for aesthetic mappings to point geoms, x and y:

We can employ other scales outside of aesthetic data mappings. For example, if we want to change the aesthetic mapping of the above scatterplot by changing the shape, color, and size scale, we can do so with the following:

Notice in the above code that the scales that are not mapped to data are outside the aes() command.

R Studio Cheat Sheet Ggplot

As an aside, looking at the ?shape help file, we can find code to see all possible shapes:

Now suppose we want to aesthetically map other variables with the shape, color, and size scales. We must now put these specifications inside the aes() command and specify the variables we wish to map. Consider the following code, and note the different looks, error messages and warnings that appear when attempting to apply aesthetic mappings using various scales depending on the data type. In ggplot-speak, “continuous” refers to quantitative data in general; while “discrete” refers to categorical data:

Challenge

Re-create the following plots:

Note some interesting concepts illustrated here:

  • Continuous (numeric, quantitative) variables should be mapped using size or color scales; these are the scales that can encode quantity.
  • Discrete (categorical) variables should be mapped with shape or color scales; these are the scales that are best used for indicating “categories.”

Layers

A very important aspect of the ggplot2 package is the idea of layers. Aesthetic mappings to different geoms can take place simply by specifying additional mappings with a + sign. For example, suppose we want to create the above scatterplots with points and lines. This requires two aesthetic mappings: one from the data to the points geom, and one from the data to the lines geom. We can see this in what follows. Note that because both geom_point() and geom_line() rely on the same aesthetic mapping, we could simplify the code by specifiying the appropriate mapping in the initial ggplot() command. The following two lines of code are equivalent:

Challenge

Re-create the following plots. What happens if you try to map variable C to geom_line() using the size scale?

Analysis of ecology data

Now let’s start visualizing some real data. If not still in the workspace, load the data we saved in the previous lesson.

When plotting scatterplots, ggplot likes data in the ‘long’ format: i.e., a column for every dimension, and a row for every observation. However, when plotting barplots where the height of the bars are counts or percents, pre-aggregated data (e.g., the output from a series of dplyr commands) may work better. Well-structured data will save you lots of time when making figures with ggplot.

To create a scatterplot of hind foot length versus weight, 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 scales to define the geoms
  • add geoms – graphical representation of the data in the plot (points, lines, bars). To add a geom to the plot use + operator

Recall that the + in the ggplot2 package allows you to modify existing ggplot Citrix plugin for mac. 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:

Remember:

  • 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 datasets. For data sets with large numbers of observations, such as the surveys 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 tessellated into hexagons. Each hexagon is assigned a color based on the number of observations that fall within its boundaries. To use hexagonal binning with ggplot2, first install the R package hexbin from CRAN:

Then use the geom_hex() function:

  • 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:

Challenge

Use what you just learned to create a scatter plot of weight over species_id with the plot types showing in different colors. Is this a good way to show this type of data?

Boxplot

We can use boxplots to visualize 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, it 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). Try making these modifications:

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

So far, we’ve looked at the distribution of weight within species. Try making a new plot to explore the distribution of another variable within each species.

  • Create boxplot for hindfoot_length. Overlay the boxplot layer on a jitter layer to show actual measurements.

  • 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?

Bar graphs

Bar graphs are frequently used for visualizing the number of observations in each category of a categorical variable, or summary statistics (like a mean or median) of a quantitative variable across levels of a categorical variable.

By default, ggplot counts the number of observations in each level and plots those counts on the y-axis. For example, consider plotting the number of each sex in the data set:

However, what if we wanted to visualize the average hind foot length for each sex instead?
We first need to use dplyr to group the data by sex and compute the mean length. We can also filter out the unlabeled sexes:

We now want to map the mean_length variable to the y scale. We must specify stat='identity' inside the geom_bar() command, to specify that we want to use the actual values in the mean_length column on the y-axis instead of the default count:

Challenges

  • Create a bar graph that shows the number of each species in each data set. What are the issues with this plot?
  • Use group_by(), summarize(), n() and mean() to create a data set with the species IDs in one column, the number of observations in the second column, and the mean hind foot length in the third column.
  • Filter this data set to contain only the species with 5 or more entries. Re-create the bar graph showing the count of each species.
  • Create a second bar graph showing the mean foot length of each species. Which has the largest? The smallest?

Plotting time series data

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

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

Unfortunately, this does not work because we plotted 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 (using color also automatically groups the data):

Faceting

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

Rstudio Ggplot2 Cheat Sheet

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:

We can now make the faceted plot by splitting further by sex using color (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 remove the grid:

ggplot2 themes

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

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.

Challenge

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

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 males and females has changed through time:

Customization

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

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

The axes have more informative names, but their readability can be improved by increasing the font size:

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:

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

Challange

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 for inspiration.

Rstudio Ggplot2

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 its labels?
  • Try using 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 favorite format. You can easily change the dimension (and resolution) of your plot by adjusting the appropriate arguments (width, height and dpi):

R Ggplot Cheat Sheet

Note: The parameters width and height also determine the font size in the saved plot.

Page build on: 2017-08-15 10:21:58

Ggplot2 Cheat Sheet Pdf

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