0

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."

enter image description here

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

Sharif Amlani
  • 1,138
  • 1
  • 11
  • 25
  • 2
    Check your code. You have `df$group` in `split()` but there is no such column. Should it be `df$type` ? Also for reproducibility you should use `set.seed` when using `runif` and `rnorm`. – neilfws Apr 05 '23 at 03:00
  • 1
    Possible dupe: https://stackoverflow.com/questions/27803710/ggplot2-divide-legend-into-two-columns-each-with-its-own-title or https://stackoverflow.com/questions/67030642/ggplot2-add-extra-space-between-two-legend-items – Jon Spring Apr 05 '23 at 04:52

0 Answers0