I already have 'color' and 'fill' legends. How can I control the colour of a line produced using geom_vline? - TagMerge
1I already have 'color' and 'fill' legends. How can I control the colour of a line produced using geom_vline?I already have 'color' and 'fill' legends. How can I control the colour of a line produced using geom_vline?

I already have 'color' and 'fill' legends. How can I control the colour of a line produced using geom_vline?

Asked 11 months ago
0
1 answers

One option to achieve your desired result would be to override the aesthetics applied to your linetype legend using the override.aes argument of guide_legend which allows you to set the colors for each legend item:

library(dplyr)
library(ggplot2)
library(scales)

ggplot() +
  # Rectangle covering last few days
  geom_rect(aes(
    xmin = max(data_bar$date) + 4, xmax = max(data_bar$date), ymin = -Inf, ymax = Inf,
    fill = "Time period subject\nto reporting delays"
  ), colour = NA, alpha = .2) +
  # Bar plot
  geom_bar(data = data_bar, aes(fill = count_variable, y = count, x = date), position = "dodge", stat = "identity") +
  scale_fill_manual(
    labels = c("Pass", "Fail", "Time period subject\nto reporting delays"),
    values = c("green", "red", "#e4004620")
  ) +
  # Line plot
  geom_line(data = data_line, aes(x = date, y = perc / 3, color = perc_variable)) +
  # scale_color_manual(labels = c("Pass rate"), values = c("blue")) +
  # Vertical lines
  geom_vline(aes(xintercept = as.Date("2022-01-05"), linetype = "Exam change 1 announced"), color = "orange") +
  geom_vline(aes(xintercept = as.Date("2022-01-06"), linetype = "Exam change 1"), color = "orange") +
  geom_vline(aes(xintercept = as.Date("2022-01-12"), linetype = "Exam change 2 announced"), color = "black") +
  geom_vline(aes(xintercept = as.Date("2022-01-13"), linetype = "Exam change 2"), color = "black") +
  scale_color_manual(
    labels = c(
      "Pass rate", "Exam change 1 announced", "Exam change 1",
      "Exam change 2 announced", "Exam change 2"
    ),
    values = c("blue", "orange", "orange", "black", "black")
  ) +
  scale_linetype_manual(
    values = c("longdash", "solid", "longdash", "solid"),
    limits = c(
      "Exam change 1 announced", "Exam change 1",
      "Exam change 2 announced", "Exam change 2"
    ),
    labels = c(
      "Exam change 1 announced", "Exam change 1",
      "Exam change 2 announced", "Exam change 2"
    )
  ) +
  scale_y_continuous(
    sec.axis = sec_axis(~ . * 3, name = "Percentage"),
    labels = comma
  ) +
  guides(linetype = guide_legend(override.aes = list(color = c("orange", "orange", "black", "black"))))

Source: link

Recent Questions on r

    Programming Languages