Python 使用matplotlib条形图设置列的顺序
我用以下代码生成一个条形图:Python 使用matplotlib条形图设置列的顺序,python,pandas,numpy,matplotlib,bar-chart,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') 它生成以下条形图: 我想更改列的列出顺序。我尝试了一些似乎不起作用的不同方法。我正在使用的数据帧如下所示: 我正在创建图中数据框中最后一列的条形图。我非常感谢任何关于创建条形图的替代方法的方向或
Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CON'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index')
df.plot(kind = 'bar')
它生成以下条形图:
我想更改列的列出顺序。我尝试了一些似乎不起作用的不同方法。我正在使用的数据帧如下所示:
我正在创建图中数据框中最后一列的条形图。我非常感谢任何关于创建条形图的替代方法的方向或想法,以允许我更改轴的顺序。由于它的存在,很难解释 我建议您将
TEMPBIN\u CON
分为两部分:LOWER\u TEMP
和HIGHER\u TEMP
。然后,使用以下命令按这些列对数据帧进行排序:
sorted = df.sort_values(by=['LOWER_TEMP', 'HIGHER_TEMP'])
然后,按照已经完成的步骤进行绘图:
sorted.plot(kind='bar')
我认为您可以使用with和last:
或者,如果您想使用您的解决方案:
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()
它是如何工作的?或者您需要一些自定义排序吗?添加.sort_index()对我的数据很有效-谢谢!
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()