Reputation: 717
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)
Upvotes: 0
Views: 280
Reputation: 17204
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.
Upvotes: 1
Reputation: 17204
You can add a legend across multiple geoms by
color = "label"
within aes()
for each geom, where "label"
is a unique label for each geom; thenscale_color_manual()
(or scale_linetype_manual()
, etc, depending on the aesthetic), and set the values
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)
Upvotes: 1