I am trying to adjust the secondary y axis on this plot for the SST. I want that axis to start at 20 rather than 0 so that visually the SST data points are closer to the average RI data points rather than being right at the top
ggplot(average_RI_per_month_species, aes(x = factor(month))) +
geom_point(aes(y = avg_RI, color = species, shape = "RI"), size = 3) +
geom_line(aes(y = avg_RI, color = species, linetype = species), size = 1) +
geom_point(aes(y = av_SST / 10, shape = "SST"), color = "black", size = 3, alpha = 0.7) +
geom_line(aes(y = av_SST / 10), color = "black", size = 1, alpha = 0.7) +
scale_y_continuous(
name = "Average RI",
sec.axis = sec_axis(~ . * 10, name = "Average SST (°C)", ) ) +labs(
title = "Monthly Average RI and SST", x = "Month", color = "Species", shape = "Metric",linetype = "Species") + scale_x_discrete(labels = month.abb) +
scale_color_manual(values = c("Galapagos" = "blue", "Silky" = "red")) +
scale_shape_manual(values = c("RI" = 16, "SST" = 17)) + # 16 = filled circle, 17 = filled triangle
theme_minimal()
I tried adding: breaks = seq(25, max(average_RI_per_month_species$av_SST), by = 5))
But this just removed the 0-20 from the y axis but didnt actually make any of the SST data points move
Sure, you'd just need to adjust your transformation to add 20 in sec_axis
(so that 0 on primary axis becomes 20 on secondary axis), and subtract 20 inside aes()
for the secondary series, before the division. That's because the two operations need to be the inverse of each other. The only requirement (see ?sec_axis
) is that "All secondary axes must be based on a one-to-one transformation of the primary axes." That does not limit you to them being purely proportional to each other.
So we might have
geom_point(aes(y = (av_SST - 20) / 10, shape = "SST") ....
matched with
sec.axis = sec_axis(~ (. * 10) + 20, name = "Average SST (°C)") ...
On my own fake data, that transforms this:
into this:
data.frame(month = factor(month.abb, levels = month.abb),
av_SST = 30 + sin(1:12),
avg_RI = 0.5 + 0.5 * cos(1:12)) -> df
df |>
ggplot(aes(x = factor(month))) +
geom_point(aes(y = avg_RI, shape = "RI"), size = 3) +
geom_point(aes(y = av_SST, shape = "SST"), color = "black", size = 3, alpha = 0.7) +
scale_y_continuous(
name = "Average RI",
sec.axis = sec_axis(transform = ~., name = "Average SST (°C)", ) )
df |>
ggplot(aes(x = factor(month))) +
geom_point(aes(y = avg_RI, shape = "RI"), size = 3) +
geom_point(aes(y = (av_SST - 20) / 10, shape = "SST"), color = "black", size = 3, alpha = 0.7) +
scale_y_continuous(
name = "Average RI",
sec.axis = sec_axis(~ (. * 10) + 20, name = "Average SST (°C)", ) ) +labs(
title = "Monthly Average RI and SST", x = "Month", color = "Species", shape = "Metric",linetype = "Species")