另一个“传奇-问题”。
我有几种美学,并希望指定绘制每种美学的图例的顺序。多数线程有关更改项目的顺序中的审美,但是这不是我的问题。在我的示例中,我想指定填充图例的位置。有趣的是,当在底部绘制图例时,颜色图例绘制在填充图例的顶部,但“右”到填充图例。对于像我这样的从上到下阅读的从左到右的读者来说,这似乎有些随机。
该图显然有些随机,只是为了 reprex 目的而快速制作的。
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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

您可以使用以下order选项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))
Run Code Online (Sandbox Code Playgroud)