Matplotlib savefig图像修剪

2024-04-28 10:51:41 发布

您现在位置:Python中文网/ 问答频道 /正文

以下示例代码将生成不带轴的基本线条图,并将其保存为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)

如何设置图像的分辨率/尺寸?在图像的所有边上都有线图之外的填充。如何移除填充以使线条显示在图像的边缘?


Tags: 文件代码svg图像import示例plotmatplotlib
3条回答

默认的axis对象为标题、记号标签等留下了一些空间。创建填充整个区域的轴对象:

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渲染器的一个特性。您可能需要添加一点填充以保持所有内容都可见。

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

Documentation用于savefig()

减少大多数填充的一个非常简单的方法是在保存图之前调用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')

相关问题 更多 >