简体   繁体   English

Python Pandas - 不要在 y 轴值上对条形图进行排序

[英]Python Pandas - Don't sort bar graph on y axis values

I am beginner in Python.我是 Python 初学者。 I have a Series with Date and count of some observation as below我有一个带有日期的系列和一些观察的计数如下

Date      Count

2003        10

2005        50

2015        12

2004        12

2003        15

2008        10

2004        05

I wanted to plot a graph to find out the count against the year with a Bar graph (x axis as year and y axis being count) .我想用条形图(x 轴为年份,y 轴为计数)绘制图表以找出与年份相对的计数 I am using the below code我正在使用下面的代码

import pandas as pd

pd.value_counts(sfdf.Date_year).plot(kind='bar')

I am getting the bar graph which is automatically sorted on the count.我正在获取按计数自动排序的条形图。 So I am not able to clearly visualize how the count is distributed over the years.所以我无法清楚地想象这些年来计数是如何分布的。 Is there any way we can stop sorting the data on the bar graph on the count and instead sort on the x axis values (i,e year)?有什么方法可以停止对条形图上的数据进行计数排序,而是对 x 轴值(即年份)进行排序?

The following code uses groupby() to join the multiple instances of the same year together, and then calls sum() on the groupby() object to sum it up.以下代码使用groupby()将同一年的多个实例连接在一起,然后对 groupby() 对象调用sum()进行求和。 By default groupby() pushes the grouped object to the dataframe index.默认情况下groupby()将分组的对象推送到数据帧索引。 I think that groupby() automatically sorts, but just in case, sort(axis=0) will sort the index.我认为groupby()自动排序,但以防万一, sort(axis=0)会对索引进行排序。 All that then remains is to plot.然后剩下的就是绘图。 All in one line:全部在一行中:

df = pd.DataFrame([[2003,10],[2005,50],[2015,12],[2004,12],[2003,15],[2008,10],[2004,5]],columns=['Date','Count'])
df.groupby('Date').sum().sort(axis=0).plot(kind='bar')

I know this is an old question, but in case someone is still looking for another answer.我知道这是一个老问题,但以防万一有人仍在寻找另一个答案。

I solved this by adding .sort_index(axis=0)我通过添加.sort_index(axis=0)解决了这个问题

So, instead of this:所以,而不是这个:

pd.value_counts(sfdf.Date_year).plot(kind='bar')

you can write this:你可以这样写:

pd.value_counts(sfdf.Date_year).sort_index(axis=0).plot(kind='bar')

Hope, this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM