4

Another "legend - question".

I have several aesthetics and wish to specify the order in which the legends for each aesthetic are drawn. Most threads are about changing the order of the items within an aesthetic, but that's not my problem. In my example, I would like to specify the location of the fill legend. Funnily, the color legend is drawn on top of the fill legend, but "right" to the fill legend, when drawing the legend on the bottom. That seems somewhat random to left to right readers like me who also rather read from the top to the bottom.

The graph is obviously somewhat random and was just quickly made for reprex purpose.

library(ggplot2)

ggplot(mtcars) +
  geom_boxplot(aes(cyl, hp, fill = as.character(gear))) +
  geom_boxplot(aes(cyl, disp, color = as.character(cyl))) +
  labs(fill = 'fill', color = 'color')

# here I would like the fill legend to be *above* the color legend

ggplot(mtcars) +
  geom_boxplot(aes(cyl, hp, fill = as.character(gear))) +
  geom_boxplot(aes(cyl, disp, color = as.character(cyl))) +
  labs(fill = 'fill', color = 'color') +
  theme(legend.position = 'bottom')

# here I would like the fill legend to be *right* and the color legend left

Created on 2018-12-10 by the reprex package (v0.2.1)

tjebo
  • 21,977
  • 7
  • 58
  • 94

1 Answers1

10

You can use the order option of guide_legend:

ggplot(mtcars) +
  geom_boxplot(aes(cyl, hp, fill = as.character(gear))) +
  geom_boxplot(aes(cyl, disp, color = as.character(cyl))) +
  labs(fill = 'fill', color = 'color') +
  guides(fill  = guide_legend(order = 1),
         color = guide_legend(order = 2))

enter image description here

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
  • 1
    Danke, Martin! That's exactly what I was looking for :) – tjebo Dec 10 '18 at 11:22
  • Surprising how hard it was to find this trick! I don't normally care about the order but when using second y-axis with legend at the bottom it greatly helps readability to have them match their axis. – Will Hore-Lacy Jun 18 '20 at 04:47