使用matplotlib条形图设置列的顺序

4
我使用以下代码生成一个条形图:
Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CON'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index')
df.plot(kind = 'bar')

它生成以下条形图:

enter image description here

我想改变列的顺序。我尝试了几种不起作用的方法。我正在使用的数据框长这样:

enter image description here

我正在创建一个条形图,显示图片中数据框的最后一列。如果有任何指导或其他方法可以创建一个允许我更改轴顺序的条形图,将不胜感激。目前的图表很难解释。

2个回答

4

我认为你可以使用 value_countssort_index,最后使用 Series.plot.bar 生成条形图:

weatherDFConcat['TEMPBIN_CON'].value_counts().sort_index().plot.bar()

或者如果你想使用你自己的解决方案:

Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CON'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index').sort_index()
df.plot(kind = 'bar')

样例:

import matplotlib.pyplot as plt

weatherDFConcat = pd.DataFrame({'TEMPBIN_CON':['30 degrees or more', '-15 to -18 degrees', '-3 to 0 degrees', '15 to 18 degrees', '-15 to -18 degrees'
]})
print (weatherDFConcat)
          TEMPBIN_CON
0  30 degrees or more
1  -15 to -18 degrees
2     -3 to 0 degrees
3    15 to 18 degrees
4  -15 to -18 degrees

weatherDFConcat['TEMPBIN_CON'].value_counts().sort_index().plot.bar()
plt.show()

它是如何工作的?还是您需要一些定制排序? - jezrael
在我的数据上加入 .sort_index() 很好用 - 谢谢! - Justin

2
我建议将TEMPBIN_CON拆分为两个: LOWER_TEMPHIGHER_TEMP。然后,您可以使用以下方式按这些列对DataFrame进行排序:
sorted = df.sort_values(by=['LOWER_TEMP', 'HIGHER_TEMP'])

然后您按照之前的方式进行绘图:

sorted.plot(kind='bar')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接