1

我试图在 pyplot 中保存一个边距很小的数字。

以下代码与 PDF 输出完美配合:

from matplotlib import pyplot as plt
plt.plot(1)
plt.savefig('test.pdf', bbox_inches='tight')

但不是 PGF 输出

plt.savefig('test.pgf', bbox_inches='tight')

当它返回时RuntimeError: Cannot get window extent w/o renderer

为什么会发生这种情况,有没有办法解决它?

Ubuntu 13.04 上的 matplotlib 1.3.0rc2

python -c "from matplotlib import pyplot as plt; plt.plot(1); plt.savefig('test.pgf', bbox_inches='tight');"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/pyplot.py", line 561, in savefig
    return fig.savefig(*args, **kwargs)
  File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/figure.py", line 1410, in savefig
    self.canvas.print_figure(*args, **kwargs)
  File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4agg.py", line 161, in print_figure
    FigureCanvasAgg.print_figure(self, *args, **kwargs)
  File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/backend_bases.py", line 2169, in print_figure
    bbox_inches = self.figure.get_tightbbox(renderer)
  File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/figure.py", line 1551, in get_tightbbox
    bb.append(ax.get_tightbbox(renderer))
  File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/axes.py", line 9153, in get_tightbbox
    bb_xaxis = self.xaxis.get_tightbbox(renderer)
  File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 1055, in get_tightbbox
    renderer)
  File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 1038, in _get_tick_bboxes
    extent = tick.label1.get_window_extent(renderer)
  File "PYTHONPATH/matplotlib-1.3.0rc2-py2.7-linux-x86_64.egg/matplotlib/text.py", line 751, in get_window_extent
    raise RuntimeError('Cannot get window extent w/o renderer')
RuntimeError: Cannot get window extent w/o renderer
4

1 回答 1

1

顺便说一句,有一个解决方法。通常 PGF/TikZ 图像的范围会自动调整,使其与绘图相匹配。为了保留 matplotlib 预期的图形大小,这些行被添加到输出中:

\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{8.000000in}{6.000000in}}%
\pgfusepath{use as bounding box}%

如果您从 PGF 输出的最顶部删除这些行,您应该摆脱图形周围的任何额外空间。

在 1.3 版中使用plt.tight_layout(),或更好plt.figure(tight_layout=True)的是另一种方法(与 PGF 和 PGF->PDF 完美配合),尽管它有点不同。它重新计算图形的布局,使其适合给定的图形大小。我通常更喜欢这种方法,因为它还消除了文本元素重叠等问题。

于 2013-09-07T15:02:25.593 回答