python - 绘图时实例不匹配
问题描述
我正在尝试使用 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
解决方案
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')
也可以
推荐阅读
- python - 盈透证券 - 未找到请求的安全定义
- amazon-web-services - 从 Secrets Manager 映射 AWS API Gateway HTTPIntegration 标头
- qt - 分配给已经在 QML 中定义的绑定的属性是否合法
- python-3.x - Python从简单图像中提取数字
- javascript - 如何在反应和提取数据中向制表器添加行
- angular - 全局图标库已弃用。FortAwesome/angular-fontawesome
- google-apps-script - 如何编写 Google 高级服务脚本
- javascript - JS 更改 ID 属性仅更改连续第一条记录上的 ID
- testing - 断言动态类 Tescafe 和 vue-virtual-scroll-list
- amazon-sns - 将 SSM 值转换为数字