簡體   English   中英

繪制來自熊貓的時間序列數據會導致 ValueError

[英]Plotting time-series data from pandas results in ValueError

我正在使用pandas DataFrame 和matplotlib在同一圖中繪制三條線。 數據應該是正確的,但是當我嘗試繪制線條時,代碼返回一個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)
  • 盡管我對導入和繪圖進行了一些調整,但運行代碼沒有出現錯誤。
    • 更新matplotlibpandas
    • 如果您使用的是 Anaconda,請在 Anaconda 提示符下鍵入conda update --all
  • 'Date'列解析為'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()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM