'Adding legend to a plot based error bar color

I have prepared sample data. I want to add a legend for this plot based on the error bar color. I tried to add legend manually, but it is not working. Thank you for the hlep.

data = data.frame(x = c(5,  10, 15, 20, 25, 30, 35, 40, 50),
                  Y1 = c(179,   212,    201,    204,    220,    181,    176,    219,    182),
                  SD1 = c(58,   93, 74, 55, 59  ,56,    53, 62, 62),
                  Y2 = c(273,   267,    329,    329,    386,    401,    399,    350,    274),
                  SD2 = c(107,  85, 141,    126,    94, 101,    65, 65, 58)) 
Y21 = data$Y2/5
SD21 = data$SD2/5
data = cbind(data, Y21, SD21)

ggplot(data=data,aes(x = x ,y=Y1))+
  geom_errorbar(data=data,aes(ymin=Y1-SD1,ymax=Y1+SD1), colour="orange", width = 0.9, size = 1.5, linetype = "solid")+
  geom_point(aes(y=Y1), color = "black")+
  geom_errorbar(data=data,aes(ymin=Y2-SD2,ymax=Y2+SD2),color="blue", width = 0.9, size = 1.5, linetype = "solid")+
  scale_y_continuous("first y axis", sec.axis = sec_axis(Y2~ .*(5)  , name = "second y axis" ))+
  geom_point(aes(y=Y2), color = "black")+
  expand_limits(x = 0, y = 0)

enter image description here



Solution 1:[1]

Often, if you find yourself making multiples of the same geom with manual aesthetics, it's a sign you should pivot your data to long format and use a single geom with mapped aesthetics instead. In your case, this will give you a legend and also simplify the ggplot2 specification.

library(tidyverse)

data %>% 
  pivot_longer(Y1:SD2, names_to = c(".value", "yNum"), names_pattern = "(\\D+)(\\d)") %>% 
  ggplot(aes(x = x, y = Y)) +
  geom_errorbar(
    aes(ymin = Y - SD, ymax = Y + SD, color = yNum), 
    width = 0.9, 
    size = 1.5
  ) +
  geom_point(aes(y = Y), color = "black") +
  scale_y_continuous(
    "first y axis", 
    sec.axis = sec_axis(Y2 ~ .*(5), name = "second y axis")
  ) +
  scale_color_manual(values = c("orange", "blue")) +
  expand_limits(x = 0, y = 0)

If you really do need to or prefer to use separate geoms, though, I've described how to generate a legend across multiple geoms in a separate answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zephryl