Cheat Sheet RStudio® is a trademark of RStudio, Inc. CC BY RStudio. info@rstudio.com. 844-448-1212. rstudio.com Learn more at docs.ggplot2.org. ggplot2 0.9.3.1. Updated: 3/15 Geoms- Use a geom to represent data points, use the geom’s aesthetic properties to represent variables. Each function returns a.
Learning Objectives
Plotting with ggplot2. Ggplot2 is a plotting package that makes it simple to create complex plots from data in a data frame. It provides a more programmatic interface for specifying what variables to plot, how they are displayed, and general visual properties. The ggplot2 Cheat Sheet by RStudio. In Data Visualization with ggplot2 / Starting with ggplot2 Fant du det du lette etter? Did you find this helpful? Here are several options: A very polished ggplot2 cheat sheet from RStudio (Dec 2015). This version is updated for ggplot2 2.0. Another ggplot cheat sheet. A ggplot2 tutorial (October 2014). A 14-page quick reference/tutorial for ggplot2 published in September 2011: ggplot2 tutorial by Ramon Saccilotto. A detailed tutorial on a wide range of plot types and customization options, published. Data Visualization with ggplot2:: CHEAT SHEET ggplot2 is based on the grammar of graphics, the idea that you can build every graph from the same components: a data set, a coordinate system, and geoms—visual marks that represent data points. Basics GRAPHICAL PRIMITIVES a + geomblank (Useful for expanding limits).
- Produce scatter plots, boxplots, and time series plots using ggplot.
- Set universal plot settings.
- Understand and apply faceting in ggplot.
- 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.
If not still in the workspace, load the data we saved in the previous lesson.
Plotting with ggplot2
ggplot2
is a plotting package that makes it simple to create complex plots from data in a data frame. It provides a more programmatic interface for specifying what variables to plot, how they are displayed, and general visual properties. Therefore, we only need minimal changes if the underlying data change
or if we decide to change from a bar plot to a scatterplot. This helps in creating publication quality plots with minimal amounts of adjustments and tweaking.
ggplot likes data in the ‘long’ format: i.e., a column for every dimension, and a row for every observation. Well structured data will save you lots of time when making figures with ggplot.
ggplot graphics are built step by step by adding new elements. Adding layers in this fashion allows for extensive flexibility and customization of plots.
To build a ggplot, we need to:
- use the
ggplot()
function and bind the plot to a specific data frame using thedata
argument
- define aesthetics (
aes
), by selecting the variables to be plotted and the
variables to define the presentation such as plotting size, shape color, etc.
- add
geoms
– graphical representation of the data in the plot (points, lines, bars).ggplot2
offers many different geoms; we will use some common ones today, including:geom_point()
for scatter plots, dot plots, etc.geom_boxplot()
for, well, boxplots!geom_line()
for trend lines, time-series, etc.
To add a geom to the plot use +
operator. Because we have two continuous variables,
let’s use geom_point()
first:
The +
in the ggplot2
package is particularly useful because it allows you to modify existing ggplot
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:
Notes:
- 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 inaes()
. - 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 specimens_complete
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:
Rstudio Ggplot Cheat Sheet Free
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 scientificName
with the genera 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
length
. Overlay the boxplot layer on a jitter layer to show actual measurements.Add color to the datapoints on your boxplot according to the month from which the specimen was taken (
month
).
Hint: Check the class for month
. Consider changing the class of month
from integer to factor. Why does this change how R makes the graph?
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 = scientificName
:
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:
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
, scientificName
, 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:
Challenge
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.
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)/).
Arranging and exporting plots
Faceting is a great tool for splitting one plot into multiple plots, but sometimes you may want to produce a single figure that contains multiple plots using different variables or even different data frames. The gridExtra
package allows us to combine separate ggplots into a single figure using grid.arrange()
:
In addition to the ncol
and nrow
arguments, used to make simple arrangements, there are tools for constucting more complex layouts.
After creating your plot, you can save it to a file in your favorite format. The Export tab in the Plot pane in RStudio will save your plots at low resolution, which will not be accepted by many journals and will not scale well for posters.
Instead, use the ggsave()
function, which allows you easily change the dimension and resolution of your plot by adjusting the appropriate arguments (width
, height
and dpi
):
Note: The parameters width
and height
also determine the font size in the saved plot.
Page build on: 2017-10-25 10:37:03
Data Carpentry, 2017. License. Contributing.
Questions? Feedback? Please file an issue on GitHub.
On Twitter: @datacarpentry
I reproduce some of the plots from Rstudio’s ggplot2 cheat sheet using Base R graphics. I didn’t try to pretty up these plots, but you should.
I use this dataset
The main functions that I generally use for plotting are
- Plotting Functions
plot
: Makes scatterplots, line plots, among other plots.lines
: Adds lines to an already-made plot.par
: Change plotting options.hist
: Makes a histogram.boxplot
: Makes a boxplot.text
: Adds text to an already-made plot.legend
: Adds a legend to an already-made plot.mosaicplot
: Makes a mosaic plot.barplot
: Makes a bar plot.jitter
: Adds a small value to data (so points don’t overlap on a plot).rug
: Adds a rugplot to an already-made plot.polygon
: Adds a shape to an already-made plot.points
: Adds a scatterplot to an already-made plot.mtext
: Adds text on the edges of an already-made plot.
- Sometimes needed to transform data (or make new data) to make appropriate plots:
table
: Builds frequency and two-way tables.density
: Calculates the density.loess
: Calculates a smooth line.predict
: Predicts new values based on a model.
All of the plotting functions have arguments that control the way the plot looks. You should read about these arguments. In particular, read carefully the help page ?plot.default
. Useful ones are:
main
: This controls the title.xlab
,ylab
: These control the x and y axis labels.col
: This will control the color of the lines/points/areas.cex
: This will control the size of points.pch
: The type of point (circle, dot, triangle, etc…)lwd
: Line width.lty
: Line type (solid, dashed, dotted, etc…).
Discrete
Barplot
Different type of bar plot
Continuous X, Continuous Y
Scatterplot
Jitter points to account for overlaying points.
Add a rug plot
Add a Loess Smoother
Loess smoother with upper and lower 95% confidence bands
Loess smoother with upper and lower 95% confidence bands and that fancy shading from ggplot2
.
Add text to a plot
Discrete X, Discrete Y
Rstudio Ggplot Cheat Sheet 2017
Mosaic Plot
Color code a scatterplot by a categorical variable and add a legend.
par
sets the graphics options, where mfrow
is the parameter controling the facets.
Ggplot Cheat Sheet Pdf
The first line sets the new options and saves the old options in the list old_options
. The last line reinstates the old options.
R-studio Cheats
This R Markdown site was created with workflowr