You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言ggplot2饼图如何重排切片顺序将Other类别置于末尾

ggplot饼图固定"other"类别到末尾的实现方案

核心原因是你当前用reorder(IndSec, amt)会对所有行业类别按照排放量数值自动排序,只要合并后的"other"类别数值不是最小的,就会被自动插入到饼图中间位置,要固定位置只需要手动调整因子水平,强制把"other"放到所有类别的最后即可。

操作步骤

  • 先完成数据汇总、排放量较小部门合并为"other"的预处理
  • 对分类变量IndSec做因子水平调整:先将除"other"外的类别按你需要的顺序(通常是排放量从高到低)排序,再将"other"强制追加到因子水平的最后一位
  • 传入ggplot绘图即可,不需要改动原有饼图的绘图逻辑

修正后完整代码

library(dplyr)
library(ggplot2)
library(forcats)

plot_data <- tri1987tce %>% 
  group_by(IndSec) %>% 
  summarize(amt = sum(`61. ON-SITE RELEASE TOTAL`)/1000) %>%
  # 小类别合并逻辑示例:将排放量占总排放比例低于2%的部门合并为other,可按需调整阈值
  mutate(IndSec = ifelse(amt / sum(amt) < 0.02, "other", IndSec)) %>%
  group_by(IndSec) %>%
  summarize(amt = sum(amt)) %>%
  # 核心因子调整逻辑
  mutate(
    # 非other类别按排放量从高到低排序
    IndSec = fct_reorder(IndSec, amt, .desc = TRUE),
    # 无视数值大小,把other强制放到所有因子的最后一位
    IndSec = fct_relevel(IndSec, "other", after = Inf)
  )

# 绘制饼图
ggplot(plot_data, aes(x = "", y = amt, fill = IndSec)) +
  geom_col(width = 1, color = "white") +
  coord_polar("y", start = 0) +
  theme_void()

注:如果不想用forcats包的函数,也可以用基础R的因子调整语法实现相同效果:

# 基础R实现因子调整
non_other_levels <- plot_data$IndSec[plot_data$IndSec != "other"]
non_other_levels <- non_other_levels[order(plot_data$amt[plot_data$IndSec != "other"], decreasing = TRUE)]
plot_data$IndSec <- factor(plot_data$IndSec, levels = c(non_other_levels, "other"))

问题复现参考图

当前代码输出的饼图效果

内容的提问来源于stack exchange,提问作者nahgemp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 10:09:20