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

如何在Matplotlib中自定义X轴分类变量的排序?

如何在matplotlib.pyplot.bar()中自定义DataFrame分类变量的排序?

问题背景

我熟悉R语言,能通过factor类及其levels轻松实现X轴月份的自定义排序,但刚接触Python时遇到了麻烦:我知道pandas的Categorical dtype和R的factor最接近,但用pyplot.bar()绘图时,分类并没有按我设置的自定义顺序排列,而seaborn的条形图却能正常排序。使用的版本如下:

  • pandas = 0.22.0
  • matplotlib = 2.1.2
  • seaborn = 0.8.1

测试代码如下:

import pandas as pd
import matplotlib.pyplot as plt
from pandas.api.types import CategoricalDtype
TestData = pd.DataFrame({'value':[1,2,5,3,5,6,8,9,8,1,2,8,9],'Month':['Jan','Mar','Jan','Feb','May','Apr','Jan','Mar','Jan','Feb','May','Apr','May']})
# 应用自定义分类顺序
MonthLabels = ['Jan','Feb','Mar','Apr','May']
M_catType = CategoricalDtype(categories = MonthLabels, ordered = True)
TestData['Month'] = TestData['Month'].astype(M_catType)
plt.bar('Month','value', data=TestData)

已验证的解决方案

我已经解决了这个问题,核心要点有两个:

  1. 版本兼容性问题:将matplotlib版本更新至2.2.2后,plt.bar()就能正确识别pandas分类变量的自定义顺序了,X轴会严格按照你设置的MonthLabels顺序排列。
  2. 简化分类变量设置:你可以直接使用pd.Categorical()来定义分类,不需要额外导入CategoricalDtype,代码更简洁:
TestData['Month'] = pd.Categorical(TestData['Month'], categories = MonthLabels , ordered = True)

修改后再运行plt.bar('Month','value', data=TestData),X轴的月份就会按照Jan→Feb→Mar→Apr→May的自定义顺序正常显示了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:58:28