使用组合项目更改 ggplot2 图例中项目的顺序

Change order of items in ggplot2 legend with combined items

我使用 ggplot2 绘制散点图,其中包含分组和未分组 geom_smooth()。我希望未分组平滑的条目出现在图例的顶部或底部,但图例是按字母顺序排序的。

my.colors <- c('4' = 'red', 'f' = 'green', 'r' = 'blue', 'all' = 'black')
ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(color = drv), alpha = 1/3) + theme_bw() +
  geom_smooth(aes(color = drv), method = 'lm') +
  geom_smooth(aes(color = 'all'), method = 'lm') +
  scale_color_manual(name = "Drive Types", values = my.colors)

问题类似于Scott's,但包含一个geom_blank()并不能解决问题。此外,将 'all' 作为 mpg$drv 中的级别也没有区别。

使用休息时间?

my.colors <- c('4' = 'red', 'f' = 'green', 'r' = 'blue', 'all' = 'black')
ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(color = drv), alpha = 1/3) + theme_bw() +
  geom_smooth(aes(color = drv), method = 'lm') +
  geom_smooth(aes(color = 'all'), method = 'lm') +
  scale_color_manual(name = "Drive Types", values = my.colors, 
                     breaks=c("all", "4", "f", "r"))