首页 > 解决方案 > 绘制来自 pandas 的时间序列数据会导致 ValueError

问题描述

我正在使用pandasDataFrame 并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)

标签: pythonpandasmatplotlib

解决方案


  • 尽管我对导入和绘图进行了一些调整,但运行代码时没有出现错误。
    • 更新matplotlibpandas.
    • 如果您使用的是 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()

在此处输入图像描述


推荐阅读