Matplotlib 保存图像时裁剪
下面这段示例代码会生成一个基本的折线图,图上没有坐标轴,并将其保存为SVG格式的文件:
import matplotlib.pyplot as plt
plt.axis('off')
plt.plot([1,3,1,2,3])
plt.plot([3,1,1,2,1])
plt.savefig("out.svg", transparent = True)
我该如何设置图像的分辨率或尺寸呢?现在图像的四周都有一些空白区域,超出了折线图的部分。我该如何去掉这些空白,让折线图的边缘紧贴图像的边缘呢?
3 个回答
3
一个很简单的方法来减少大部分的空白边距,就是在保存图像之前调用 tight_layout()
。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 200)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x))
fig.tight_layout()
fig.savefig('plot.pdf')
3
默认的坐标轴对象会留出一些空间给标题、刻度标签等。你可以自己制作一个坐标轴对象,让它填满整个区域:
fig=figure()
ax=fig.add_axes((0,0,1,1))
ax.set_axis_off()
ax.plot([3,1,1,2,1])
ax.plot([1,3,1,2,3])
fig.savefig('out.svg')
在svg格式中,我看不到最底部的那条线,但在png格式中可以看到,所以这可能是svg渲染器的一个特性。你可能需要加一点边距,以确保所有内容都能看得见。
63
我一直对在matplotlib中有这么多种方法来做同一件事感到惊讶。
所以,我相信一定有人能把这段代码写得更简洁。
无论如何,这段代码应该能清楚地展示如何解决你的问题。
>>> import pylab
>>> fig = pylab.figure()
>>> pylab.axis('off')
(0.0, 1.0, 0.0, 1.0)
>>> pylab.plot([1,3,1,2,3])
[<matplotlib.lines.Line2D object at 0x37d8cd0>]
>>> pylab.plot([3,1,1,2,1])
[<matplotlib.lines.Line2D object at 0x37d8d10>]
>>> fig.get_size_inches() # check default size (width, height)
array([ 8., 6.])
>>> fig.set_size_inches(4,3)
>>> fig.get_dpi() # check default dpi (in inches)
80
>>> fig.set_dpi(40)
# using bbox_inches='tight' and pad_inches=0
# I managed to remove most of the padding;
# but a small amount still persists
>>> fig.savefig('out.svg', transparent=True, bbox_inches='tight', pad_inches=0)