Str*_*tch 5 python pdf matplotlib
当您在 Matplotlib 的 savefig() 函数中设置 bbox_inches = 'tight' 时,它会尝试找到封装图形窗口中所有内容的最紧密的边界框。不幸的是,最紧密的边界框似乎包括不可见的轴。
例如,这里是一个片段,其中设置 bbox_inches = 'tight' 可以根据需要工作:
import matplotlib.pylab as plt
fig = plt.figure(figsize = (5,5))
data_ax = fig.add_axes([0.2, 0.2, 0.6, 0.6])
data_ax.plot([1,2], [1,2])
plt.savefig('Test1.pdf', bbox_inches = 'tight', pad_inches = 0)
Run Code Online (Sandbox Code Playgroud)
它产生:
保存的 pdf 的边界对应于内容的边界。这很好,除了我喜欢使用一组不可见图形轴来放置注释。如果不可见轴超出可见内容的边界,则 pdf 边界大于可见内容。例如:
import matplotlib.pylab as plt
fig = plt.figure(figsize = (5,5))
fig_ax = fig.add_axes([0, 0, 1, 1], frame_on = False)
fig_ax.xaxis.set_visible(False)
fig_ax.yaxis.set_visible(False)
data_ax = fig.add_axes([0.2, 0.2, 0.6, 0.6])
data_ax.plot([1,2], [1,2])
plt.savefig('Test2.pdf', bbox_inches = 'tight', pad_inches = 0)
Run Code Online (Sandbox Code Playgroud)
生产
如何强制 savefig() 忽略图形窗口中的不可见项?我想出的唯一解决方案是自己计算边界框并明确指定 bbox 到 savefig()。
以防万一,我在 Mac OS X 10.8.5 上的 Python 2.7.3 下运行 Matplotlib 1.2.1。
相关函数(由其调用canvas.print_figure
以figure.savefig
生成边界框)backend_bases.py
:
def get_tightbbox(self, renderer):
"""
Return a (tight) bounding box of the figure in inches.
It only accounts axes title, axis labels, and axis
ticklabels. Needs improvement.
"""
bb = []
for ax in self.axes:
if ax.get_visible():
bb.append(ax.get_tightbbox(renderer))
_bbox = Bbox.union([b for b in bb if b.width != 0 or b.height != 0])
bbox_inches = TransformedBbox(_bbox,
Affine2D().scale(1. / self.dpi))
return bbox_inches
Run Code Online (Sandbox Code Playgroud)
决定轴是否“可见”的唯一考虑因素是 if返回 true,即使轴中 ax.get_visible()
没有可见(或简单透明)艺术家。artist.get_visible() == False
您观察到的边界框行为是正确的行为。
归档时间: |
|
查看次数: |
9498 次 |
最近记录: |