使用 matplotlib 在 x 轴上自定义分类变量排序

M_S*_*mal 5 python matplotlib

我想按照我指定的顺序对 x 轴上的月份进行排序。我在谷歌上进行了广泛的搜索,以了解如何做到这一点,但没有运气。我对 R 语言非常熟悉,我会在 R 使用factor class和它的级别中很容易地做到这一点。但是我对 python 比较陌生,我从阅读中学到的是Categorical dtypepython 中最接近factorR。但是,这两种语言中的这些类似乎存在主要的行为差异。使用绘制时没有分类顺序的排序,pyplot.bar()但在seaborn条形图中正确排序了相同的图。

pyplot.bar() 的数据框中是否有自定义排序分类变量的选项?

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']})

# Applying custom categorical order
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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明 在此处输入图片说明

解决了

可能是 matplotlib 版本的错误。阅读这篇文章后,我将版本更新为 2.2.2 ,一切都按预期工作(即,轴按照设置类别时提供的顺序进行排序。我还使用下面的代码设置类别,

TestData['Month'] = pd.Categorical(TestData['Month'], categories = MonthLabels , ordered = True)
Run Code Online (Sandbox Code Playgroud)

edu*_*ffy 1

这可能会有所帮助;从文档中:

注意新分类数据不会自动排序。您必须显式传递ordered=True以指示有序Categorical.