I'm trying to make a plot with a single legend with two titles.
For example, the figure below is the original. I would like to split its legend so that line 1 and line 2 have the legend title "Group 1" and line 3 and line 4 to have the legend title "Group 2."
Here is a reproducible code:
set.seed(1993)
# create years from 2017 to 2022
years <- 2017:2022
# set number of groups per year
ngroups <- 4
# create a data frame with same groups per year but varying groups within each year
df <- expand.grid(
year = rep(years, each = ngroups),
value = rep(runif(length(years), min = 0, max = 100), each = ngroups) + rnorm(length(years) * ngroups, sd = 10),
type = factor(rep(1:ngroups, length(years))),
stringsAsFactors = FALSE
)
# randomly shuffle the order of the levels within each year
df$type <- unlist(lapply(split(df$type, df$year), function(x) sample(x)))
library(ggplot2)
ggplot(df, aes(x =year, y = value, linetype = type, color = type)) +
geom_line()