Learning Objectives
- Create simple scatterplots, histograms, and boxplots in R.
- Compare the plotting features of base R and the ggplot2 package.
- Customize the aesthetics of an existing plot.
- Create plots from data in a data frame.
- Export plots from RStudio to standard graphical file formats.
The mathematician Richard Hamming once said, “The purpose of computing is insight, not numbers”, and the best way to develop insight is often to visualize data. Visualization deserves an entire lecture (or course) of its own, but we can explore a few features of R’s plotting packages.
When we are working with large sets of numbers it can be useful to display that information graphically. R has a number of built-in tools for basic graph types such as hisotgrams, scatter plots, bar charts, boxplots and much more. We’ll test a few of these out here on the Weight
vector from our metadata.
metadata_weight <- metadata$Weight
Let’s start with a scatterplot. A scatter plot provides a graphical view of the relationship between two sets of numbers. We don’t have a variable in our metadata that is a continous variable, so there is nothing to plot it against but we can plot the values against their index values just to demonstrate the function.
plot(metadata_weight)
Each point represents a clone and the value on the x-axis is the clone index in the file, where the values on the y-axis correspond to the weight for the clone. For any plot you can customize many features of your graphs (fonts, colors, axes, titles) through graphic options For example, we can change the shape of the data point using pch
.
plot(metadata_weight, pch=8)
We can add a title to the plot by assigning a string to main
:
plot(metadata_weight, pch=8, main="Scatter plot of weights")
Another way to visualize the distribution of genome sizes is to use a histogram, we can do this buy using the hist
function:
hist(metadata_weight)
Using additional information from our metadata, we can use plots to compare values between the different citrate mutant status using a boxplot. A boxplot provides a graphical view of the median, quartiles, maximum, and minimum of a data set.
# Boxplot
boxplot(metadata_weight ~ Genotype, metadata)
Similar to the scatterplots above, we can pass in arguments to add in extras like plot title, axis labels and colors.
boxplot(metadata_weight ~ Genotype, metadata, col=c("pink","purple", "darkgrey", "blue"),
main="Average weight differences between genotypes", ylab="Weight")
ggplot2
)More recently, R users have moved away from base graphic options and towards a plotting package called ggplot2
that adds a lot of functionality to the basic plots seen above. The syntax takes some getting used to but it’s extremely powerful and flexible. We can start by re-creating some of the above plots but using ggplot functions to get a feel for the syntax.
ggplot2
is best used on data in the data.frame
form, so we will will work with metadata
for the following figures. Let’s start by loading the ggplot2
library.
library(ggplot2)
The ggplot()
function is used to initialize the basic graph structure, then we add to it. The basic idea is that you specify different parts of the plot, and add them together using the +
operator.
We will start with a blank plot and will add layers as we go along.
ggplot(metadata)
Geometric objects are the actual marks we put on a plot. Examples include:
geom_point
, for scatter plots, dot plots, etc)geom_line
, for time series, trend lines, etc)geom_boxplot
, for, well, boxplots!)A plot must have at least one geom; there is no upper limit. You can add a geom to a plot using the + operator
ggplot(metadata) +
geom_point() # note what happens here
Each type of geom usually has a required set of aesthetics to be set, and usually accepts only a subset of all aesthetics –refer to the geom help pages to see what mappings each geom accepts. Aesthetic mappings are set with the aes() function. Examples include:
To start, we will add position for the x- and y-axis since geom_point
requires mappings for x and y, all others are optional.
ggplot(metadata) +
geom_point(aes(x = Genotype, y= Weight))
The labels on the x-axis are quite hard to read. To do this we need to add an additional theme layer. The ggplot2 theme
system handles non-data plot elements such as:
There are built-in themes we can use, or we can adjust specific elements. For our figure we will change the x-axis labels to be plotted on a 45 degree angle with a small horizontal shift to avoid overlap. We will also add some additional aesthetics by mapping them to other variables in our dataframe. For example, the color of the points will reflect the number of generations and the shape will reflect citrate mutant status. The size of the points can be adjusted within the geom_point
but does not need to be included in aes()
since the value is not mapping to a variable.
ggplot(metadata) +
geom_point(aes(x = Genotype, y= Weight, color = Source, shape = Sex), size = rel(3.0)) +
theme(axis.text.x = element_text(angle=45, hjust=1))
To plot a histogram we require another geometric object geom_bar
, which requires a statistical transformation. Some plot types (such as scatterplots) do not require transformations, each point is plotted at x and y coordinates equal to the original value. Other plots, such as boxplots, histograms, prediction lines etc. need to be transformed, and usually has a default statistic that can be changed via the stat_bin
argument.
ggplot(metadata) +
geom_bar(aes(x = Weight))
Try plotting with the default value and compare it to the plot using the binwidth values. How do they differ?
ggplot(metadata) +
geom_bar(aes(x = Weight), stat = "bin", binwidth=0.05)
Now that we have all the required information on let’s try plotting a boxplot similar to what we had done using the base plot functions at the start of this lesson. We can add some additional layers to include a plot title and change the axis labels. Explore the code below and all the different layers that we have added to understand what each layer contributes to the final graphic.
ggplot(metadata) +
geom_boxplot(aes(x = Genotype, y = Weight)) +
ggtitle('Distribution of weight by genotype') +
xlab('Genotype') +
ylab('Weight') +
theme(panel.grid.major = element_line(size = .5, color = "grey"),
axis.text.x = element_text(angle=45, hjust=1),
axis.title = element_text(size = rel(1.5)),
axis.text = element_text(size = rel(1.25)))
Notes:
+
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.ggplot2
themesIn 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.
Take a look at the ggplot2
cheat sheet, for ideas on how you can improve plots.
There are two ways in which figures and plots can be output to a file (rather than simply displaying on screen). The first (and easiest) is to export directly from the RStudio ‘Plots’ panel, by clicking on Export
when the image is plotted. This will give you the option of png
or pdf
and selecting the directory to which you wish to save it to.
The second option is to use R functions in the console, allowing you the flexibility to specify parameters to dictate the size and resolution of the output image. Some of the more popular formats include pdf()
, png()
, which are functions that initialize a plot that will be written directly to a file in the pdf
or png
format, respectively. Within the function you will need to specify a name for your image in quotes and the width and height. Specifying the width and height is optional, but can be very useful if you are using the figure in a paper or presentation and need it to have a particular resolution. Note that the default units for image dimensions are either pixels (for png) or inches (for pdf). To save a plot to a file you need to:
pdf("filename")
dev.off()
.# Let's make a new directory where figures can be stored:
dir.create("figures")
pdf("figures/boxplot.pdf")
ggplot(metadata) +
geom_boxplot(aes(x = Genotype, y = Weight)) +
ggtitle('Distribution of weight by genotype') +
xlab('Genotype') +
ylab('Weight') +
theme(panel.grid.major = element_line(size = .5, color = "grey"),
axis.text.x = element_text(angle=45, hjust=1),
axis.title = element_text(size = rel(1.5)),
axis.text = element_text(size = rel(1.25)))
dev.off()
We have only scratched the surface here. To learn more, see the ggplot2 reference site, and Winston Chang’s excellent Cookbook for R site. Though slightly out of date, ggplot2: Elegant Graphics for Data Anaysis is still the definative book on this subject. Much of the material here was adpapted from Introduction to R graphics with ggplot2 Tutorial at IQSS.
Data Carpentry,
2017. License. Contributing.
Questions? Feedback?
Please file
an issue on GitHub.
On
Twitter: @datacarpentry