matplotlib错误:AttributeError:'int'对象没有属性'toordinal'

时间:2019-07-30 16:07:43

标签: python-3.x pandas matplotlib

我正在尝试使用matplotlib绘制图形。 我正在使用how to plot candlesticks in python

中的代码

代码是:

from pandas_datareader import data
import matplotlib.pyplot as plt
from mpl_finance import candlestick2_ohlc
import matplotlib.dates as mdates
import fix_yahoo_finance as yf
import datetime

start = datetime.date(2018, 1, 1)
end = datetime.date.today()

aapl = yf.download("AAPL",start,end) 
aapl.reset_index(inplace=True)

aapl['Date'] = aapl.index.map(mdates.date2num)

fig, ax = plt.subplots()
plt.xlabel("Date")
plt.ylabel("Price")

candlestick2_ohlc(ax, aapl.Open, aapl.High, aapl.Low, aapl.Close, width=1, colorup='g')
plt.savefig('my_figure.png')
plt.show() 

当我在google colab中运行此代码时,出现此错误:

AttributeError                            Traceback (most recent call last)
    <ipython-input-21-521826b3b41d> in <module>()
         16 
         17 
    ---> 18 aapl['Date'] = aapl.index.map(mdates.date2num)
         19 
         20 

3 frames
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()

/usr/local/lib/python3.6/dist-packages/matplotlib/dates.py in _to_ordinalf(dt)
    226         tzi = UTC
    227 
--> 228     base = float(dt.toordinal())
    229 
    230     # If it's sufficiently datetime-like, it will have a `date()` method

AttributeError: 'int' object has no attribute 'toordinal'

引起问题的代码行是这样的: aapl['Date'] = aapl.index.map(mdates.date2num)

当我将此行更改为:aapl['Date'] = mdates.date2num时,整个代码可以正常工作。

我正在使用:

matplotlib:3.0.3 熊猫:0.24.2

有人可以告诉我为什么先前的代码不起作用吗? 任何帮助将不胜感激。

0 个答案:

没有答案