如何在ggplot2中更改geom_rects图例的顺序?

时间:2020-07-20 14:25:24

标签: r ggplot2

我正在尝试使用geom_rect()包中的ggplot2几何图形绘制图形。

这是我的MWE:

library(tidyverse)

groups = tribble(
    ~size, ~income,
    10, 400,
    60, 500,
    20, 600
)
heights = c("Height <= 60 Inches",
            "Height 61-70 Inches",
            "Height >= 71 Inches")

g = ggplot()
g = g + geom_rect(aes(xmin = 0, 
                      ymin = 0,
                      xmax = groups$size[1],
                      ymax = groups$income[1],
                      fill = heights[1]))
g = g + geom_rect(aes(xmin = groups$size[1],
                      ymin = 0,
                      xmax = sum(groups$size[1:2]),
                      ymax = groups$income[2],
                      fill = heights[2]))
g = g + geom_rect(aes(xmin = sum(groups$size[1:2]),
                      ymin = 0,
                      xmax = sum(groups$size[1:3]),
                      ymax = groups$income[3],
                      fill = heights[3]))
g = g + labs(fill = 'People Groups')

输出如下所示: output of code

我对在绘图上绘制矩形的方式感到满意, 但是,我对填充顺序的混乱感到不满意。

如何将填充顺序更改为: “高度<= 60英寸”,“高度61-70英寸”,“高度> = 71英寸”?

1 个答案:

答案 0 :(得分:2)

我们可以在scale_fill_discrete中使用breaks参数

g + scale_fill_discrete(breaks = heights)

enter image description here