2

I am producing a map with ggplot2 with colours to represent six types of areas, which can be further regrouped in three categories.

With

scale_fill_manual(labels=MyLabels, values=MyColors)

I can get a simple legend like this, showing the 6 areas:

enter image description here

But for publication purpose, what I would like to get is:

enter image description here

Id est, with main categories included as subheadings in the legend.

How is that feasible ?

Evargalo
  • 126
  • 6
  • When the legend is unconventional like this, consider drawing it from scratch on a separate plot, then inserting it as a subplot, or laying out [multiple plots](https://cran.r-project.org/web/packages/egg/vignettes/Ecosystem.html) (where one plot is just the custom legend). See also https://stackoverflow.com/questions/1249548/side-by-side-plots-with-ggplot2. – wibeasley Nov 19 '18 at 14:56
  • My first thought for an alternative was to produce multiple legends, each with their own title. Unfortunately, I think `ggplot2` does not support multiple legends for the same aesthetic (perhaps a niche feature to support), so your only options will include either (a) using a single legend with "fake" entries, as Adela offered in a answer; or (b) manually creating a neighbor plot (perhaps using `gridExtra::grid.arrange` to combine them), this option allows you to manually control indentation. – r2evans Nov 19 '18 at 15:09

1 Answers1

4

You can try to add fake rows into your data and with these fake rows you can create subheadings.

There is a sample data with fake values:

df <- data.frame(x = 1:9,
                 y = c(0, 0, 0, rnorm(6)),
                 g = factor(c("fakedog", "bigdog", "smalldog", 
                       "fakerabbit", "rabbit",
                       "fakecat", "white", "black", "gray")))

Now I create set labels and colours to use in ggplot:

lbl <- c(expression(bold("dogs")), "big dogs", "small dogs",
         expression(bold("rabbits")), "rabbits",
         expression(bold("cats")), "white", "black", "gray")
colo <- c(NA, "red1", "red3",
          NA, "blue1", 
          NA, "green1", "green2", "green3")

And plot sample data:

library(ggplot2)
ggplot(df, aes(x = x, y = y, col = g)) +
  geom_point() + 
  scale_colour_manual("Terrirories where people like", values = colo, label = lbl) + 
  theme(legend.key = element_rect(fill = NA))

Final output:

enter image description here

Adela
  • 1,757
  • 19
  • 37
  • 1
    Thanks, great and fast answer. It solves my problem perfectly. You will get the check soon, I just let one day pass in case another astuce is proposed. – Evargalo Nov 20 '18 at 09:31