# Chapter 13 Plotting

“Make it informative, then make it pretty”

There are two major sets of tools for creating plots in R:

1. base, which come with all R installations.
1. ggplot2, a stand-alone package.

Note that other plotting facilities do exist (notably lattice), but base and ggplot2 are by far the most popular.

## 13.1 The Dataset

For the following examples, we will be using the gapminder dataset we’ve used previously. Gapminder is a country-year dataset with information on life expectancy, among other things.

gap <- read.csv("data/gapminder-FiveYearData.csv", stringsAsFactors = F)

## 13.2 R Base Graphics

The basic call takes the following form:

plot(x=, y=)
plot(x = gap$gdpPercap, y = gap$lifeExp)

### 13.2.1 Scatter and Line Plots

The “type” argument accepts the following character indicators.

• “p” – point/scatter plots (default plotting behavior)
plot(x = gap$gdpPercap, y = gap$lifeExp, type="p")
• “l” – line graphs
# Note that "line" does not create a smoothing line, just connected points
plot(x = gap$gdpPercap, y = gap$lifeExp, type="l") 
• “b” – both line and point plots
plot(x = gap$gdpPercap, y = gap$lifeExp, type="b") 

### 13.2.2 Histograms and Density Plots

Histograms display the frequency of different values of a variable.

hist(x=gap$lifeExp) Histograms require a breaks argument, which determine the number of bins in the plot. Let’s play around with different breaks values. hist(x=gap$lifeExp, breaks=5)
hist(x=gap$lifeExp, breaks=10) Density plots are similar, they visualize the distribution of data over a continuous interval. # Create a density object (NOTE: be sure to remove missing values) age.density <- density(x=gap$lifeExp, na.rm=T)

# Plot the density object
plot(x=age.density)

Density passes a bw parameter, which determins the plot’s “bandwidth”.

# Plot the density object, bandwidth of 0.5
plot(x=density(x=gap$lifeExp, bw=.5)) # Plot the density object, bandwidth of 2 plot(x=density(x=gap$lifeExp, bw=2))
# Plot the density object, bandwidth of 6
plot(x = gap$gdpPercap, y = gap$lifeExp, type="p",pch="$", cex=2)  • Line Styles and Widths # Line plot with solid line plot(x = gap$gdpPercap, y = gap$lifeExp, type="l", lty=1) # Line plot with medium dashed line plot(x = gap$gdpPercap, y = gap$lifeExp, type="l", lty=2) # Line plot with short dashed line plot(x = gap$gdpPercap, y = gap$lifeExp, type="l", lty=3) # Change line width to 2 plot(x = gap$gdpPercap, y = gap$lifeExp, type="l", lty=3, lwd=2) # Change line width to 5 plot(x = gap$gdpPercap, y = gap$lifeExp, type="l", lwd=5) # Change line width to 10 and use dash-dot plot(x = gap$gdpPercap, y = gap$lifeExp, type="l", lty=4, lwd=10) ### 13.2.6 Annotations, Reference Lines, and Legends • Text We can add text to an arbitrary point on the graph like this: # plot the line first plot(x = gap$gdpPercap, y = gap$lifeExp, type="p") # now add the label text(x=40000, y=50, labels="Evens Out", cex = .75) We can also add labels for every point by passing in a vector of text: # first randomly select rows for a smaller gapaset library(dplyr) small <- gap %>% sample_n(100) # plot the line first plot(x = small$gdpPercap, y = small$lifeExp, type="p") # now add the label text(x = small$gdpPercap, y = small$lifeExp, labels = small$country)
• Reference Lines
# plot the line
plot(x = gap$gdpPercap, y = gap$lifeExp, type="p")
# now the guides
abline(v=40000, h=75, lty=2)

## 13.3 ggplot2

Setup:

library(ggplot2)
gap <- read.csv("data/gapminder-FiveYearData.csv", stringsAsFactors = F)

#### Why ggplot?

• More elegant & compact code than R base graphics
• More aesthetically pleasing defaults than lattice
• Very powerful for exploratory data analysis
• Follows a grammar, just like any language.
• It defines basic components that make up a sentence. In this case, the grammar defines components in a plot.
• Grammar of graphics originally coined by Lee Wilkinson

### 13.3.1 Grammar

The general call for ggplot2 looks like this:

ggplot(data=, aes(x=, y=), color=, size=,) + geom_xxxx()+geom_yyyy()

The grammar involves some basic components:

1. Data: a data.frame
2. Aesthetics: How your data are represented visually, aka its “mapping”. Which variables are shown on x, y axes, as well as color, size, shape, etc.
3. Geometry: The geometric objects in a plot – points, lines, polygons, etc.

The key to understanding ggplot2 is thinking about a figure in layers: just like you might do in an image editing program like Photoshop, Illustrator, or Inkscape.

Let’s look at an example:

ggplot(data = gap, aes(x = gdpPercap, y = lifeExp)) +
geom_point()

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

We’ve passed in two arguments to ggplot. First, we tell ggplot what data we want to show on our figure, in this example the gapminder data we read in earlier.

For the second argument we passed in the aes function, which tells ggplot how variables in the data map to aesthetic properties of the figure, in this case the x and y locations. Here we told ggplot we want to plot the lifeExp column of the gapminder data frame on the x-axis, and the gdpPercap column on the y-axis.

Notice that we didn’t need to explicitly pass aes these columns (e.g. x = gapminder[, "lifeExp""]), this is because ggplot 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:

ggplot(data = gap, aes(x = gdpPercap, y = lifeExp))

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

ggplot(data = gap, aes(x = gdpPercap, y = lifeExp)) +
geom_point()

# same as
# my_plot <- ggplot(data = gap, aes(x = gdpPercap, y = lifeExp))
# my_plot + geom_point()

#### Challenge 1.

Modify the example so that the figure visualises how life expectancy has changed over time:

Hint: the gapminder dataset has a column called year, which should appear on the x-axis.

### 13.3.2 Anatomy of aes

In the previous examples and challenge we’ve used the aes function to tell the scatterplot geom about the x and y locations of each point. Another aesthetic property we can modify is the point color.

ggplot(data = gap, aes(x = gdpPercap, y = lifeExp, color=continent)) +
geom_point()

Normally, specifying options like color="red" or size=10 for a given layer results in its contents being red and quite large. Inside the aes() function, however, these arguments are given entire variables whose values will then be displayed using different realizations of that aesthetic.

Color isn’t the only aesthetic argument we can set to display variation in the data. We can also vary by shape, size, etc.

ggplot(data=, aes(x=, y=, by =, color=, linetype=, shape=, size=))

### 13.3.3 Layers

In the previous challenge, you plotted lifExp over time. Using a scatterplot probably isn’t the best for visualising change over time. Instead, let’s tell ggplot to visualise the data as a line plot:

ggplot(data = gap, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line()

Instead of adding a geom_point layer, we’ve added a geom_line layer. We’ve also added the by aesthetic, which tells ggplot to draw a line for each country.

But what if we want to visualise both lines and points on the plot? We can simply add another layer to the plot:

ggplot(data = gap, aes(x=year, y=lifeExp, by=country, color=continent)) +
geom_line() +
geom_point()

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

ggplot(data = gap, aes(x=year, y=lifeExp, by=country)) +
geom_line(aes(color=continent)) +
geom_point()

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

#### Challenge 2.

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

### 13.3.4 Labels

Labels are considered to be their own layers in ggplot.

# add x and y axis labels
ggplot(data = gap, aes(x = gdpPercap, y = lifeExp, color=continent)) +
geom_point() +
xlab("GDP per capita") +
ylab("Life Expectancy") +
ggtitle("My fancy graph")

So are scales:

# limit x-axis from 1,000 to 20,000
ggplot(data = gap, aes(x = gdpPercap, y = lifeExp, color=continent)) +
geom_point() +
xlab("GDP per capita") +
ylab("Life Expectancy") +
ggtitle("My fancy graph") +
xlim(1000, 20000)
#> Warning: Removed 515 rows containing missing values (geom_point).

### 13.3.5 Transformations and Stats

ggplot also makes it easy to overlay statistical models over the data. To demonstrate we’ll go back to an earlier example:

ggplot(data = gap, aes(x = gdpPercap, y = lifeExp, color=continent)) +
geom_point()

We can change the scale of units on the x-axis using the scale functions. These control the mapping between the data values and visual values of an aesthetic.

ggplot(data = gap, aes(x = gdpPercap, y = lifeExp, color=continent)) +
geom_point() +
scale_x_log10()

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

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

ggplot(data = gap, aes(x = gdpPercap, y = lifeExp, color=continent)) +
geom_point() +
scale_x_log10() +
geom_smooth(method="lm")

Note that we have 5 lines, one for each region, because of the color option is the global aes function. But if we move it, we get different results:

ggplot(data = gap, aes(x = gdpPercap, y = lifeExp)) +
geom_point(aes(color=continent)) +
scale_x_log10() +
geom_smooth(method="lm")

So, there are two ways an aesthetic can be specified. Here, we set the color aesthetic by passing it as an argument to geom_point. Previously in the lesson, we used the aes function to define a mapping between data variables and their visual representation.

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

ggplot(data = gap, aes(x = gdpPercap, y = lifeExp)) +
geom_point(aes(color=continent)) +
scale_x_log10() +
geom_smooth(method="lm", size = 1.5)

#### Challenge 3.

Modify the color and size of the points on the point layer in the previous example so that they are fixed (i.e. not reflective of continent).

Hint: do not use the aes function.

### 13.3.6 Facets

Earlier, we visualised the change in life expectancy over time across all countries in one plot. Alternatively, we can split this out over multiple panels by adding a layer of facet panels:

ggplot(data = gap, aes(x = year, y = lifeExp)) +
geom_point() +
facet_wrap( ~ continent)

### 13.3.7 Putting Everything Together

Here are some other common geom layers:

bar plots

# count of lifeExp bins
ggplot(data = gap, aes(x = lifeExp)) +
geom_bar(stat="bin")
#> stat_bin() using bins = 30. Pick better value with binwidth.

# with color representing regions
ggplot(data = gap, aes(x = lifeExp, fill = continent)) +
geom_bar(stat="bin")
#> stat_bin() using bins = 30. Pick better value with binwidth.

box plots

ggplot(data = gap, aes(x = continent, y = lifeExp)) +
geom_boxplot()

This is just a taste of what you can do with ggplot2.

RStudio provides a really useful cheat sheet of the different layers available, and more extensive documentation is available on the ggplot2 website.

Finally, if you have no idea how to change something, a quick Google search will usually send you to a relevant question and answer on Stack Overflow with reusable code to modify!

#### Challenge 4.

Create a density plot of GDP per capita, filled by continent.

Advanced: - Transform the x-axis to better visualise the data spread. - Add a facet layer to panel the density plots by year.

## 13.4 Saving plots

There are two basic image types:

1. Raster/Bitmap (.png, .jpeg)

Every pixel of a plot contains its own separate coding; not so great if you want to resize the image.

jpeg(filename="example.png", width=, height=)
plot(x,y)
dev.off()
1. Vector (.pdf, .ps)

Every element of a plot is encoded with a function that gives its coding conditional on several factors; this is great for resizing.

pdf(filename="example.pdf", width=, height=)
plot(x,y)
dev.off()

Exporting with ggplot

# Assume we saved our plot is an object called example.plot
ggsave(filename="example.pdf", plot=example.plot, scale=, width=, height=)