Last active
March 18, 2022 15:54
-
-
Save swo/25038ee4be745746a66c339e388e85d8 to your computer and use it in GitHub Desktop.
Making a second axis on ggplot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
# "faithful" is a dataset about a geyser, showing size of eruption vs. waiting | |
# time before the eruption | |
data <- as_tibble(datasets::faithful) %>% | |
mutate(index = 1:n()) %>% | |
head(10) | |
data | |
# values for "eruptions" range from 2 to 5; for "waiting", from 50 to 90 | |
data %>% | |
pivot_longer(!index) %>% | |
ggplot(aes(index, value)) + | |
facet_grid(rows = vars(name), scales = "free_y") + | |
geom_line() | |
# using ggplot ----------------------------------------------------------------- | |
# get a scaling factor that is median of eruptions:waiting ratio | |
scale_factor <- with(data, { median(eruptions / waiting) }) | |
data %>% | |
# scale the value to be shown on the plot (which always goes with main y-axis) | |
mutate(scaled_waiting = waiting * scale_factor) %>% | |
select(index, eruptions, waiting = scaled_waiting) %>% | |
pivot_longer(!index) %>% | |
ggplot(aes(index, value)) + | |
geom_line(aes(color = name)) + | |
# the secondary axis is the main axis but *divided* by the scaling factor | |
scale_y_continuous( | |
"eruptions", | |
sec.axis = sec_axis( | |
trans = ~ . / scale_factor, | |
name = "waiting" | |
) | |
) | |
# using cowplot ---------------------------------------------------------------- | |
library(cowplot) | |
p1 <- data %>% | |
ggplot(aes(index, eruptions)) + | |
geom_line(color = "red") | |
p2 <- data %>% | |
ggplot(aes(index, waiting)) + | |
geom_line(color = "blue") + | |
scale_y_continuous(position = "right") | |
aligned_plots <- align_plots(p1, p2, align = "hv") | |
ggdraw(aligned_plots[[1]]) + | |
draw_plot(aligned_plots[[2]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment