12  ggplot2

Author

Jarad Niemi

R Code Button

This chapter will provide a number of examples of ggplot2 graphics. ggplot2 graphics are built on the Grammar of Graphics and provide a consistent interface across different types of plots.

library("tidyverse")
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4.9000     ✔ readr     2.1.5     
✔ forcats   1.0.0          ✔ stringr   1.5.1     
✔ ggplot2   3.5.1          ✔ tibble    3.2.1     
✔ lubridate 1.9.3          ✔ tidyr     1.3.1     
✔ purrr     1.0.2          
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

12.1 Histograms

# Histogram
d <- data.frame(area = islands)
ggplot(data = d, 
       aes(x = area)) + 
  geom_histogram()
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

12.2 Boxplots

# Single boxplot
ggplot(data = d, 
       aes(x = area)) + 
  geom_boxplot()

# Multiple boxplots
ggplot(data = InsectSprays, 
       aes(
         x = spray, 
         y = count)) + 
  geom_boxplot()

12.3 Scatterplot

# Scatterplot
ggplot(data = cars, 
       aes(x = speed, 
           y = dist)) + 
  geom_point()

12.4 Line plot

# Line plot
ggplot(data = economics,
       aes(
         x = date,
         y = unemploy
       )) +
  geom_line()

12.5 Function

# Plot a function
ggplot(data.frame(x = seq(0, 6)),
       aes(x = x)) + 
  stat_function(fun = dnorm,
                args = list(
                  mean = 3, 
                  sd   = 1
                ))

12.6 Heatmap

# Heatmap
# Tidy the data
d <- reshape2::melt(volcano) # similar to tidyr::pivot_longer

ggplot(data = d, 
       aes(
         x    = Var1, 
         y    = Var2, 
         fill = value)) + 
  geom_raster() 

12.7 Summary

As a general rule, working with ggplot2 graphics will require a bit more data wrangling to get it into the appropriate tidy (long) format. Once the data is in the correct format, construction of the plot uses a similar syntax.