【问题标题】:Save only line without axes, labels and padding in matplotlib在 matplotlib 中只保存没有轴、标签和填充的线
【发布时间】:2021-01-09 22:09:18
【问题描述】:

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

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

这是我的代码:

import matplotlib.pyplot as plt

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

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.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())

fig = plt.figure(figsize=(9,3))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_axis_off()

ax.plot(x, y)
# plt.savefig("result.png", format="png", transparent=True, `bbox_inches="tight", pad_inches=0)  # Result image is empty.
plt.savefig("result.png", format="png", transparent=True)
plt.show()

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

有没有什么方法可以实现无填充的图表?

【问题讨论】:

    标签: python matplotlib figure


    【解决方案1】:

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

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

    输出

    【讨论】:

    • 感谢您的建议,但是结果图像没有 3:1 的纵横比,所以我必须手动创建图形。如果我这样做,那么删除填充将不再起作用。
    • 好吧,我不确定你的意思是什么?我这样做没有问题。查看我的更新答案。
    • 问题在于方法调用的顺序错误。我首先设置了边距,然后创建了图形,这没有用 - 我的错误。
    猜你喜欢
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 2017-02-24
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 2015-12-29
    相关资源
    最近更新 更多