[英]Matplotlib savefig image trim
The following sample code will produce a basic line plot with no axes and save it as an SVG file:以下示例代码将生成一个没有轴的基本线图并将其保存为 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)
How do I set the resolution / dimensions of the image?如何设置图像的分辨率/尺寸? There is padding on all sides of the image beyond the line graph.
超出折线图的图像的所有边都有填充。 How do I remove the padding so that the lines appear on the edge of the image?
如何删除填充以使线条出现在图像的边缘?
I am continually amazed at how many ways there are to do the same thing in matplotlib.我一直惊讶于在 matplotlib 中有多少种方法可以做同样的事情。
As such, I am sure that someone can make this code much more terse.因此,我相信有人可以使这段代码更加简洁。
At any rate, this should clearly demonstrate how to go about solving your problem.无论如何,这应该清楚地展示如何着手解决您的问题。
>>> 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 for savefig()
. savefig()
文档。
The default axis object leaves some room for titles, tick labels and the like.默认轴对象为标题、刻度标签等留下了一些空间。 Make your own axis object that fills the whole area:
制作自己的轴对象来填充整个区域:
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')
In svg format I can't see the line that's right at the bottom, but in png format I can, so it's probably a feature of the svg renderer.在 svg 格式中,我看不到底部的行,但在 png 格式中我可以看到,所以这可能是 svg 渲染器的一个功能。 You might want to add just a little padding to keep everything visible.
您可能只想添加一点填充以保持所有内容可见。
A very easy way to trim down most padding is to call tight_layout()
before saving the figure.减少大多数填充的一种非常简单的方法是在保存图形之前调用
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.