首页 > 解决方案 > 绘图时实例不匹配

问题描述

我正在尝试使用 seaborn 进行绘图

 data=pd.read_csv('MyCSV')
 data['Date']= pd.to_datetime(data['Date'])
 start_date ='2016-04-18'
 end_date ='2016-04-21'

 fig, ax = plt.subplots(figsize=(16,9))

 ax.plot(data.loc[start_date:end_date,'Date'].index, data.loc[start_date:end_date,"Price"], label='Price')


 ax.legend(loc='best')
 ax.set_ylabel('Price in $')
 ax.xaxis.set_major_formatter(my_year_month_fmt)
 plt.show()

TypeError: '<' not supported between instances of 'int' and 'datetime.datetime'

但是,如果我将线路更改为

 ax.plot(data['Date'].index, data["Price"], label='Price')

我的图表显示了,但我的日期搞砸了。他们都从1970-01-01

我的数据框看起来像这样

   Date       Price   
0 2016-04-18  24.992023  
1 2016-04-19  24.859484  
2 2016-04-20  24.910643  
3 2016-04-21  24.640911 

标签: pythonpandasmatplotlib

解决方案


data['Date']= pd.to_datetime(data['Date'])
data = data.set_index('Date')

start_date =datetime.strptime('2016-04-18', '%Y-%m-%d')
end_date =datetime.strptime('2016-04-21', '%Y-%m-%d')

fig, ax = plt.subplots(figsize=(16,9))

ax.plot(data.loc[start_date:end_date].index, data.loc[start_date:end_date, "Price"], label='Price')
ax.legend(loc='best')
ax.set_ylabel('Price in $')
plt.show()

注意:ax.plot(data.loc[start_date:end_date, "Price"], label='Price')也可以

在此处输入图像描述


推荐阅读