I have a line chart with metrics for different years and months. I want to add a median line for each month.
library(dplyr)
library(lubridate)
library(ggplot2)
set.seed(52)
data <- tibble(
date = seq.Date(from = as.Date("2017-01-01"), to = date("2020-12-31"), by = "month")
) %>%
mutate(
metric = rnorm(n(), mean = 5, sd = 2),
month = month(date, label = TRUE),
year = as.factor(year(date))
)
ggplot(data, aes(x = month, y = metric, color = year, group = year)) +
geom_line()

I tried using geom_hline() to do this but it only produces a line for the total median.
ggplot(data, aes(x = month, y = metric, color = year, group = year)) +
geom_line() +
geom_hline(aes(yintercept = median(metric), group = month))

Created on 2021-11-18 by the reprex package (v2.0.1)
What is the easiest way to create a median line for each month? Like this:




