0

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()

enter image description here

dont_want_2 =    ggplot(df, aes(x=year, y = y, color = group, linetype = group)) + 
                  geom_line()

enter image description here

Rtist
  • 3,167
  • 1
  • 25
  • 34
  • 3
    Hi, I found this old answer: https://stackoverflow.com/a/17426936/10264278. It could be a start for a `ggplot` only solution or an uptaded one. Another (similar) idea: https://stackoverflow.com/a/46065025/10264278 – Paul Aug 11 '21 at 12:54

0 Answers0