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

R语言中基于整数列排序字符串列并修复ggplot绘图排序异常

解决ggplot柱状图x轴排序问题的思路
  • 核心原因:ggplot默认会按字符串的字典序对the_bin列排序,而非你指定的the_bin_num整数顺序,所以需要手动指定排序规则。

方法一:将the_bin转换为有序因子(推荐)

先在数据预处理阶段把the_bin转为有序因子,用the_bin_num来定义因子水平的顺序,这样ggplot会直接遵循这个顺序绘图:

# 先按the_bin_num排序数据,再把the_bin设为有序因子
data_by_time2 <- data_by_time2 %>%
  arrange(the_bin_num) %>%
  mutate(the_bin = factor(the_bin, levels = unique(the_bin), ordered = TRUE))

# 再用原代码绘图即可
ggplot(data = data_by_time2,aes(x=the_bin,y=avg,fill =avg))+
  geom_bar(stat = "identity",position = "dodge")+
  labs(title = "Average Profit According To The Running Time Of The Movie",x="Run Time",y="Mean Trim Profit",color="Mean Trim Profit",fill="Mean Trim")+
  facet_grid(.~genres)+
  theme(axis.text.x = element_text(angle = 90,vjust = 0.5 ,hjust = 1))

方法二:直接在ggplot的aes中重排x轴

如果不想修改原始数据框,可以用reorder()函数在绘图时指定the_bin的排序依据为the_bin_num:

ggplot(data = data_by_time2,aes(x=reorder(the_bin, the_bin_num),y=avg,fill =avg))+
  geom_bar(stat = "identity",position = "dodge")+
  labs(title = "Average Profit According To The Running Time Of The Movie",x="Run Time",y="Mean Trim Profit",color="Mean Trim Profit",fill="Mean Trim")+
  facet_grid(.~genres)+
  theme(axis.text.x = element_text(angle = 90,vjust = 0.5 ,hjust = 1))

注意:如果同一个the_bin对应多个the_bin_num,reorder()会默认取the_bin_num的均值来排序,确保你的数据中每个the_bin对应唯一的the_bin_num即可避免问题。

验证步骤

可以先检查the_bin和the_bin_num的对应关系,确保排序逻辑正确:

# 查看每个the_bin对应的the_bin_num值
table(data_by_time2$the_bin, data_by_time2$the_bin_num)

内容的提问来源于stack exchange,提问作者נדב ברזי

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:04:53