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

ggplot2分面绘图中按指定分面组数值重排X轴类别顺序

解决方案

你当前代码排序不符合预期的核心原因是reorder(PopName, Dx)默认使用所有年龄组的Dx值计算排序权重,没有限定仅使用65岁年龄组的死亡数据作为排序依据。以下方法对任意数量的X轴类别(包括50个州的全量场景)都适用,不需要手动逐个调整类别顺序。

方法1:绘图时直接指定排序规则

不需要修改原始数据,在reorder函数内筛选仅65岁年龄组的Dx值作为排序权重即可:

library(tidyverse)

CAPS_plot_facet <- CAPS_2019 %>% 
  ggplot(aes(
    x = reorder(PopName, Dx[Age == "65"], FUN = mean), 
    y = Dx, 
    fill = factor(as.character(Age))
  )) +
  geom_col(position = position_stack(reverse = TRUE)) +
  facet_wrap("Age", scales = "free_x") +
  theme_classic() +
  theme(strip.background = element_blank(), strip.text = element_blank()) +
  coord_flip() +
  labs(x = "State", y = "Deaths (%)", caption = "", face = "bold", fill = "Age")

CAPS_plot_facet

方法2:提前重排数据因子水平

如果后续需要复用排序后的州维度,可以先在数据预处理阶段把PopName的因子水平按65岁组Dx值排好再绘图,全量50个州场景下该方式效率更高:

# 预处理阶段完成因子排序
CAPS_2019 <- CAPS_2019 %>%
  mutate(PopName = reorder(PopName, Dx[Age == "65"], FUN = mean))
  # 若需要按65岁死亡数从高到低排序,把上面一行替换为下面的代码即可
  # mutate(PopName = reorder(PopName, desc(Dx[Age == "65"]), FUN = mean))

# 绘图时直接调用PopName即可
CAPS_plot_facet <- CAPS_2019 %>% 
  ggplot(aes(x = PopName, y = Dx, fill = factor(as.character(Age)))) +
  geom_col(position = position_stack(reverse = TRUE)) +
  facet_wrap("Age",scales="free_x")+
  theme_classic()+
  theme(strip.background = element_blank(), strip.text = element_blank())+
  coord_flip()+
  labs(x = "State", y = "Deaths (%)", caption = "", face = "bold", fill = "Age")

CAPS_plot_facet

注意事项

  • 该方法自动适配任意数量的X轴类别,哪怕是50个州的全量数据也不需要手动枚举州名调整顺序
  • 排序后的州顺序会在所有分面中保持统一,不会出现分面间类别顺序错乱的问题
  • 如果需要反转排序方向(按65岁组死亡数从高到低排列),只需要在排序的Dx值外包裹desc()函数即可

你当前代码生成的原图效果如下:
当前绘图效果


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 16:33:26