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)
CodePudding user response:
You can add a legend across multiple geoms by
- setting
color = "label"
withinaes()
for each geom, where"label"
is a unique label for each geom; then - add
scale_color_manual()
(orscale_linetype_manual()
, etc, depending on the aesthetic), and set thevalues
arg to a named vector whose names correspond to the geom labels, and values correspond to the colors (or linetypes, or whatever) wanted.
ggplot(data = data,aes(x = x, y = Y1))
geom_errorbar(
aes(ymin = Y1 - SD1, ymax = Y1 SD1, color = "Y1"),
width = 0.9,
size = 1.5
)
geom_point(aes(y = Y1), color = "black")
geom_errorbar(
aes(ymin = Y2 - SD2, ymax = Y2 SD2, color = "Y2"),
width = 0.9,
size = 1.5
)
geom_point(aes(y = Y2), color = "black")
scale_y_continuous(
"first y axis",
sec.axis = sec_axis(Y2 ~ .*(5), name = "second y axis")
)
scale_color_manual("legend title", values = c(Y2 = "blue", Y1 = "orange"))
expand_limits(x = 0, y = 0)
CodePudding user response:
Often, if you find yourself making multiples of the same geom with manual aesthetics, it's a sign you should
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.