我正在使用pandas
DataFrame和matplotlib
在同一图中绘制三条线。数据应该是正确的,但是当我尝试绘制线条时,代码返回了ValueError
,这是意外的。
详细错误警告说:ValueError: view limit minimum -105920.979 is less than 1 and is an invalid Matplotlib date value
。如果您将非datetime值传递给具有datetime单位的轴,通常会发生这种情况
如何解决此错误,并在同一图中绘制三行?
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)
答案 0 :(得分:2)
matplotlib
和pandas
。conda update --all
'Date'
列解析为datetime并将其设置为索引。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()