【问题标题】:Matplotlib "ValueError: width and height must each be below 32768" in IPython NotebookIPython Notebook中的Matplotlib“ValueError:宽度和高度必须分别低于32768”
【发布时间】:2015-06-09 17:56:16
【问题描述】:

我正在研究“用于数据分析的 Python”中的一些示例,并尝试在 IPython 笔记本中使用以下内联脚本制作一个简单的绘图:

%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 启动图形来手动设置图形宽度,但结果是一样的。

我也发现了这个关于同一问题的旧错误报告,但它似乎从未得到解决:https://github.com/ipython/ipython/issues/1740

知道如何解决这个问题吗?

【问题讨论】:

  • 根据您发布的问题,您可以尝试在%matplotlib inline 呼叫后拨打%config InlineBackend.print_figure_kwargs={'bbox_inches':None} 吗?

标签: python matplotlib ipython ipython-notebook


【解决方案1】:

我在 Sage 中遇到了类似的问题,由于我的 x^5 函数,我无意中绘制了超过 32K 的图。展示比描述更容易。

如果您复制并粘贴此 Sage 代码,您将看到问题和解决方案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多