【问题标题】:Matplotlib savefig image trimMatplotlib savefig 图像修剪
【发布时间】:2011-03-08 23:42:55
【问题描述】:

以下示例代码将生成一个没有轴的基本线图并将其保存为 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)

如何设置图像的分辨率/尺寸?折线图之外的图像四面都有填充。如何删除填充以使线条出现在图像的边缘?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    我一直对在 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)
    

    Documentationsavefig()

    【讨论】:

    • 有没有办法把这些放在 matplotlibrc 中? Bad key "savefig.bbox_inches"
    • 不客气。我不知道是否可以使用 matplotlibrc 文件提供这样的配置规范。
    • 我喜欢在 pyplot 中使用的另一个命令(与上面列出的命令一起使用)是 plt.tight_layout(),它会删除图形周围多余的空白。
    • 如果我想为 png 设置像素分辨率?
    【解决方案2】:

    默认轴对象为标题、刻度标签等留出了一些空间。制作自己的轴对象,填充整个区域:

    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 渲染器的一个功能。您可能只想添加一点填充以保持所有内容可见。

    【讨论】:

    • 正确。您可以通过手动制作轴来调整图中轴的位置。用于制作坐标区的 pyplot(或 pylab)命令在其文档字符串中包含以下内容: axes(rect, axisbg='w') where rect=[left, bottom, width, height] 以标准化 (0,1) 单位表示。 axisbg 是轴的背景颜色,默认为白色
    【解决方案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')
    

    【讨论】:

    • plt.tight_layout() 也为我完成了 SVG 的工作。对于 PNG,没有必要,但 matplotlib 似乎以不同的方式对待 SVG。
    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 2013-12-19
    • 2012-02-19
    • 2012-10-12
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    相关资源
    最近更新 更多