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

使用指定水平因子时ggplot2 Y轴标签排序失效问题解决

解决方案:让Y轴标签按DATA原始顺序排列

问题出在你对Recommendations变量的处理顺序上:你先将其转换为因子,但紧接着用stringr::str_wrap重新赋值时,会把因子转回字符类型,导致之前设置的因子层级完全失效。

以下是两种可行的修复方法:

方法1:先处理换行,再转换为因子(保留原始顺序)

先对文本做换行处理,再基于处理后的字符串设置因子层级,确保顺序和DATA一致:

library(tidyverse)
library(scales)

DATA %>% 
  mutate(
    # 先处理文本换行
    Recommendations = stringr::str_wrap(Recommendations, 30),
    # 转换为因子,levels用处理后的字符串的原始顺序
    Recommendations = factor(Recommendations, levels = unique(Recommendations))
  ) %>% 
  ggplot(aes(y = Recommendations, x = `Number of Responses`)) +
  geom_col(fill = "steelblue") +
  geom_text(
    aes(label = paste0(`Number of Responses`, "(", scales::percent(`Number of Responses` / sum(`Number of Responses`), accuracy = 1), ")")), 
    hjust = 0, nudge_x = 1, size = 3, fontface = 2
  ) +
  theme_minimal(16) +
  theme(
    panel.grid = element_blank(),
    axis.line.y = element_line(),
    axis.text = element_text(size = 9)
  )

方法2:使用forcats::fct_inorder自动保留顺序

用forcats包的fct_inorder函数,直接基于数据中的出现顺序设置因子层级,无需手动指定levels:

library(tidyverse)
library(scales)
library(forcats)

DATA %>% 
  mutate(
    Recommendations = stringr::str_wrap(Recommendations, 30),
    # 按数据中的出现顺序设置因子层级
    Recommendations = fct_inorder(Recommendations)
  ) %>% 
  ggplot(aes(y = Recommendations, x = `Number of Responses`)) +
  geom_col(fill = "steelblue") +
  geom_text(
    aes(label = paste0(`Number of Responses`, "(", scales::percent(`Number of Responses` / sum(`Number of Responses`), accuracy = 1), ")")), 
    hjust = 0, nudge_x = 1, size = 3, fontface = 2
  ) +
  theme_minimal(16) +
  theme(
    panel.grid = element_blank(),
    axis.line.y = element_line(),
    axis.text = element_text(size = 9)
  )

核心原理

stringr::str_wrap的返回值是字符向量,会覆盖之前的因子类型。必须保证因子转换操作在换行处理之后,或者用fct_inorder自动识别数据中的顺序,才能让Y轴标签按DATA的原始顺序显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 08:30:04