I'm trying to make a bar chart of numbers, with an overlaid line and confidence interval for the rate. I want the legend to make sense, i.e. one entry for the bars and one for the line and confidence interval.
This is what I've got so far. It's almost perfect, except for the red border around the legend key for the rate. I can't figure out how to remove the border without removing the line too. Am I missing something? Am I going about the whole construction of the legend wrong? I haven't used scale_xxx_identity()
before and what I'm doing feels like a bit of a hack, so I'm open to other options.
library(tidyverse)
test <- tibble(year = 2001:2010,
number = 20:29,
rate = 0.02,
rate_l = 0.015,
rate_u = 0.025)
secondAxisFactor <- 500
test %>%
ggplot(aes(factor(year), number)) +
geom_col(aes(fill = "turquoise",
colour = "transparent")) +
geom_ribbon(aes(ymin = rate_l * secondAxisFactor,
ymax = rate_u * secondAxisFactor,
group = 1,
fill = "pink"),
alpha = 0.8) +
geom_line(aes(y = rate * secondAxisFactor,
group = 1,
colour = "red"),
size = 1) +
scale_fill_identity(name = NULL,
guide = "legend",
breaks = c("turquoise", "pink"),
labels = c("Number", "Rate (95% CI)")) +
scale_color_identity(name = NULL,
guide = "legend",
breaks = c("transparent", "red"),
labels = c("Number", "Rate (95% CI)"))
I've also tried having a fill legend only for the bars and a colour legend only for the line, and then setting the legend.key
fill to pink in theme()
. That also almost works, but the pink peeks out from behind the turquoise. Perhaps there's a way to fix that?
test %>%
ggplot(aes(factor(year), number)) +
geom_col(aes(fill = "turquoise")) + # removed transparent
geom_ribbon(aes(ymin = rate_l * secondAxisFactor,
ymax = rate_u * secondAxisFactor,
group = 1), # pink not in aes()
fill = "pink",
alpha = 0.8) +
geom_line(aes(y = rate * secondAxisFactor,
group = 1,
colour = "red"),
size = 1) +
scale_fill_identity(name = NULL,
guide = "legend",
# fill legend only for bars
breaks = c("turquoise"),
labels = c("Number")) +
scale_color_identity(name = NULL,
guide = "legend",
# colour legend only for line
breaks = c("red"),
labels = c("Rate (95% CI)")) +
# setting legend.key fill to pink
theme(legend.key = element_rect(fill = "pink"))