2015-04-04 93 views
2

我正在通過「Python For Data Analysis」中的一些示例來工作,並且試圖使用以下內嵌腳本IPython的筆記本:在IPython筆記本中的Matplotlib「ValueError:寬度和高度都必須低於32768」

%matplotlib 
%pdb 
from datetime import datetime 
import pandas as pd 
import matplotlib.pyplot as plt 

fig = plt.figure() 
ax = fig.add_subplot(1,1,1) 

data = pd.read_csv("ch08/spx.csv", index_col=0, parse_dates=True) 
spx = data['SPX'] 
ax.plot(spx, 'k-') 

crisis_data = [ 
    (datetime(2007, 10, 11), 'Peak of bull market'), 
    (datetime(2008, 3, 12), 'Bear Stearns Fails'), 
    (datetime(2008, 9, 15), 'Lehman Bankruptcy') 
] 

for date, label in crisis_data: 
    ax.annotate(label, 
       xy=(date, spx.asof(date) + 50), 
       xytext=(date, spx.asof(date) + 200), 
       arrowprops=dict(facecolor='black'), 
       horizontalalignment='left', 
       verticalalignment='top') 

ax.set_title('Important dates in 2008-2009 financial crisis') 
fig 

凡spx.csv具有約5500行數據看起來像這樣:

,SPX 
1990-02-01 00:00:00,328.79 
1990-02-02 00:00:00,330.92 
1990-02-05 00:00:00,331.85 
1990-02-06 00:00:00,329.66 
1990-02-07 00:00:00,333.75 
1990-02-08 00:00:00,332.96 
1990-02-09 00:00:00,333.62 
1990-02-12 00:00:00,330.08 
1990-02-13 00:00:00,331.02 
1990-02-14 00:00:00,332.01 
1990-02-15 00:00:00,334.89 
1990-02-16 00:00:00,332.72 
1990-02-20 00:00:00,327.99 
1990-02-21 00:00:00,327.67 
1990-02-22 00:00:00,325.7 
1990-02-23 00:00:00,324.15 
1990-02-26 00:00:00,328.67 
1990-02-27 00:00:00,330.26 
1990-02-28 00:00:00,331.89 
1990-03-01 00:00:00,332.74 

ax.plot(spec, 'k-')不發放部分地塊,但是當我嘗試在循環後再次情節和設置標題後,我得到了以下內容摹錯誤:

Using matplotlib backend: MacOSX 
Automatic pdb calling has been turned OFF 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
/Users/B/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/core/formatters.pyc in __call__(self, obj) 
    333     pass 
    334    else: 
--> 335     return printer(obj) 
    336    # Finally look for special method names 
    337    method = _safe_get_formatter_method(obj, self.print_method) 

/Users/B/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in <lambda>(fig) 
    205 
    206  if 'png' in formats: 
--> 207   png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs)) 
    208  if 'retina' in formats or 'png2x' in formats: 
    209   png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs)) 

/Users/B/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in print_figure(fig, fmt, bbox_inches, **kwargs) 
    115 
    116  bytes_io = BytesIO() 
--> 117  fig.canvas.print_figure(bytes_io, **kw) 
    118  data = bytes_io.getvalue() 
    119  if fmt == 'svg': 

/Users/B/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs) 
    2192     orientation=orientation, 
    2193     bbox_inches_restore=_bbox_inches_restore, 
-> 2194     **kwargs) 
    2195   finally: 
    2196    if bbox_inches and restore_bbox: 

/Users/B/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs) 
    519 
    520  def print_png(self, filename_or_obj, *args, **kwargs): 
--> 521   FigureCanvasAgg.draw(self) 
    522   renderer = self.get_renderer() 
    523   original_dpi = renderer.dpi 

/Users/B/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in draw(self) 
    462   if __debug__: verbose.report('FigureCanvasAgg.draw', 'debug-annoying') 
    463 
--> 464   self.renderer = self.get_renderer(cleared=True) 
    465   # acquire a lock on the shared font cache 
    466   RendererAgg.lock.acquire() 

/Users/B/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in get_renderer(self, cleared) 
    479 
    480   if need_new_renderer: 
--> 481    self.renderer = RendererAgg(w, h, self.figure.dpi) 
    482    self._lastKey = key 
    483   elif cleared: 

/Users/B/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in __init__(self, width, height, dpi) 
    92   self.height = height 
    93   if __debug__: verbose.report('RendererAgg.__init__ width=%s, height=%s'%(width, height), 'debug-annoying') 
---> 94   self._renderer = _RendererAgg(int(width), int(height), dpi, debug=False) 
    95   self._filter_renderers = [] 
    96 

ValueError: width and height must each be below 32768 

調試,它看起來像的width值733431.53993055562出於某種原因。我嘗試通過figsize=(3,4)set_size_inches啓動數字來手動設置圖形寬度,但結果相同。

我也發現了同樣的問題的這種老的bug報告,但它似乎從來沒有得到解決:https://github.com/ipython/ipython/issues/1740

不知道如何解決這個問題?

+0

按照您發佈的問題,你可以嘗試調用'%配置InlineBackend.print_figure_kwargs = {'bbox_inches':None}'在'%matplotlib inline'調用之後? – Jakob 2015-04-08 14:33:11

回答

0

我在Sage中遇到了類似的問題,由於我的x^5函數,我無意中將其繪製在32K以上。演示比描述更容易。

go() is essentially plot()

如果您複製並粘貼此代碼賢者,你會看到的問題和解決方案:

def go(fx=0, gx=0, xmin=-3, xmax=3, ymin=-10, ymax=10, step=2, x1=0, label=True): 
"""Show a graph, table of values, and points of interest """ 
x = var('x'); fn = 'plot' + str(int(random()*10000)) + '.png' 

f(x) = fx 
g(x) = gx 
s = abs(xmin/step) 

# data 
x1 = x1 
p1 = (x1, f(x1)) # point of interest 
fv = [(i, f(i)) for i in xrange(xmin,xmax,s)] 
gv = [(i, g(i)) for i in xrange(xmin,xmax,s)] 

# plot with points 
G = plot(f(x),(x,xmin,xmax), ymin=ymin, ymax=ymax, color='green'); 
G += plot(g(x),(x,xmin,xmax),ymin=ymin, ymax=ymax, color='red'); 
G += points(fv+gv,pointsize=40,color='black'); 
G += points(p1,pointsize=40,color='blue') 

if label: 
    for p in fv+gv: # label points 
     G += text('(%d,%.1f)'%(p[0],p[1]),p,horizontal_alignment='left',rotation=40,color='black',fontsize=10, fontweight='light') 
    G += text('(%.1f,%.1f)'%(p1[0],p1[1]),p1,horizontal_alignment='left',rotation=40,color='blue',fontsize=10, fontweight='bold') 

G.save(DATA + fn) # required due to Sage object caching 

html('<div style="float:left;">') 
html("<img src="+fn+"></img>") 
html('</div><div style="float:left; padding-left:50px;">Green Graph') 
html.table([["$x$", f]] + fv, header = True) 
html('</div><div style="float:left; padding-left:50px;">Red Graph') 
html.table([["$x$", g]] + gv, header = True) 
html('</div><div style="float:left; padding-left:50px;">Interesting Points') 
html.table([["$x$", "$y$"]] + [p1], header = True) 
html('</div>') # html 

import time; time.sleep(1); os.remove(DATA + fn) # cleanup 
return 

go(x^3,x^5,-20,20,-1000,1000,label=True) # causes error 
go(x^3,x^5,-20,20,-1000,1000,label=False) # works 
go(x^3,x^5, -7, 7,-1000,1000,label=True) # works (but notice huge png!) 
相關問題