I am looking for a way to create a two by two legend in ggplot.
Suppose I have two factors, age (young, old) in linetype and gender (female, male) in color. I want a legend displaying the four possibilities in a two by two table with key legends inside. Something like that:
Female Male
Young
Old
Note that I don't want two legends with two groups (see below). Neither I want a legend with four groups one below the others (see below).
df = expand_grid(
year = c(2010, 2020),
gender = c('male', 'female'),
age = c('young', 'old')) %>%
mutate(
group = str_c( gender, '; ', age),
y = 1:8)
dont_want_1 = ggplot(df, aes(x=year, y = y, color = gender, linetype = age)) +
geom_line()
dont_want_2 = ggplot(df, aes(x=year, y = y, color = group, linetype = group)) +
geom_line()