Visualizing data with ggplot2. Starting with ggplot2. The ggplot2 Cheat Sheet by RStudio. March 2020 @ 23:20 Site last updated 9. Get the Ultimate R Cheat Sheet here: Learn R here: https://university.business-science.io/p/ds4b-101-r-busi.

Overview

Questions
  • How can I create publication-quality graphics in R?

Objectives
  • To be able to use ggplot2 to generate publication quality graphics.

  • To apply geometry, aesthetic, and statistics layers to a ggplot plot.

  • To manipulate the aesthetics of a plot using different colors, shapes, and lines.

  • To improve data visualization through transforming scales and paneling by group.

  • To save a plot created with ggplot to disk.

Ggplot2 Example

Plotting our data is one of the best ways toquickly explore it and the various relationshipsbetween variables.

There are three main plotting systems in R,the base plotting system, the latticepackage, and the ggplot2 package.

Ggplot2 Cheat Sheet 2020

Today we’ll be learning about the ggplot2 package, becauseit is the most effective for creating publication qualitygraphics.

ggplot2 is built on the grammar of graphics, the idea that any plot can beexpressed from the same set of components: a data set, acoordinate system, and a set of geoms – the visual representation of datapoints.

The key to understanding ggplot2 is thinking about a figure in layers.This idea may be familiar to you if you have used image editing programs like Photoshop, Illustrator, orInkscape.

Let’s start off with an example:

So the first thing we do is call the ggplot function. This function lets Rknow that we’re creating a new plot, and any of the arguments we give theggplot function are the global options for the plot: they apply to alllayers on the plot.

We’ve passed in two arguments to ggplot. First, we tell ggplot what data wewant to show on our figure, in this example the gapminder data we read inearlier. For the second argument, we passed in the aes function, whichtells ggplot how variables in the data map to aesthetic properties ofthe figure, in this case the x and y locations. Here we told ggplot wewant to plot the “gdpPercap” column of the gapminder data frame on the x-axis, andthe “lifeExp” column on the y-axis. Notice that we didn’t need to explicitlypass aes these columns (e.g. x = gapminder[, 'gdpPercap']), this is becauseggplot is smart enough to know to look in the data for that column!

By itself, the call to ggplot isn’t enough to draw a figure:

We need to tell ggplot how we want to visually represent the data, which wedo by adding a new geom layer. In our example, we used geom_point, whichtells ggplot we want to visually represent the relationship between x andy as a scatterplot of points:

Challenge 1

Modify the example so that the figure shows how life expectancy haschanged over time:

Hint: the gapminder dataset has a column called “year”, which should appearon the x-axis.

Solution to challenge 1

Here is one possible solution:

Challenge 2

In the previous examples and challenge we’ve used the aes function to tellthe scatterplot geom about the x and y locations of each point.Another aesthetic property we can modify is the point color. Modify thecode from the previous challenge to color the points by the “continent”column. What trends do you see in the data? Are they what you expected?

Solution to challenge 2

The solution presented below adds color=continent to the call of the aesfunction. The general trend seems to indicate an increased life expectancyover the years. On continents with stronger economies we find a longer lifeexpectancy.

Layers

Using a scatterplot probably isn’t the best for visualizing change over time.Instead, let’s tell ggplot to visualize the data as a line plot:

Instead of adding a geom_point layer, we’ve added a geom_line layer. We’veadded the byaesthetic, which tells ggplot to draw a line for eachcountry.

But what if we want to visualize both lines and points on the plot? We canadd another layer to the plot:

It’s important to note that each layer is drawn on top of the previous layer. Inthis example, the points have been drawn on top of the lines. Here’s ademonstration:

In this example, the aesthetic mapping of color has been moved from theglobal plot options in ggplot to the geom_line layer so it no longer appliesto the points. Now we can clearly see that the points are drawn on top of thelines.

Tip: Setting an aesthetic to a value instead of a mapping

So far, we’ve seen how to use an aesthetic (such as color) as a mapping to a variable in the data. For example, when we use geom_line(mapping = aes(color=continent)), ggplot will give a different color to each continent. But what if we want to change the colour of all lines to blue? You may think that geom_line(mapping = aes(color='blue')) should work, but it doesn’t. Since we don’t want to create a mapping to a specific variable, we can move the color specification outside of the aes() function, like this: geom_line(color='blue').

Download 3,581 black tree free vectors. Choose from over a million free vectors, clipart graphics, vector art images, design templates, and illustrations created by artists worldwide! Black tree drawing.

Challenge 3

Switch the order of the point and line layers from the previous example. Whathappened?

Solution to challenge 3

The lines now get drawn over the points!

Transformations and statistics

ggplot2 also makes it easy to overlay statistical models over the data. Todemonstrate we’ll go back to our first example:

Currently it’s hard to see the relationship between the points due to some strongoutliers in GDP per capita. We can change the scale of units on the x axis usingthe scale functions. These control the mapping between the data values andvisual values of an aesthetic. We can also modify the transparency of thepoints, using the alpha function, which is especially helpful when you havea large amount of data which is very clustered.

The log10 function applied a transformation to the values of the gdpPercapcolumn before rendering them on the plot, so that each multiple of 10 now onlycorresponds to an increase in 1 on the transformed scale, e.g. a GDP per capitaof 1,000 is now 3 on the x axis, a value of 10,000 corresponds to 4 on the xaxis and so on. This makes it easier to visualize the spread of data on thex-axis.

Tip Reminder: Setting an aesthetic to a value instead of a mapping

Notice that we used geom_point(alpha = 0.5). As the previous tip mentioned, using a setting outside of the aes() function will cause this value to be used for all points, which is what we want in this case. But just like any other aesthetic setting, alpha can also be mapped to a variable in the data. For example, we can give a different transparency to each continent with geom_point(mapping = aes(alpha = continent)).

We can fit a simple relationship to the data by adding another layer,geom_smooth:

We can make the line thicker by setting the size aesthetic in thegeom_smooth layer:

There are two ways an aesthetic can be specified. Here we set the sizeaesthetic by passing it as an argument to geom_smooth. Previously in thelesson we’ve used the aes function to define a mapping between datavariables and their visual representation.

Challenge 4a

Modify the color and size of the points on the point layer in the previousexample.

Hint: do not use the aes function.

Solution to challenge 4a

Here a possible solution:Notice that the color argument is supplied outside of the aes() function.This means that it applies to all data points on the graph and is not related toa specific variable.

Challenge 4b

Modify your solution to Challenge 4a so that thepoints are now a different shape and are colored by continent with newtrendlines. Hint: The color argument can be used inside the aesthetic.

Solution to challenge 4b

Here is a possible solution:Notice that supplying the color argument inside the aes() functions enables you toconnect it to a certain variable. The shape argument, as you can see, modifies alldata points the same way (it is outside the aes() call) while the color argument whichis placed inside the aes() call modifies a point’s color based on its continent value.

Ggplot2 Sheet

Multi-panel figures

Earlier we visualized the change in life expectancy over time across allcountries in one plot. Alternatively, we can split this out over multiple panelsby adding a layer of facet panels.

Tip

We start by making a subset of data including only countries locatedin the Americas. This includes 25 countries, which will begin toclutter the figure. Note that we apply a “theme” definition to rotatethe x-axis labels to maintain readability. Nearly everything inggplot2 is customizable.

The facet_wrap layer took a “formula” as its argument, denoted by the tilde(~). This tells R to draw a panel for each unique value in the country columnof the gapminder dataset.

Modifying text

Ggplot2 Cheat Sheet 2020 Free

To clean this figure up for a publication we need to change some of the textelements. The x-axis is too cluttered, and the y axis should read“Life expectancy”, rather than the column name in the data frame.

We can do this by adding a couple of different layers. The theme layercontrols the axis text, and overall text size. Labels for the axes, plottitle and any legend can be set using the labs function. Legend titlesare set using the same names we used in the aes specification. Thus belowthe color legend title is set using color = 'Continent', while the titleof a fill legend would be set using fill = 'MyTitle'.

Exporting the plot

The ggsave() function allows you to export a plot created with ggplot. You can specify the dimension and resolution of your plot by adjusting the appropriate arguments (width, height and dpi) to create high quality graphics for publication. In order to save the plot from above, we first assign it to a variable lifeExp_plot, then tell ggsave to save that plot in png format to a directory called results. (Make sure you have a results/ folder in your working directory.)

There are two nice things about ggsave. First, it defaults to the last plot, so if you omit the plot argument it will automatically save the last plot you created with ggplot. Secondly, it tries to determine the format you want to save your plot in from the file extension you provide for the filename (for example .png or .pdf). If you need to, you can specify the format explicitly in the device argument.

This is a taste of what you can do with ggplot2. RStudio provides areally useful cheat sheet of the different layers available, and moreextensive documentation is available on the ggplot2 website.Finally, if you have no idea how to change something, a quick Google search willusually send you to a relevant question and answer on Stack Overflow with reusablecode to modify!

Cheat

Challenge 5

Generate boxplots to compare life expectancy between the different continents during the available years.

Advanced:

  • Rename y axis as Life Expectancy.
  • Remove x axis labels.

Ggplot2 Cheat Sheet 2020 Pdf

Solution to Challenge 5

Here a possible solution:xlab() and ylab() set labels for the x and y axes, respectivelyThe axis title, text and ticks are attributes of the theme and must be modified within a theme() call.

Key Points

  • Use ggplot2 to create plots.

  • Think about graphics in layers: aesthetics, geometry, statistics, scale transformation, and grouping.