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

时间:2021-06-07 15:00:15

I use ggplot2 to draw a scatter plot which contains both a grouped and an ungrouped geom_smooth(). I would like the entry for the ungrouped smooth to appear at the top or bottom of the legend, but the legend is sorted alphabetically instead.

我使用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)

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

The problem is similar to Scott's, but including a geom_blank() does not solve it. Also, including 'all' as a level in mpg$drv makes no difference.

这个问题与Scott的类似,但是包含geom_blank()并不能解决这个问题。此外,在mpg$drv中包含“all”也没有区别。

1 个解决方案

#1


4  

Use breaks?

使用优惠吗?

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"))

#1


4  

Use breaks?

使用优惠吗?

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"))