如何在ggplot2中对聚集条形图的条形进行排序

问题描述 投票:0回答:1

我编写了以下代码来生成簇状条形图。如何从最小频率到最大频率排列各个条形?

library(ggplot2)
ggplot(mpg, aes(y = trans, group = class, fill = class)) + 
      geom_bar(position = position_dodge2())

我尝试使用

fill = forcats::fct_infrq(class)
,但没有成功。

r ggplot2
1个回答
0
投票

您可以首先计算每组的值,然后创建一个返回每组排名数的列。这可以用作

group
的美感来对每组的躲避条进行排序,如下所示:

library(ggplot2)
library(dplyr)

mpg2 <- mpg %>%
  group_by(trans, class) %>%
  summarise(n = n()) %>%
  group_by(trans) %>%
  arrange(desc(n)) %>%
  mutate(bar_order = row_number()) 

ggplot(mpg2, aes(y = trans, x = n, fill = class, group = bar_order)) + 
  geom_col(position = position_dodge2())

创建于 2024-03-28,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.