At the end of this exercise, you will be able to:
1. Build stacked bar plots of categorical variables.
2. Build side-by-side barplots using position= "dodge".
library(tidyverse)
library(janitor)
library(palmerpenguins)
options(scipen=999) #cancels the use of scientific notation for the session
Database of vertebrate home range sizes.
Reference: Tamburello N, Cote IM, Dulvy NK (2015) Energy and the scaling
of animal space use. The American Naturalist 186(2):196-211. http://dx.doi.org/10.1086/682070.
Data: http://datadryad.org/resource/doi:10.5061/dryad.q5j65/1
homerange <- read_csv("data/Tamburelloetal_HomeRangeDatabase.csv", na = c("", "NA", "\\")) %>% clean_names()
There are many options to create nice plots in ggplot.
One useful trick is to store the plot as a new object and then
experiment with geom’s and aesthetics. Let’s setup a plot that compares
log10_mass and log10_hra. Notice that we are
not specifying a geom.
Play with point size by adjusting the size argument.
We can color the points by a categorical variable.
We can also map shapes to another categorical variable.
What about just filling in with a color preference or size?
# Plot all available point shapes
df <- data.frame(x = 1:25, y = rep(1, 25), shape = 0:24)
ggplot(df, aes(x, y)) +
geom_point(aes(shape = factor(shape)), size = 5, fill = "lightblue") +
scale_shape_manual(values = 0:24) +
theme_void() +
theme(legend.position = "none") +
geom_text(aes(label = shape), vjust = -1, size = 5)
At this point you should be comfortable building bar plots that show
counts of observations using geom_bar(). Last time we
explored the fill option as a way to bring color to the
plot; i.e. we filled by the same variable that we were plotting. What
happens when we fill by a different categorical variable?
Let’s start by counting how many observations we have in each taxonomic group.
Now let’s make a bar plot of these data.
By specifying fill=trophic.guild we build a stacked bar
plot that shows the proportion of a given taxonomic group that is an
herbivore or carnivore.
We can also have counts of each trophic guild within taxonomic group
shown side-by-side by specifying position="dodge".
Here is the same plot oriented vertically.
We can also scale all bars to a percentage.
For this practice, let’s use the palmerpenguins data.
Make a bar plot that shows counts of individuals by island. Fill
by species, and try both a stacked bar plot and
position="dodge".
Make another bar plot that shows the number of individuals by sex on each island?
groupIn addition to fill, group is an aesthetic
that accomplishes the same function but does not add color. It groups
data for plotting.
Here is a box plot that shows log10.mass by taxonomic
class.
I use group to make individual box plots for each
taxon.
I can also use fill to associate the different taxa with
a color coded key.
Please review the learning goals and be sure to use the code here as a reference when completing the homework.
–>Home