简体   繁体   中英

Plotting time-series data from pandas results in ValueError

I'm using pandas DataFrame and matplotlib to draw three lines in the same figure. The data ought to be correct, but when I try to plot the lines, the code returns a ValueError , which is unexpected.

The detail error warning says: ValueError: view limit minimum -105920.979 is less than 1 and is an invalid Matplotlib date value . This often happens if you pass a non-datetime value to an axis that has datetime units

How to fix this error, and plot three lines in the same figure?

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)
  • I don't get an error running the code, though I have made a couple of adjustments to the import and the plot.
    • Update matplotlib and pandas .
    • If you're using Anaconda, at the Anaconda prompt, type conda update --all
  • Parse the 'Date' column to datetime and set it as the index.
  • Place the legend outside the plot
  • Set the yscale to 'log' , because the range of numbers is large.
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()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM