Matplotlib pyplot水平条形图 - 防止轴的自动排序

时间:2018-04-08 05:48:22

标签: python matplotlib

我想强制条形图使x轴按特定顺序排列。但出于某种原因,它总是按字母顺序排序,我不知道为什么。是否有一个设置我可以用来阻止它这样做。

在下面的示例中,我希望x轴的排序为['d', 'a', 'c', 'b']。但它始终将其命令为['a', 'b', 'c', 'd']

代码:

import pandas as pd
import matplotlib.pyplot as plt

ser = pd.Series([1,2,3,4], index=['d', 'a', 'c', 'b'])
fig = plt.bar(ser.index, ser.values, tick_label=ser.index)

截图:

enter image description here

1 个答案:

答案 0 :(得分:1)

plt.bar()将其第一个参数视为X坐标数组。考虑传递整数数组而不是字符数组:

plt.bar(range(ser.shape[0]), ser.values, tick_label=ser.index)

enter image description here

相关问题