1

For the following plot I would like to have 2 options for adding a legend:

  • add a legend displaying a single dashed line (black) with the text "3 day moving average". The legend for the bars should remain
  • add a legend diplaying 3 dashed lines (colors same as those for bar legend) with the text "3 day moving average". The legend for the bars should remain

Anyone know how to do this?

Sample code:

dat <- data.frame( x = c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6),
                   y = c(sample(10:30,6),sample(60:80,6),sample(120:150,6)),
                   z = c("A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C"))


dat2 <- dat %>%
  group_by(z) %>%
  mutate(roll_mean = rollmean(y,2, align = "right", fill=NA))


ggplot(data=dat2, aes(x=x, y=y, fill=z)) +
  geom_bar(stat="identity", position=position_dodge2(preserve = "single")) +
  geom_line(aes(y=roll_mean, color=z),size=1.1, linetype = "dashed") +
  theme_classic()                   
Joep_S
  • 481
  • 4
  • 22

1 Answers1

2

Here's a solution to your second bullet point:

ggplot(data=dat2, aes(x=x, y=y, fill=z)) +
  geom_bar(stat="identity", position=position_dodge2(preserve = "single")) +
  geom_line(aes(y=roll_mean, color=z),size=1.1, linetype = 2) +
  theme_classic() +
  scale_colour_manual(name="3 day moving average",
                      values=c("A" = "#F8766D", "B" = "#00BA38", "C" = "#619CFF"), 
                      guide = guide_legend(override.aes=aes(fill=NA))) +
  theme(legend.key.size =  unit(0.5, "in"))

enter image description here

Matt
  • 7,255
  • 2
  • 12
  • 34
  • Thanks! But where did you get the color codes to match those of the bars? – Joep_S Jan 26 '21 at 16:40
  • No problem. I found the default `ggplot2` colors here: https://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette – Matt Jan 26 '21 at 17:07