【问题标题】:Custom sorting of categorical variable on x-axis using matplotlib使用 matplotlib 在 x 轴上对分类变量进行自定义排序
【发布时间】:2018-05-26 13:00:15
【问题描述】:

我想将 x 轴上的月份按我指定的顺序排列。我已经广泛搜索,学习如何做到这一点,但没有运气。我非常熟悉 R 语言,我会在 R 中使用factor class 和它的级别很容易地做到这一点。但我对 python 比较陌生,我从阅读中了解到,python 中的 Categorical dtype 最接近 R 中的 factor。但是,这两种语言中的这些类似乎存在主要的行为差异。使用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)

已解决

可能是 matplotlib 的版本出错。在阅读this post 后,我将版本更新为 2.2.2,一切都按预期工作(即,轴按设置类别时提供的顺序排序。另外,我使用下面的代码设置类别,

TestData['Month'] = pd.Categorical(TestData['Month'], categories = MonthLabels , ordered = True)

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    这可能会有所帮助;来自documentation

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

    【讨论】:

    • 试过了,但没有用。我将更改代码以反映这一点
    猜你喜欢
    • 2021-08-13
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2022-08-18
    • 1970-01-01
    相关资源
    最近更新 更多