Reputation: 23807
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)
Upvotes: 4
Views: 1529
Reputation: 23919
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))
Upvotes: 12