FigureCanvasAgg'对象没有属性'invalidate'吗? python绘图 [英] FigureCanvasAgg' object has no attribute 'invalidate' ? python plotting

查看:181
本文介绍了FigureCanvasAgg'对象没有属性'invalidate'吗? python绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在关注用于数据分析的python".在pg. 345,您将获得此代码以绘制各种股票的收益.但是,绘图功能对我不起作用.我懂了 FigureCanvasAgg'对象没有属性'invalidate'吗?

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' ?

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()

更新:完全追溯

---------------------------------------------------------------------------
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'

推荐答案

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

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

  • 通过系列或数据框成员方法使用熊猫图
  • 使用日期索引进行绘图
  • 在ipython中使用%matplotlib inline魔术
  • using pandas plotting with a series or dataframe member method
  • plotting with a date index
  • using %matplotlib inline magic in ipython
  • importing the pylab module before the matplotlib magic

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

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

# 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()

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

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

这篇关于FigureCanvasAgg'对象没有属性'invalidate'吗? python绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆