【问题标题】:Matplotlib get clean plot (remove all decorations)Matplotlib 获得干净的情节(删除所有装饰)
【发布时间】:2016-11-19 13:21:00
【问题描述】:

作为参考,同样的问题,但针对imshow():Matplotlib plots: removing axis, legends and white spaces

由于stackoverflow页面背景是白色的,因此在所选答案的嵌入图像中,情节周围有厚厚的白色边距并不明显。

@unutbu 的以下回答适用于imshow(),但不适用于一般plot()。此外,aspect='normal 自 1.2 版以来已被弃用。

那么如何将plot()保存为图片,不加任何装饰?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    ax.set_axis_off(),或等效的ax.axis('off') 关闭轴线和标签。要删除更多空格,您可以使用

    fig.savefig('/tmp/tight.png', bbox_inches='tight', pad_inches=0.0)
    

    或to remove all whitespace up to the axis' boundaries,使用

    extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    fig.savefig('/tmp/extent.png', bbox_inches=extent)
    

    这些命令同样适用于ax.imshow(data) 或ax.plot(data)。


    例如,

    import numpy as np
    import matplotlib.pyplot as plt
    
    data = np.arange(1,10).reshape((3, 3))
    fig, ax = plt.subplots()
    ax.plot(data)
    ax.axis('off')
    # https://stackoverflow.com/a/4328608/190597 (Joe Kington)
    # Save just the portion _inside_ the axis's boundaries
    extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    fig.savefig('/tmp/extent.png', bbox_inches=extent)
    fig.savefig('/tmp/tight.png', bbox_inches='tight', pad_inches=0.0)
    

    extent.png (504x392):

    tight.png (521x414):

    【讨论】:

      【解决方案2】:

      我刚刚了解到@unutbu 的答案也适用于plot(),如果我们从plot() 指令中删除aspect='normal':

      data = np.arange(1,10).reshape((3, 3))
      fig = plt.figure()
      fig.set_size_inches(1, 1)
      ax = plt.Axes(fig, [0., 0., 1., 1.])
      ax.set_axis_off()
      fig.add_axes(ax)
      ax.plot(data)
      plt.savefig('test.png')
      

      但是,我仍然想知道这一切是否真的有必要获得干净的情节?
      savefig() 不应该有明显的论据可以处理这个问题吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-10
        • 2019-09-27
        • 2017-05-28
        • 2018-11-07
        • 2016-09-09
        相关资源
        最近更新 更多