在条形图中绘制顶部n和其他

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

我正在使用来自Kaggle的WW2 ally bombings dataset,它有一个五级的分类变量。我试图绘制两个最高的轰炸机(美国和英国)并将其他(南非,新西兰,澳大利亚)划分为条形图。

如何将最小的组聚合成“其他”组?

目前的方法

我有一个解决方法,将使用xlim绘制前两个。我想知道在R中是否有一种简单的方法可以将残差分组并将它们绘制为“其他”?

ggplot(data = operations) +
geom_bar(mapping = aes(x = Country, fill = Country)) + xlim('USA', 'GREAT 
         BRITAIN')+
ggtitle("Allied Bombings") +
    xlab("Country") + ylab("Bombs Dropped") +
    theme(plot.title = element_text(hjust = 0.5))+
    theme(panel.background = element_rect(fill = 'transparent', colour = NA))
r ggplot2
1个回答
3
投票

您可以使用fct_lump包中的forcats函数,该函数将最少/最常见的因子级别聚合到“其他”中。

这是一个可重复的例子。在此示例中仅保留两个最大的组:

df <- data.frame(group =rep(LETTERS[1:9], times = c(40, 10, 5, 27, 1, 1, 1, 1, 1)))

library(forcats)
df$groupLump <- fct_lump(df$group, 2)

library(ggplot2)
ggplot(df) +
  geom_bar(aes(x = groupLump, fill = groupLump))

enter image description here

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