【问题标题】:Instance mismatch while plotting绘图时实例不匹配
【发布时间】:2021-04-26 06:21:30
【问题描述】:

我正在尝试使用 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 

【问题讨论】:

  • 你使用的是最新的matplotlib和pandas版本吗?

标签: python pandas matplotlib


【解决方案1】:
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') 也可以使用

【讨论】:

  • 嗨@Rohit你能复制粘贴完整的错误吗
  • TypeError: '<' not supported between instances of 'int' and 'datetime.datetime'
  • 我已经用我得到的图表更新了答案,请随意使用确切的代码来生成图表,看看它是否抛出任何错误
  • 你能用 data.info() 的结果更新你的代码吗
猜你喜欢
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 2012-07-07
  • 1970-01-01
相关资源
最近更新 更多