Python 保留最近日期的条形图,其中日期为日期时间索引

Python 保留最近日期的条形图,其中日期为日期时间索引,python,pandas,matplotlib,bar-chart,datetimeindex,Python,Pandas,Matplotlib,Bar Chart,Datetimeindex,我尝试按日期时间索引对数据框进行排序,然后绘制图表,但没有任何变化,它仍然显示了最新日期,如2017年、2018年在右边,2008年、2009年在左边 我想让最近的一年从左往右。 这是之前的数据帧 Title Date 2001-01-01 0 2002-01-01 9 2003-01-01 11 2004-01-01 17 20

我尝试按日期时间索引对数据框进行排序,然后绘制图表,但没有任何变化,它仍然显示了最新日期,如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)
使用
invert_xaxis()

如果不想使用熊猫绘图,请执行以下操作:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
plt.bar(df.index, df['Title'])
ax.invert_xaxis() 

我想你没有把你的指数改到今年。这就是它不起作用的原因。您可以通过以下方式实现:

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()

您的数据结构可能存在的重复项不清楚,因为您尚未提供。您是如何从数据表到达发布的图片的仍然是一个谜-数字根本不匹配。所以这个问题也不清楚,为什么排序没有影响绘图。我使用ax绘图,所以下面的一个给出了错误,ax.bar(df1.index,df1['Title',width=100,zorder=3)。invertxaxis()
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()