首页 > 解决方案 > 带有最近日期的条形图,其中日期是日期时间索引

问题描述

我尝试按日期时间索引对数据框进行排序,然后绘制图表,但仍然没有任何变化,它显示了 2017 年、2018 年等最新日期在右侧,2008 年、2009 年在左侧。

在此处输入图像描述

我希望最近的一年从左到右。这是之前的数据框。

            Title  
Date                      
2001-01-01      0       
2002-01-01      9        
2003-01-01     11       
2004-01-01     17       
2005-01-01     23       
2006-01-01     25       
2007-01-01     51       
2008-01-01     55       
2009-01-01    120      
2010-01-01    101     
2011-01-01     95       
2012-01-01    118      
2013-01-01     75       
2014-01-01     75       
2015-01-01     3      
2016-01-01     35       
2017-01-01     75       
2018-01-01     55

忽略值。然后我按索引对上面的数据框进行排序,然后绘图但绘图仍然没有变化

df.sort_index(ascending=False, inplace=True)

标签: pythonpandasmatplotlibbar-chartdatetimeindex

解决方案


我猜您没有将索引更改为年份。这就是它不起作用的原因。您可以通过以下方式执行此操作:

df.index = pd.to_datetime(df.Date).dt.year
#then sort index in descending order
df.sort_index(ascending = False , inplace = True)
df.plot.bar()

推荐阅读