pandas FigureCanvasAgg' 对象没有属性 'invalidate' ?蟒蛇绘图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23550056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:01:42  来源:igfitidea点击:

FigureCanvasAgg' object has no attribute 'invalidate' ? python plotting

pythonmatplotlibpandasfinancial

提问by user3314418

I've been following 'python for data analysis'. On pg. 345, you get to this code to plot returns across a variety of stocks. However, the plotting function does not work for me. I get FigureCanvasAgg' object has no attribute 'invalidate' ?

我一直在关注“用于数据分析的python”。在第。345,您可以使用此代码绘制各种股票的回报。但是,绘图功能对我不起作用。我得到 FigureCanvasAgg' 对象没有属性 'invalidate' ?

names = ['AAPL','MSFT', 'DELL', 'MS', 'BAC', 'C'] #goog and SF did not work
def get_px(stock, start, end):
    return web.get_data_yahoo(stock, start, end)['Adj Close']
px = pd.DataFrame({n: get_px(n, '1/1/2009', '6/1/2012') for n in names})

#fillna method pad uses last valid observation to fill
px = px.asfreq('B').fillna(method='pad')
rets = px.pct_change()
df2 = ((1 + rets).cumprod() - 1)

df2.ix[0] = 1

df2.plot()

UPDATE: full traceback

更新:完整回溯

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-122-df192c0432be> in <module>()
      6 df2.ix[0] = 1
      7 
----> 8 df2.plot()

//anaconda/lib/python2.7/site-packages/pandas/tools/plotting.pyc in plot_frame(frame, x, y, subplots, sharex, sharey, use_index, figsize, grid, legend, rot, ax, style, title, xlim, ylim, logx, logy, xticks, yticks, kind, sort_columns, fontsize, secondary_y, **kwds)
   1634                      logy=logy, sort_columns=sort_columns,
   1635                      secondary_y=secondary_y, **kwds)
-> 1636     plot_obj.generate()
   1637     plot_obj.draw()
   1638     if subplots:

//anaconda/lib/python2.7/site-packages/pandas/tools/plotting.pyc in generate(self)
    854         self._compute_plot_data()
    855         self._setup_subplots()
--> 856         self._make_plot()
    857         self._post_plot_logic()
    858         self._adorn_subplots()

//anaconda/lib/python2.7/site-packages/pandas/tools/plotting.pyc in _make_plot(self)
   1238         if not self.x_compat and self.use_index and self._use_dynamic_x():
   1239             data = self._maybe_convert_index(self.data)
-> 1240             self._make_ts_plot(data, **self.kwds)
   1241         else:
   1242             lines = []

//anaconda/lib/python2.7/site-packages/pandas/tools/plotting.pyc in _make_ts_plot(self, data, **kwargs)
   1319                 self._maybe_add_color(colors, kwds, style, i)
   1320 
-> 1321                 _plot(data[col], i, ax, label, style, **kwds)
   1322 
   1323         self._make_legend(lines, labels)

//anaconda/lib/python2.7/site-packages/pandas/tools/plotting.pyc in _plot(data, col_num, ax, label, style, **kwds)
   1293         def _plot(data, col_num, ax, label, style, **kwds):
   1294             newlines = tsplot(data, plotf, ax=ax, label=label,
-> 1295                                 style=style, **kwds)
   1296             ax.grid(self.grid)
   1297             lines.append(newlines[0])

//anaconda/lib/python2.7/site-packages/pandas/tseries/plotting.pyc in tsplot(series, plotf, **kwargs)
     79 
     80     # set date formatter, locators and rescale limits
---> 81     format_dateaxis(ax, ax.freq)
     82     left, right = _get_xlim(ax.get_lines())
     83     ax.set_xlim(left, right)

//anaconda/lib/python2.7/site-packages/pandas/tseries/plotting.pyc in format_dateaxis(subplot, freq)
    258     subplot.xaxis.set_major_formatter(majformatter)
    259     subplot.xaxis.set_minor_formatter(minformatter)
--> 260     pylab.draw_if_interactive()

//anaconda/lib/python2.7/site-packages/IPython/utils/decorators.pyc in wrapper(*args, **kw)
     41     def wrapper(*args,**kw):
     42         wrapper.called = False
---> 43         out = func(*args,**kw)
     44         wrapper.called = True
     45         return out

//anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.pyc in draw_if_interactive()
    227         figManager =  Gcf.get_active()
    228         if figManager is not None:
--> 229             figManager.canvas.invalidate()
    230 
    231 

AttributeError: 'FigureCanvasAgg' object has no attribute 'invalidate'

回答by Calvin

I found this error to be due to a combination of:

我发现此错误是由于以下原因造成的:

  • using pandas plotting with a series or dataframe member method
  • plotting with a date index
  • using %matplotlib inlinemagic in ipython
  • importing the pylab module beforethe matplotlib magic
  • 使用带有系列或数据框成员方法的Pandas绘图
  • 用日期索引绘图
  • %matplotlib inline在 ipython 中使用魔法
  • 在 matplotlib 魔法之前导入 pylab 模块

So the following will fail on a newly started kernelin an ipython notebook:

因此,在 ipython 笔记本中新启动的内核上,以下内容将失败:

# fails 
import matplotlib.pylab
%matplotlib inline

import pandas
ser = pandas.Series(range(10), pandas.date_range(end='2014-01-01', periods=10))
ser.plot()

The best way to solve this is to move the magic up to the top:

解决这个问题的最好方法是将魔法移到顶部:

# succeeds
%matplotlib inline # moved up
import matplotlib.pylab

import pandas
ser = pandas.Series(range(10), pandas.date_range(end='2014-01-01', periods=10))
ser.plot()

However the problem also goes away if you pass the series to a matplotlibplotting method, don't use a date index, or simply don't import the matplotlib.pylabmodule.

但是,如果您将系列传递给matplotlib绘图方法,不使用日期索引,或者只是不导入matplotlib.pylab模块,问题也会消失。

回答by Briford Wylie

Not an answer but I can't figure out how to put code block in comments :)

不是答案,但我不知道如何在评论中放置代码块 :)

So I got to this question because the exact same thing was happening on my Mac

所以我问了这个问题,因为我的 Mac 上发生了完全相同的事情

/Users/briford/myPVE/workbench/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.pyc in draw_if_interactive()
    227         figManager =  Gcf.get_active()
    228         if figManager is not None:
--> 229             figManager.canvas.invalidate()
    230 
AttributeError: 'FigureCanvasAgg' object has no attribute 'invalidate'

Anyway I know it's not satisfying but just doing a shutdown of my ipython notebook service and doing a restart cleared it up... shrug...

无论如何,我知道这并不令人满意,但只是关闭我的 ipython notebook 服务并重新启动它就可以了……耸耸肩……

回答by Jay

I seemed to resolve the issue (well at least in my case).

我似乎解决了这个问题(至少在我的情况下)。

I'm running IPython on a mac using python 2.7 and was getting the same error.

我在使用 python 2.7 的 mac 上运行 IPython 并遇到相同的错误。

It did seem to be an issue with the backend as when I looked at the "dock", quite a few instances of the Python Launcher had been opened (not sure why this happened in the first place though).

这似乎是后端的一个问题,因为当我查看“dock”时,已经打开了很多 Python Launcher 实例(虽然不确定为什么会发生这种情况)。

Forcing those to close caused the python kernel to restart and has seemed to have fixed my issue.

强制关闭会导致 python 内核重新启动,并且似乎已经解决了我的问题。

The inline codeis still in placeand plots are showing correctly.

行内代码仍然是在地方情节是否正确显示

回答by Sidrah

I resolved the issue by adding %matplotlib inlineon the first code cell of jupyter notebook and running it

我通过添加%matplotlib inlinejupyter notebook 的第一个代码单元并运行它来解决这个问题

回答by cefect

I have this error when I use a non-interactive backend (e.g. matplotlib.use('svg'))

当我使用非交互式后端时出现此错误(例如matplotlib.use('svg')

Fix for me was to change the backend (e.g. matplotlib.use('Qt5Agg'))

对我来说修复是更改后端(例如matplotlib.use('Qt5Agg')

回答by dmnd

The other answers didn't work for me. Instead my problem was because I was starting the notebook with ipython notebook --pylab. Once I dropped the --pylabthings worked again.

其他答案对我不起作用。相反,我的问题是因为我用ipython notebook --pylab. 一旦我放下--pylab东西,事情就又开始了。

So make sure you start ipython notebook with only ipython notebook.

因此,请确保您仅使用ipython notebook.

(There's actually a warning emitted when you use --pylabbut I missed it until now.)

(实际上在您使用时会发出警告,--pylab但直到现在我都错过了。)