legend in multiple y-axis plot

I think what you want is the code below. Notice that what is plotted for CR5, geom_line(), is 3 times the actual value and that the transformation in sec.axis() divides the labeling by 3. So, the values of CR5 get scaled up to have convenient values on the left plotting axis but the values displayed on the right axis, which labels CR5, show the actual CR5 values.

library(ggplot2)
ggplot(data_plot, aes(x = year)) +
  geom_line(aes(y = avg_z_score, linetype = "avg_z_score"), size = 1.1 ) +
  geom_line(aes(y = CR5*3, linetype = "CR5"), size = 1.1) +
  scale_y_continuous(
    name = "Avg. z score",
    breaks = seq(0, 3, by = 1),
    limits = c(0, 3),
    sec.axis = sec_axis(
      name = "CR5",
      breaks = seq(0, 1, by = .25),
      trans = ~./3
    )
  ) +
  scale_linetype_manual(name= NULL,values = c("avg_z_score" = 1, "CR5" = 4), 
                        labels = c("Avg. DtD", "CR5")) +
  theme(legend.position = "bottom",
        axis.title.x = element_blank(),
        legend.title = element_text(),    
        legend.key.width = unit(3, "cm"),
        axis.title.y = element_text(colour = "black", face = "bold"),  # Darken y-axis label
        axis.text.x = element_text(colour = "black", face = "bold"),  # Darken x-axis tick labels
        axis.text.y = element_text(colour = "black", face = "bold"),  # Darken y-axis tick labels
        legend.text = element_text(colour = "black", face = "bold"))  # Darken legend text

1 Like