R Bootcamp - Day 5
more ggplot2
Class 4 & 5 outline
- Introduce ggplot2 & today’s data sets (Exercise 1)
- Understand the basics of ggplot2 (Exercise 2, 3)
- Geom functions (Exercise 4-8)
- Geom_point properties (Exercise 9)
- Position adjustments (Exercise 10)
- Coordinate and Scale Functions (Exercise 11)
- Zooming into a plot (Exercise 12)
- Faceting (Exercise 13)
- Themes (Exercise 14)
- Labels & Legends (Exercise 15)
- Adding lines to plots (Exercise 16)
- Making multi-panel figures (Exercise 17)
- Saving a plot (Exercise 18)
shape, size, fill, color, and transparency - Exercise 9
Get a diamonds subset.
Note that aesthetics can also be defined within a geom.
This is useful if you use two different geoms that share an aesthetic.
Position adjustments - Exercise 10
A stacked bar chart.
Dodged bars are easier to read (proportions are clearer)
Coordinate and Scale Functions - Exercise 11
Logarithmic axes - 1
Note the difference between axis labels in these two examples.
Logarithmic axes - 2
Flipping coordinate system (swapping x
and y
)
Now flip the axis.
Brief aside: ggplot can handle on-the-fly data transformations.
Here we log-transform carat and convert USD to CAD.
Zooming into a plot - Exercise 12
We might want to change the limits of x or y axes to zoom in.
Faceting to plot subsets of data into separate panels - Exercise 13
A density plot we’ve seen before.
Which variables can we use to subdivide the data?
Faceted by cut
Let’s also use facet_grid()
to facet by two variables.
Faceted by clarity
and cut
.
Scatter plot with facets.
Themes - Exercise 14
Scatter plot with default theme.
Change the theme with theme_bw()
.
My go-to is cowplot::theme_cowplot()
.
It implements much of the advice in the “Dataviz” book, i.e.. YOUR LABELS ARE TOO SMALL.
We’re not going to cover it, but you can also customize pre-existing themes.
Labels & Legends - Exercise 15
Use labs()
to add / change plot labels.
Additional points
How to add a line to a plot? (Exercise 16)
Also try:
How to combine multiple plots into a figure? (Exercise 17)
We have 4 legends - can they be condensed?
Yes, but it is not exactly straightforward.
need to scroll below
Saving plots (Exercise 18)
Saves last plot as 5’ x 5’ file named “plot_final.png” in working directory.
Matches file type to file extension.