传说多个美学的变化顺序(change order of legends for multiple a

2019-09-28 07:20发布

另一个“传说 - 问题”。

我有几个美学和希望,以指定每个美学传说绘制的顺序。 多数线程是要改变审美的项目的顺序,但是这不是我的问题。 在我的例子,我想指定填充图例的位置。 有趣地,色彩的传说绘制在填充图例的顶部,但“权利”填充传说,借鉴底部的图例时。 这似乎有点随意留给像我的权利读者谁也宁愿从顶部向底部读取。

该图显然是有些随机和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

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

由创建于2018年12月10日reprex包 (v0.2.1)

Answer 1:

您可以使用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))



文章来源: change order of legends for multiple aesthetics
标签: r ggplot2