python - 如何防止使用 matplotlib 对 python 条进行字母排序?

标签 python python-3.x matplotlib

我正在使用条形图绘制一些分类数据。即使我对数据框值进行排序,Matplotlib 仍会按字母顺序对 x 轴进行排序。 这是我的代码:

fig3, new_ax = plt.subplots(1,1, figsize=(25/3,5))
summary = tsa.source.sum().sort_values(ascending=False)
new_ax.bar(summary.index, summary.values, color=my_colors)
new_ax.legend()
bar_heights(new_ax) # custom function to get the values on top of bars
simpleaxis(new_ax) # custom function to define an axis to please my boss...
new_ax.set_ylabel('Effectifs')
new_ax.set_xlabel("Type d'arme")
new_ax.grid(False)

输出: enter image description here

但这是摘要的样子,这就是我希望在图表上看到的顺序:

famas            2214.0
aut_typebruit     759.0
grena             200.0
flg                78.0
douze              72.0
sept               53.0
dtype: float64

这是我的数据样本的链接: https://files.fm/u/wumscb4q 用这一行导入它:

tsa.source = pd.read_csv('sample.csv', sep=';', index_col=0)

这里是我的功能:

def simpleaxis(ax):
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

def bar_heights(axes):
    for rect in axes.containers[0]:
        height = rect.get_height()
        rect.axes.text(rect.get_x() + rect.get_width()/2., height+3,
            '%d' % int(height),
            ha='center', va='bottom')

最佳答案

问题

这是 a bug在 matplotlib < 2.2.0 中,即使值是字符串,也始终对 X 轴进行排序。这就是下图中条形顺序颠倒的原因。

x = ['foo', 'bar']
y = [1, 2]
plt.bar(x, y, color=['b', 'g'])

enter image description here

修复

将 matplotlib 升级到 2.2.0 或更高版本。对于这些版本,相同的代码会产生预期的结果。

enter image description here

解决方法

如果您不能或不想升级 matplotlib,您可以使用数字而不是字符串,然后将刻度和标签设置为正确的值:

index = range(len(x))
plt.bar(x, y, color=['b', 'g'])  # use numbers in the X axis.
plt.xticks(index, x)  # set the X ticks and labels

enter image description here

Pandas 之道

您可以使用 Series.plot,这对您来说可能很方便,因为您的数据已经采用 Series 的形式,但请注意 pandas 以不同的方式绘制内容。使用关键字参数 rot 来控制标签的旋转。

s = pd.Series(y, index=x)
s.plot(kind='bar',rot=0, color=['b', 'g'])

enter image description here

关于python - 如何防止使用 matplotlib 对 python 条进行字母排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49647875/

相关文章:

赋值运算符左侧的Python多个变量

python - 在列表中迭代字典

python - "import matplotlib.pyplot as plt"时出错

python - 使用 matplotlib Python 绘制参数图

python 3 : CSV utf-8 encoding

python - 如何根据numpy中的条件拆分数组?

python - 在不使用 str() 的情况下将类对象用作字符串

python - Matplotlib 热图标签

python - 文件路径上的正则表达式用于匹配不以某些单词开头的文件名

python - kwargs 的自定义异常 (Python)