首页 > 解决方案 > 如何更改ggplot2中geom_rects图例的顺序?

问题描述

我正在尝试使用包中的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')

输出如下所示: 代码输出

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

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

标签: rggplot2

解决方案


我们可以使用breaks参数scale_fill_discrete

g + scale_fill_discrete(breaks = heights)

在此处输入图像描述


推荐阅读