Skip to content

Instantly share code, notes, and snippets.

@adamhsparks
Last active January 21, 2022 02:18
Show Gist options
  • Save adamhsparks/ecb0a06863ac746a028a5c755fe848e4 to your computer and use it in GitHub Desktop.
Save adamhsparks/ecb0a06863ac746a028a5c755fe848e4 to your computer and use it in GitHub Desktop.
Another example of dual axis in ggplot2
# Entering data
week <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
YLI <- c(3, 4, 5, 2, 6, 5, 4, 3, 5, 6, 2, 4)
YLS <- c(10, 11, 11, 12, 10, 11, 11, 10, 12, 13, 10, 11)
rainfall <- c(1, 10, 8, 6, 65, 30, 2, 10, 8, 6, 65, 30)
# Creating Data Frame
perf <- data.frame(week, YLI, YLS, rainfall)
# Plotting Charts and adding a secondary axis
library(ggplot2)
# max rainfall set from max clermont rainfall in Apr 2019
ylim.prim <- c(0, max(rainfall))
ylim.sec <- c(0, 15)
b <- diff(ylim.prim) / diff(ylim.sec)
a <- b * (ylim.prim[1] - ylim.sec[1])
ggplot(perf, aes(x = week, y = rainfall)) +
geom_col() +
geom_line(aes(y = a + YLI * b,
colour = "YLI"),
size = 1.25) +
geom_line(aes(y = a + YLS * b,
colour = "YLS"),
size = 1.25) +
scale_y_continuous("Precipitation (mm)",
sec.axis = sec_axis( ~ (. - a) / b,
name = "Leaf Position")) +
labs(
title = "Sigatoka") +
scale_colour_manual("Leaf Position", values = c("red", "blue")) +
xlab("Week") +
theme(legend.position = "bottom")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment