Reputation: 6416
Given some data like:
my.data <- data.frame(time = rep(1:3, 2),
means = 2:7,
lowerCI = 1:6,
upperCI = 3:8,
scenario = rep(c("A","Z"), each=3))
my.data
# time means lowerCI upperCI scenario
# 1 1 2 1 3 A
# 2 2 3 2 4 A
# 3 3 4 3 5 A
# 4 1 5 4 6 Z
# 5 2 6 5 7 Z
# 6 3 7 6 8 Z
I need to make a plot like the one below but some label for the (confidence) dotted lines should appear in the legend - the order matters, should be something like Z, A, CI-Z, CI-A (see below). This is the corresponding code:
ggplot(data = my.data) +
# add the average lines
geom_line(aes(x=time, y=means, color=scenario)) +
# add "confidence" lines
geom_line(aes(x=time, y=lowerCI, color=scenario), linetype="dotted") +
geom_line(aes(x=time, y=upperCI, color=scenario), linetype="dotted") +
# set color manually
scale_color_manual(name = 'Scenario',
breaks = c("Z", "A"),
values = c("Z" = "red",
"A" = "blue"))
Below is my attempt after I checked this & this SO similar questions. I get close enough, but I want the "CI" labels not to be separate.
ggplot(data = my.data) +
# add the average lines
geom_line(aes(x=time, y=means, color=scenario)) +
# add "confidence" lines
geom_line(aes(x=time, y=lowerCI, color=scenario, linetype="CI")) +
geom_line(aes(x=time, y=upperCI, color=scenario, linetype="CI")) +
# set color manually
scale_color_manual(name = 'Scenario',
breaks = c("Z", "A"),
values = c("Z" = "red",
"A" = "blue")) +
# set line type manually
scale_linetype_manual(name = 'Scenario',
breaks = c("Z", "A", "CI"),
values = c("Z" = "solid",
"A" = "solid",
"CI" = "dotted"))
I also tried something using geom_ribbon
, but I could not find a clear way to make it display only the edge lines and add them as desired in the legend. All in all, I don't need to display bands, but lines.
I'm sure there is an obvious way, but for now I'm stuck here...
Upvotes: 0
Views: 2427
Reputation: 10761
We can use guide_legend
to specify dashed linetypes for the CI's. I think this is close to what you want:
ggplot(my.data, aes(x = time, y = means))+
geom_line(aes(colour = scenario))+
geom_line(aes(y = lowerCI, colour = paste(scenario, 'CI')),
linetype = 'dashed')+
geom_line(aes(y = upperCI, colour = paste(scenario, 'CI')),
linetype = 'dashed')+
scale_colour_manual(values = c('A' = 'red','Z' = 'blue',
'A CI' = 'red','Z CI' = 'blue'),
breaks = c('Z', 'Z CI', 'A', 'A CI'))+
guides(colour = guide_legend(override.aes = list(linetype = c('solid', 'dashed'))))+
ggtitle('Dashed lines represent X% CI')
Upvotes: 2