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

如何在geom_bar图表中同时使用str_wrap与按值降序重排列

问题:ggplot中同时实现条形按数值降序排序与长标签换行

现有名为perc_responses_1的数据框,结构如下:

Options      Percent
a_Option1      0.03
z_Option2      0.05
b_Option3      0.50
x_Option4      0.25

需求:

  1. 创建条形图,条形按Percent数值降序排列(即b_Option3排第一,x_Option4第二,以此类推)
  2. 实际的选项标签很长(例如"Purchasing more land for parks and open space"),需要用str_wrap实现标签换行显示

已设置行名称:

rownames(perc_responses_1) <- c("More bike paths and hiking trails","Removal of invasive plant species","Updating buildings and facilities","Purchasing more land for parks and open space") 

遇到的问题:

  • 添加str_wrap后,条形会按字母顺序重新排序(如下代码):
ggplot(perc_responses_1, aes(x = reorder(Options, -Percent), Percent)) +
  geom_bar(stat = "identity") + 
  coord_flip()+
  scale_y_continuous(labels = scales::percent, limits = c(0, .7))+
  aes(stringr::str_wrap(Options, 20), Percent) +
  labs(x = "Options") + theme_bw()
  • 不添加str_wrap时,条形顺序正确,但标签无法换行(如下代码):
ggplot(perc_responses_1, aes(x = reorder(Options, -Percent), Percent)) +
  geom_bar(stat = "identity") + 
  coord_flip()+
  scale_y_continuous(labels = scales::percent, limits = c(0, .7))+
  labs(x = "Options") + theme_bw()

解决方案

问题出在第二次调用aes()时,覆盖了之前的x轴映射——原本用reorder(Options, -Percent)实现的排序被替换成了原始Options经str_wrap处理后的结果,而这个结果会按字母顺序排序。

可以通过两种方式解决:

方法一:在reorder后直接对结果应用str_wrap

把x轴的映射直接写成先排序、再换行的形式,既保留排序逻辑,又实现标签换行:

library(ggplot2)
library(stringr)

ggplot(perc_responses_1, aes(x = stringr::str_wrap(reorder(Options, -Percent), 20), Percent)) +
  geom_bar(stat = "identity") + 
  coord_flip()+
  scale_y_continuous(labels = scales::percent, limits = c(0, .7))+
  labs(x = "Options") + 
  theme_bw()

方法二:提前在数据框中处理标签并指定顺序

先在数据框中新增一列,同时完成排序(用factor指定水平顺序)和标签换行,之后ggplot直接调用该列:

library(ggplot2)
library(stringr)

# 新增处理后的标签列,同时按Percent降序设置因子水平
perc_responses_1$wrapped_options <- factor(
  stringr::str_wrap(perc_responses_1$Options, 20),
  levels = stringr::str_wrap(reorder(perc_responses_1$Options, -perc_responses_1$Percent), 20)
)

# 绘图
ggplot(perc_responses_1, aes(x = wrapped_options, Percent)) +
  geom_bar(stat = "identity") + 
  coord_flip()+
  scale_y_continuous(labels = scales::percent, limits = c(0, .7))+
  labs(x = "Options") + 
  theme_bw()

这两种方法都能同时实现条形按数值降序排列和长标签自动换行的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 11:47:26