pandas 使用 matplotlib 条形图设置列的顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39135472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting Order of Columns with matplotlib bar chart
提问by Justin
I produce a bar graph with the following code:
我使用以下代码生成条形图:
Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CON'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index')
df.plot(kind = 'bar')
It produces the following bar chart:
它生成以下条形图:
I would like to change the order the columns are listed. I've tried a few different things that aren't seeming to work. The DataFrame I am working with looks like this:
我想更改列的列出顺序。我尝试了一些似乎不起作用的不同方法。我正在使用的 DataFrame 如下所示:
I am creating a barplot of the last column in the dataframe pictured. Any direction or ideas of alternate methods of creating a barplot that would allow me to change the order of the axis would be greatly appreciated. As it exists its difficult to interpret.
我正在创建图中数据框中最后一列的条形图。任何创建条形图的替代方法的方向或想法都将允许我更改轴的顺序,将不胜感激。因为它存在,所以很难解释。
采纳答案by jezrael
I think you can use value_counts
with sort_index
and last Series.plot.bar
:
我认为你可以使用value_counts
withsort_index
和 last Series.plot.bar
:
weatherDFConcat['TEMPBIN_CON'].value_counts().sort_index().plot.bar()
Or if you want use your solution:
或者,如果您想使用您的解决方案:
Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CON'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index').sort_index()
df.plot(kind = 'bar')
Sample:
样本:
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()
回答by gabra
I would suggest that you split the TEMPBIN_CON
in two: LOWER_TEMP
and HIGHER_TEMP
. Then, you sort the DataFrame by these columns using:
我建议您将其一分为TEMPBIN_CON
二:LOWER_TEMP
和HIGHER_TEMP
。然后,您可以使用以下方法按这些列对 DataFrame 进行排序:
sorted = df.sort_values(by=['LOWER_TEMP', 'HIGHER_TEMP'])
and then you do the plot as you have already done:
然后你像你已经做的那样做情节:
sorted.plot(kind='bar')