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

如何重新排序柱状图?需将>£30置于末尾

解决方法

要把>£30放到图表末尾,你可以通过手动指定因子水平顺序,或者用forcats包的fct_relevel函数来实现,具体两种方案如下:

方案一:手动指定因子水平

直接将monthly_spending转换为因子,并按你想要的顺序列出所有水平,把>£30放在最后即可。假设你的monthly_spending其他类别是£0-£10、£10-£20、£20-£30,代码修改如下:

female_data%>%
  group_by(monthly_spending, Age)%>%
  summarise(Number=n())%>%
  mutate("Percentage"=Number/112*100,
         # 手动指定因子水平顺序
         monthly_spending = factor(monthly_spending, 
                                   levels = c("£0-£10", "£10-£20", "£20-£30", ">£30")))%>%
  ggplot() + geom_col(aes(x=monthly_spending, y=Percentage, fill=Age))

如果monthly_spending原本是有序因子,先转成普通因子再调整:factor(monthly_spending, ordered = FALSE),之后再按上面的方式指定水平。

方案二:用forcats包的fct_relevel函数

这个方法更灵活,不用列全所有水平,直接把>£30移到最后。需要先安装并加载forcats包:

# 先安装包(首次使用时)
install.packages("forcats")
library(forcats)

female_data%>%
  group_by(monthly_spending, Age)%>%
  summarise(Number=n())%>%
  mutate("Percentage"=Number/112*100,
         # 将>£30移到所有水平的最后
         monthly_spending = fct_relevel(monthly_spending, ">£30", after = Inf))%>%
  ggplot() + geom_col(aes(x=monthly_spending, y=Percentage, fill=Age))

after = Inf表示把目标水平放到最后,不管原来的顺序是什么。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:12:46