首页 文章

Matplotlib绘图:删除轴,图例和空格

提问于
浏览
177

我是Python和Matplotlib的新手,我想简单地将colormap应用于图像并编写生成的图像,而不使用轴,标签, Headers 或通常由matplotlib自动添加的任何内容 . 这是我做的:

def make_image(inputname,outputname):
    data = mpimg.imread(inputname)[:,:,0]
    fig = plt.imshow(data)
    fig.set_cmap('hot')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.savefig(outputname)

它成功地移除了图形的轴,但保存的图形呈现白色填充和实际图像周围的框架 . 如何删除它们(至少是白色填充)?谢谢

8 回答

  • 36

    我认为命令 axis('off') 比单独更改每个轴和边界更简洁地处理其中一个问题 . 然而,它仍然留下边界周围的白色空间 . 将 bbox_inches='tight' 添加到 savefig 命令几乎可以让你到达那里,你可以在下面的例子中看到剩下的空白区域要小得多,但仍然存在 .

    from numpy import random
    import matplotlib.pyplot as plt
    
    data = random.random((5,5))
    img = plt.imshow(data, interpolation='nearest')
    img.set_cmap('hot')
    plt.axis('off')
    plt.savefig("test.png", bbox_inches='tight')
    

    enter image description here

  • 77

    我从matehat, here学到了这个技巧:

    import matplotlib.pyplot as plt
    import numpy as np
    
    def make_image(data, outputname, size=(1, 1), dpi=80):
        fig = plt.figure()
        fig.set_size_inches(size)
        ax = plt.Axes(fig, [0., 0., 1., 1.])
        ax.set_axis_off()
        fig.add_axes(ax)
        plt.set_cmap('hot')
        ax.imshow(data, aspect='equal')
        plt.savefig(outputname, dpi=dpi)
    
    # data = mpimg.imread(inputname)[:,:,0]
    data = np.arange(1,10).reshape((3, 3))
    
    make_image(data, '/tmp/out.png')
    

    产量

    enter image description here

  • 16

    最简单的解决方案:

    我简单地将问题中描述的方法与Hooked的答案中的方法结合起来 .

    fig = plt.imshow(my_data)
    plt.axis('off')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.savefig('pict.png', bbox_inches='tight', pad_inches = 0)
    

    在此代码之后,没有空格,也没有框架 .

    No whitespaces, axes or frame

  • 1

    还没有人提到imsave,这使得它成为一个单行:

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = np.arange(10000).reshape((100, 100))
    plt.imsave("/tmp/foo.png", data, format="png", cmap="hot")
    

    它直接存储图像,即不添加任何轴或边框/填充 .

    enter image description here

  • 0

    您还可以指定 bbox_inches 参数的图形范围 . 这将摆脱图周围的白色填充 .

    def make_image(inputname,outputname):
        data = mpimg.imread(inputname)[:,:,0]
        fig = plt.imshow(data)
        fig.set_cmap('hot')
        ax = fig.gca()
        ax.set_axis_off()
        ax.autoscale(False)
        extent = ax.get_window_extent().transformed(plt.gcf().dpi_scale_trans.inverted())
        plt.savefig(outputname, bbox_inches=extent)
    
  • 241

    我喜欢ubuntu's答案,但它没有明确显示如何设置开箱即用的非方形图像的大小,所以我修改它以便于复制粘贴:

    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    import numpy as np
    
    def save_image_fix_dpi(data, dpi=100):
        shape=np.shape(data)[0:2][::-1]
        size = [float(i)/dpi for i in shape]
    
        fig = plt.figure()
        fig.set_size_inches(size)
        ax = plt.Axes(fig,[0,0,1,1])
        ax.set_axis_off()
        fig.add_axes(ax)
        ax.imshow(data)
        fig.savefig('out.png', dpi=dpi)
        plt.show()
    

    如果保留pixel_size / dpi = size,则无论选择何种dpi,都可以轻松保存没有边框的图像 .

    data = mpimg.imread('test.png')
    save_image_fix_dpi(data, dpi=100)
    

    enter image description here

    但显示是怪异的 . 如果选择小dpi,则图像尺寸可能比屏幕大,并且在显示期间会出现边框 . 然而,这不会影响储蓄 .

    因此对于

    save_image_fix_dpi(data, dpi=20)
    

    显示屏边界(但保存工作):
    enter image description here

  • 8

    这应该删除所有填充和边框:

    from matplotlib import pyplot as plt
    
    fig = plt.figure()
    fig.patch.set_visible(False)
    
    ax = fig.add_subplot(111)
    
    plt.axis('off')
    plt.imshow(data)
    
    extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    plt.savefig("../images/test.png", bbox_inches=extent)
    
  • 1

    首先,对于某些图像格式(即TIFF),您实际上可以将色彩图保存在 Headers 中,大多数查看者将使用色彩图显示您的数据 .

    为了保存实际的 matplotlib 图像,这对于向图像添加注释或其他数据非常有用,我使用了以下解决方案:

    fig, ax = plt.subplots(figsize=inches)
    ax.matshow(data)  # or you can use also imshow
    # add annotations or anything else
    # The code below essentially moves your plot so that the upper
    # left hand corner coincides with the upper left hand corner
    # of the artist
    fig.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
    # now generate a Bbox instance that is the same size as your
    # single axis size (this bbox will only encompass your figure)
    bbox = matplotlib.transforms.Bbox(((0, 0), inches))
    # now you can save only the part of the figure with data
    fig.savefig(savename, bbox_inches=bbox, **kwargs)
    

相关问题