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

如何在ggplot中重新排序含数字的字符串型坐标轴刻度?

解决ggplot中DQQ系列X轴按数字顺序排列的问题

你当前代码里用fct_relevel(DQQ, sort)是按字符串规则排序,会出现类似DQQ10排在DQQ2前面的问题——因为字符串排序是逐个字符比较,"10"的第一个字符"1"比"2"小,不符合你要的数字递增顺序。下面给你几个可行的解决思路:

方法1:提取数字后按数值重排因子

用stringr包提取DQQ后缀的数字,转成数值型后,用fct_reorder按数值大小重排因子顺序:

library(stringr)
library(forcats)

d %>%
  filter(ISO3 == "SLE") %>%
  select(starts_with("DQQ"), YEAR_WAVE) %>%
  pivot_longer(cols = starts_with("DQQ"), names_to = "DQQ", values_to = "Value") %>%
  filter(Value == 1) %>%
  mutate(
    DQQ_num = as.numeric(str_extract(DQQ, "\\d+")), # 提取DQQ后面的数字
    DQQ = fct_reorder(DQQ, DQQ_num) # 按数字大小重排因子
  ) %>%
  ggplot(aes(DQQ, fill = as.factor(YEAR_WAVE))) +
  geom_bar(position = "dodge") +
  labs(
    title = "DQQ YES Answer Counts",
    subtitle = "Counts of 'Yes' answers to DQQ indicators for Sierra Leone",
    fill = "Year"
  ) +
  scale_y_continuous(expand = expansion(add = c(0, 200))) +
  theme(
    panel.background = element_rect(fill = "white"),
    panel.border = element_blank(),
    axis.line.x = element_blank(),
    axis.line.y = element_blank(),
    plot.margin = unit(c(0, .5, 0, 0), "cm"),
    axis.ticks.length = unit(0, "cm"),
    legend.position = c(0.75, .95),
    legend.justification = c("right", "top"),
    legend.box.just = "right",
    legend.margin = margin(6, 6, 6, 6),
    axis.title.y = element_text(color = "#993333", size = 14, face = "bold"),
    axis.title.x = element_blank(),
    axis.text.x = element_text(face="bold", color="#993333", size = 12, angle=90, hjust = 0.1, vjust = 0.5)
  )

方法2:在aes中直接处理排序逻辑

如果不想新增辅助列,可以直接在ggplot的aes参数里完成排序:

ggplot(aes(fct_relevel(DQQ, DQQ[order(as.numeric(str_extract(DQQ, "\\d+")))]), fill = as.factor(YEAR_WAVE))) +
# 后续图层、主题代码保持不变

方法3:手动指定因子顺序(适合DQQ数量少的场景)

如果你的DQQ指标数量不多,也可以直接手动列出顺序:

mutate(DQQ = factor(DQQ, levels = c("DQQ1", "DQQ2", "DQQ3", "DQQ4", ...)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 01:03:13