python - 绘制来自 pandas 的时间序列数据会导致 ValueError
问题描述
我正在使用pandas
DataFrame 并matplotlib
在同一个图中绘制三条线。数据应该是正确的,但是当我尝试绘制线条时,代码返回 a ValueError
,这是出乎意料的。
详细错误警告说:ValueError: view limit minimum -105920.979 is less than 1 and is an invalid Matplotlib date value
。如果您将非日期时间值传递给具有日期时间单位的轴,这通常会发生
如何解决此错误,并在同一图中绘制三行?
import pandas as pd
import datetime as dt
import pandas_datareader as web
import matplotlib.pyplot as plt
from matplotlib import style
import matplotlib.ticker as ticker
spot=pd.read_excel('https://www.eia.gov/dnav/pet/hist_xls/RWTCd.xls',sheet_name='Data 1',skiprows=2) #this is spot price data
prod=pd.read_excel('https://www.eia.gov/dnav/pet/hist_xls/WCRFPUS2w.xls',sheet_name='Data 1',skiprows=2) #this is production data
stkp=pd.read_excel('https://www.eia.gov/dnav/pet/hist_xls/WTTSTUS1w.xls',sheet_name='Data 1',skiprows=2) #this is stockpile data
fig,ax = plt.subplots()
ax.plot(spot,label='WTI Crude Oil Price')
ax.plot(prod,label='US Crude Oil Production')
ax.plot(stkp,label='US Crude Oil Stockpile')
plt.legend()
plt.show()
print(spot,prod,stkp)
解决方案
- 尽管我对导入和绘图进行了一些调整,但运行代码时没有出现错误。
- 更新
matplotlib
和pandas
. - 如果您使用的是 Anaconda,请在 Anaconda 提示符下键入
conda update --all
- 更新
- 将该列解析
'Date'
为日期时间并将其设置为索引。 - 将图例放在情节之外
- 设置
yscale
为'log'
,因为数字的范围很大。
import pandas as pd
import matplotlib.pyplot as plt
spot=pd.read_excel('https://www.eia.gov/dnav/pet/hist_xls/RWTCd.xls', sheet_name='Data 1',skiprows=2, parse_dates=['Date'], index_col='Date') #this is spot price data
prod=pd.read_excel('https://www.eia.gov/dnav/pet/hist_xls/WCRFPUS2w.xls', sheet_name='Data 1',skiprows=2, parse_dates=['Date'], index_col='Date') #this is production data
stkp=pd.read_excel('https://www.eia.gov/dnav/pet/hist_xls/WTTSTUS1w.xls', sheet_name='Data 1',skiprows=2, parse_dates=['Date'], index_col='Date') #this is stockpile data
fig,ax = plt.subplots()
ax.plot(spot, label='WTI Crude Oil Price')
ax.plot(prod, label='US Crude Oil Production')
ax.plot(stkp, label='US Crude Oil Stockpile')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.yscale('log')
plt.show()
推荐阅读
- python - 如何使用 glumpy 放大/缩小 3D 图像?
- jquery - 仅当从下拉列表中选择选项时才附加到 iframe src
- c# - 在 c# 中使用具有父类型的子构造函数时会发生什么?父 x = new Child();
- java - 对象未从 ListView 中删除
- git - 如何将文件“广播”到 git 中的所有分支?
- snapcraft - 如何添加来自不同限制的舞台快照?
- google-visualization - pieSliceText 在谷歌图表中的位置
- javascript - Yup.string().matches() 在您输入时在有效和无效之间交替
- php - Apache GZip 无法使用文本文件和 js 文件?
- scala - 会话的值在会话之间复制