在matplotlib中仅保存没有轴,标签和填充的线

问题描述

我想将Matplotlib折线图保存为长宽比为3:1且没有轴或标签的透明png图像。我需要图的线直接在图像边缘开始和结束(没有任何填充)。

我发现了几个类似的主题,例如G。 tight savefig without axes in matplotlibRemoving white space around a saved image in matplotlib,但这两个建议都没有帮助。

这是我的代码

then

仍然,结果图像中存在一些填充(有白色背景显示填充,但实际上图像是透明的):

enter image description here

有没有办法实现图表而无需填充?

解决方法

这是基于您添加的问题之一的解决方案:

import matplotlib.pyplot as plt
import numpy as np
import os

x = np.arange(1,10)
y = np.arange(51,60)

plt.figure(figsize=(9,3))
plt.plot(x,y)
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1,bottom = 0,right = 1,left = 0,hspace = 0,wspace = 0)
plt.margins(0,0)
plt.savefig("myfig.png")

#os.system('convert myfig.png -trim myfig.png') #<- a quick workaround if you are on mac or Linux.
plt.show()

输出enter image description here