【问题标题】:How to completely remove the white space around a scatter plot如何完全删除散点图周围的空白
【发布时间】:2016-05-27 13:55:26
【问题描述】:

我正在尝试在图像上绘制散点图,而图像周围没有任何空白。

如果我只绘制如下图像,则没有空白:

fig = plt.imshow(im,alpha=alpha,extent=(0,1,1,0))
plt.axis('off')
fig.axes.axis('tight')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)

但当我在图像上添加散点图时,如下所示:

fig = plt.scatter(sx, sy,c="gray",s=4,linewidths=.2,alpha=.5)
fig.axes.axis('tight')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)

此时,通过使用以下 savefig 命令,在图像周围添加空白:

plt.savefig(im_filename,format="png",bbox_inches='tight',pad_inches=0)

关于如何明确删除空白的任何想法?

【问题讨论】:

    标签: python matplotlib plot scatter-plot imshow


    【解决方案1】:

    通过切换到 mpl 面向对象样式,您可以在同一轴上绘制图像和散点图,因此只需使用ax.imshowax.scatter 设置一次空白。

    在下面的示例中,我使用subplots_adjust 删除坐标轴周围的空白,并使用ax.axis('tight') 将坐标轴限制设置为数据范围。

    import matplotlib.pyplot as plt
    import numpy as np
    
    # Load an image
    im = plt.imread('stinkbug.png')
    
    # Set the alpha
    alpha = 0.5
    
    # Some random scatterpoint data
    sx = np.random.rand(100)
    sy = np.random.rand(100)
    
    # Creare your figure and axes
    fig,ax = plt.subplots(1)
    
    # Set whitespace to 0
    fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
    
    # Display the image
    ax.imshow(im,alpha=alpha,extent=(0,1,1,0))
    
    # Turn off axes and set axes limits
    ax.axis('tight')
    ax.axis('off')
    
    # Plot the scatter points
    ax.scatter(sx, sy,c="gray",s=4,linewidths=.2,alpha=.5)
    
    plt.show()
    

    【讨论】:

    • 关闭轴和设置轴限制也可以在show()之前的最后设置?
    • 你试过savefig吗?似乎plt.show 产生了所需的结果,但savefig(我在问题中写的带有参数的调用)仍然添加了白边
    • 实际上,分散的顺序和ax.axis('tight'); ax.axis('off') 确实很重要。在分散之前移动它们,它应该可以工作。您还需要删除 bbox_inches='tight',pad_inches=0 选项
    • 不幸的是它仍然无法正常工作。一切似乎都是那么随意。是否有理由必须在情节之前设置它?为什么需要从savefig 中删除bbox_inches='tight',pad_inches=0
    • 由于某种原因,这个技巧在 python3 matplotlib 2.0 中似乎不起作用。我只是用ax.set_yticklabels([]); ax.set_xticklabels([]);ax.axis('off') 代替。
    【解决方案2】:

    这适用于在 show 和 savefig 中将图像扩展到全屏,没有框架、刺或刻度,注意一切都在 plt 实例中完成,无需创建子图、轴实例或 bbox:

    from matplotlib import pyplot as plt
    
    # create the full plot image with no axes 
    plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
    plt.imshow(im, alpha=.8)
    plt.axis('off')
    
    # add scatter points
    plt.scatter(sx, sy, c="red", s=10, linewidths=.2, alpha=.8)
    
    # display the plot full screen (backend dependent)
    mng = plt.get_current_fig_manager()
    mng.window.state('zoomed')
    
    # save and show the plot
    plt.savefig('im_filename_300.png', format="png", dpi=300)
    plt.show()
    plt.close()  # if you are going on to do other things
    

    这至少适用于 600 dpi,这远远超出了正常显示宽度下的原始图像分辨率。 这对于显示 OpenCV 图像而不失真非常方便

    import numpy as np
    im = img[:, :, ::-1]
    

    在 plt.imshow 之前转换颜色格式。

    【讨论】: