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

时间:2016-08-25 01:45:53

标签: python pandas numpy matplotlib bar-chart

我使用以下代码生成条形图:

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

它产生以下条形图:

enter image description here

我想更改列的列顺序。我尝试了一些看似不起作用的不同的东西。我正在使用的DataFrame看起来像这样:

enter image description here

我正在创建图中数据框中最后一列的条形图。创建条形图的替代方法的任何方向或想法将允许我改变轴的顺序将是非常感激的。因为它存在很难解释。

2 个答案:

答案 0 :(得分:3)

我认为您可以将value_countssort_indexSeries.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()

答案 1 :(得分:1)

我建议您将TEMPBIN_CON分成两部分:LOWER_TEMPHIGHER_TEMP。然后,使用以下方法按这些列对DataFrame进行排序:

sorted = df.sort_values(by=['LOWER_TEMP', 'HIGHER_TEMP'])

然后你就像你已经完成的那样绘制情节:

sorted.plot(kind='bar')