Skip to content

Instantly share code, notes, and snippets.

@mxblsdl
Created April 2, 2021 17:34
Show Gist options
  • Save mxblsdl/b889346d42a5e47addc6b07afaae1d90 to your computer and use it in GitHub Desktop.
Save mxblsdl/b889346d42a5e47addc6b07afaae1d90 to your computer and use it in GitHub Desktop.
Plot two different axis in ggplot
# set the limits of each axis
# these will need to be changed for each data
# use summary(df) to get metrics
ylim_prime <- c(0.35, 0.76)
ylim_sec <- c(6200, 12000)
# calculate values for use in plot
b <- diff(ylim_prime)/diff(ylim_sec)
a <- ylim_prime[1] - b*ylim_sec[1]
# grab color variable
col1 <- unname(cadmus_palettes$cool2)[1]
col2 <- unname(cadmus_palettes$cool2)[2]
load_emssions %>%
arrange(Month, Day, HourBeginning) %>%
group_by(Month, HourBeginning) %>%
summarise(co2_per_mwh = mean(co2_per_mwh),
load = mean(load),
co2 = mean(co2)) %>%
mutate(Month = as.factor(month.abb[Month])) %>% # match month names to number
ggplot(aes(x = HourBeginning, y = co2_per_mwh)) +
geom_line(color = col1) +
geom_line(aes(y = a + load * b), color = col2) +
# Create the second axis and name it
scale_y_continuous(sec.axis = sec_axis(~(. - a) / b, name = "Demand", labels = comma)) +
facet_wrap(~ Month) +
labs(x = "Hour Beginning",
y = bquote(~'CO'^2~'/MWh'),
col = "Value") +
# Set the labels to color coordinate with the lines
theme(
axis.line.y.right = element_line(colour = col2),
axis.ticks.y.right = element_line(colour = col2),
axis.text.y.right = element_text(colour = col2),
axis.line.y.left = element_line(colour = col1),
axis.ticks.y.left = element_line(colour = col1),
axis.text.y.left = element_text(colour = col1),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment