This is an R Markdown document. Follow the link to learn more about R Markdown and the notebook format used during the workshop.
The cheat sheet is very useful when working with ggplot2: https://www.rstudio.org/links/data_visualization_cheat_sheet
library(dplyr)
library(ggplot2)
library(readr)
We’re using two data sets, one from a package, one built into R.
You only need to do this once: install the remotes package (or you can substitute devtools if you have that), and then use that package to install the palmerpenguins package from GitHub.
install.packages("palmerpenguins")
If you have it installed, load it and look at the penguins data set:
library(palmerpenguins)
penguins
We’re also going to use average yearly temperatures in New Hampshire,
a data set built into R (nhtemp
). But we need to put it in
a data frame first to make it easier to use (it’s in a special time
series object):
nh <- data.frame(temp = c(nhtemp), year = 1912:1971)
nh
Why ggplot? It makes exploring data, especially groups in data, much easier. You can pretty easily make some plots with ggplot that are difficult enough to make with base R graphics that you probably won’t do them routinely when exploring data. This is bad, because we should visualize our data! You don’t want the code to get in the way of that.
When it comes to ggplot, it’s good to first learn the basic syntax, and then go back and learn some more about the theory behind the package – what the logic is and how it works. It can take a few iterations of working with ggplot to get comfortable with it, and to understand how to think in a way that is compatible with how ggplot approaches visualization. But once you get it, it makes data visualization easier and more fun.
The syntax of ggplot2 is a little bit different than other tidyverse packages, in part because it predates them. But it does share a few things with other tidyverse packages, such as:
The package is called ggplot2 (there is no first version), the main function in the package is called ggplot, and “ggplot” generally refers to anything with the package (most people often don’t bother to say the 2 in the package name).
Each plot with ggplot has the same template for the code:
## call to ggplot and the name of the data frame
ggplot(dataframename,
## which variables to use for which plot components
aes(x = column_name, y = column_name)) +
# what type of plot
geom_****()
The first line says what data and variables to use, and the second line says what type of plot to make. We add the components of the plot together, which is a somewhat unique syntax.
For example:
ggplot(penguins, aes(x = bill_length_mm,
y = bill_depth_mm)) +
geom_point()
## Warning: Removed 2 rows containing missing values (`geom_point()`).
The warning message is telling you that two observations (rows) in your data frame are not plotted because there were missing values. You can get this warning from explicit missing values or in cases where you set the limits of the axes in a way that excludes some data points.
The first line alone (without the +
at the end) makes a
plot set up without adding the data:
ggplot(penguins, aes(x = bill_length_mm,
y = bill_depth_mm))
If we change the geom function we use, the plot type changes:
ggplot(penguins, aes(x = bill_length_mm,
y = bill_depth_mm)) +
geom_bin2d()
## Warning: Removed 2 rows containing non-finite values (`stat_bin2d()`).
This is a density plot, where the color of each rectangle indicates how many observations (points on the above plot) fall in that area.
Fill in the ___
to make a line plot using
geom_line()
with the nh
data frame, with
year
as the x variable and temp
as the y:
ggplot(___, aes(x = ___, y = ___)) +
___()
The above plots used two continuous variables. The cheat
sheet has the geoms
organized by how many and what type
of variables you want to plot. (This is very useful!) For example, we
can make a histogram, which is of a single variable:
ggplot(penguins, aes(x = bill_depth_mm)) +
geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 2 rows containing non-finite values (`stat_bin()`).
The warning message is how many bins (bars) there are in the histogram. It defaults to 30, but it wants you to explicitly pick a number instead:
ggplot(penguins, aes(x = bill_depth_mm)) +
geom_histogram(bins = 25)
## Warning: Removed 2 rows containing non-finite values (`stat_bin()`).
We can also have multiple geoms on the same plot:
ggplot(nh, aes(x = year, y = temp)) +
geom_line() +
geom_point()
ggplot(nh, aes(x = year, y = temp)) +
geom_point() +
geom_line() +
geom_smooth()
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
Make a histogram (geom_histogram()
) of the
temp
variable in the nh
dataset. You can code
here:
We can set other aesthetics of the plot (color, fill, linetype, marker, etc.) according to variables in our data.
Note that if you want a line or color for each group, those groups need to be defined by a categorical variable. This is the opposite of how data usually needs to be structured when using base R plotting functions. If the values for the two groups are in separate columns in your dataset, you’ll need to reshape your data to get them in a single column instead – something covered in the tidyr session of these workshops.
Each aesthetic – each thing you define in aes() – needs to be a single column in your data set.
With categorical variables, this helps us see the groups in our data:
ggplot(penguins, aes(x = bill_length_mm,
y = bill_depth_mm,
color = species)) +
geom_point()
## Warning: Removed 2 rows containing missing values (`geom_point()`).
Note that a legend was added automatically.
ggplot(penguins, aes(x = bill_length_mm,
y = bill_depth_mm,
color = species)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
method = lm
tells ggplot how to fit a line to the data;
“lm” means fit a linear model with the lm
function.
se = FALSE
means to not display the standard errors on the
plot.
Note that the smoothing was done by group. Specifying
color
effectively grouped our data, much like what happens
with group_by
in dplyr. How amazing is that?
Repeat the same plot as above, bill_length_mm
vs. bill_depth_mm
, but color
by
body_mass_g
instead of species
. You can code
here:
A convenient way to label axes and legends and set the title is with the labs() function, added as a component of the plot:
ggplot(penguins, aes(x = bill_length_mm,
y = bill_depth_mm,
color = species)) +
geom_point() +
labs(title = "Penguin Bill Dimensions",
y = "Depth (mm)",
x = "Length (mm)",
color = "Body Mass",
subtitle = "Three Species",
caption = "Source: palmerpenguins")
## Warning: Removed 2 rows containing missing values (`geom_point()`).
Plot flipper_length_mm
vs. body_mass_g
and
color by sex
. Label the axes and title your plot. You can
code here:
To change the axes min and max values, like we would with
xlim
or ylim
in base R graphics, we use a
scale function and set the limits
argument:
ggplot(penguins, aes(x = bill_length_mm,
y = bill_depth_mm)) +
geom_point() +
scale_x_continuous(limits = c(30, 50))
## Warning: Removed 54 rows containing missing values (`geom_point()`).
In addition to using color, fill, linetype, etc. to denote groups, we can also make a separate plot for each group, where the plots are aligned and share axes. These are called facets:
ggplot(penguins, aes(flipper_length_mm)) +
geom_histogram() +
facet_grid(sex ~ .)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 2 rows containing non-finite values (`stat_bin()`).
The facet function syntax is using the formula syntax used elsewhere in R, but it can be tough to remember. It’s on the cheat sheet though so you can look it up. There are other options for laying out plots horizontally or in a grid.
Note that the plots share an x-axis, and the y-axis has the same range in each plot.
If you want to put multiple plots in a single image together, but they are not facets of a single plot, see the patchwork package.
Make a histogram (set a value for bins) of body_mass_g
for each species
. You can fill in the blanks here:
ggplot(penguins, aes(___)) +
___(___) +
facet_grid(___ ~ .)
Themes control the look of the plot not related to the data: fonts, backgrounds, grid lines, axis lines, etc.
There are some built-in themes (theme_minimal()
,
theme_bw()
, theme_classic()
, etc.), but you
can also control the styling further with the theme()
function:
ggplot(penguins, aes(body_mass_g)) +
geom_histogram(bins = 30) +
theme_minimal()
## Warning: Removed 2 rows containing non-finite values (`stat_bin()`).
For further control, use theme
instead or in
addition:
ggplot(penguins, aes(body_mass_g)) +
geom_histogram(bins = 30) +
theme_minimal() +
theme(panel.grid.major.x = element_blank(), # get rid of the vertical grid lines
panel.grid.minor.x = element_blank())
## Warning: Removed 2 rows containing non-finite values (`stat_bin()`).
Many theme
elements are controlled by setting options in additional
element
functions:
element_blank()
- draws nothing, and assigns no
spaceelement_text()
- textelement_line()
- lineselement_rect()
- borders and backgroundsThese are options that you will generally Google for how to do: “ggplot remove gridlines”, “ggplot change font size”, etc.
In addition to themes, you can control some aspects of the
data-driven elements of the plot directly, without using a variable to
define them. For example with color or size, if we specify them outside
of a call to aes()
within the geom function:
ggplot(penguins, aes(x = bill_length_mm,
y = bill_depth_mm)) +
geom_point(color = "red", size = 3)
## Warning: Removed 2 rows containing missing values (`geom_point()`).
it colors all of the points the same color.
Change the fill
color for the bars in our histogram
above to be “darkgreen”. The code from above is copied below to get you
started. You have to change this code:
ggplot(penguins, aes(body_mass_g)) +
geom_histogram(bins = 30) +
theme_minimal() +
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank())
We use +
, not %>%
, to join together
components of our ggplot. But we can still pipe the results of other
commands into ggplot (the code above didn’t do it because we were just
plotting the data frame as it is). For example, to plot only the Adelie
penguins:
penguins %>%
filter(species == "Adelie") %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm)) +
geom_point()
## Warning: Removed 1 rows containing missing values (`geom_point()`).
This notebook provided a quick introduction to ggplot. Besides some of the basics, the notebook covered different plot types, aesthetics and grouping, labels/titles, axis limits, facets, styling, and pipes.
As previously mentioned, now that you learned the basics, it’d be good to go back and learn some more about the theory behind ggplot. You can also play around to get a feel for it. Have fun!
The first chapter of R for Data Science https://r4ds.had.co.nz/ covers ggplot well.
For more on ggplot2, see our guide with free (for Northwestern folks) resources.
We’re happy to help you use ggplot on your own data. Request a free consultation: https://services.northwestern.edu/TDClient/30/Portal/Requests/ServiceDet?ID=93
ggplot(nh, aes(x = year, y = temp)) +
geom_line()
ggplot(nh) +
geom_histogram(aes(temp), bins = 6)
ggplot(penguins, aes(x = bill_length_mm,
y = bill_depth_mm,
color = body_mass_g)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE)
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: The following aesthetics were dropped during statistical transformation: colour
## ℹ This can happen when ggplot fails to infer the correct grouping structure in
## the data.
## ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
## variable into a factor?
## Warning: Removed 2 rows containing missing values (`geom_point()`).
Weird? Check out what type of variables they are:
class(penguins$species)
## [1] "factor"
class(penguins$body_mass_g)
## [1] "integer"
ggplot(penguins, aes(x = flipper_length_mm,
y = body_mass_g,
color = sex)) +
geom_point() +
labs(title = "Flipper Length Against Body Mass",
y = "Body mass (g)",
x = "Fliper length (mm)",
color = "Sex")
## Warning: Removed 2 rows containing missing values (`geom_point()`).
ggplot(penguins, aes(x = body_mass_g)) +
geom_histogram(bins = 8) +
facet_grid(species ~ .)
ggplot(penguins, aes(body_mass_g)) +
geom_histogram(bins = 30, fill = "darkgreen") +
theme_minimal() +
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank())