如何彻底删除散点图周围的空白区域?

时间:2016-02-16 10:28:16

标签: python matplotlib plot scatter-plot imshow

我试图在图像上绘制一个散点图,周围没有任何空白区域。

如果我只按如下方式绘制图像,则没有空格:

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)

关于如何去除空白区域的任何想法?

2 个答案:

答案 0 :(得分:5)

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

在下面的示例中,我使用subplots_adjust删除了轴周围的空白,并使用ax.scatter将轴限制设置为数据范围。

ax.axis('tight')

enter image description here

答案 1 :(得分:-1)

这适用于在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之前转换颜色格式。

相关问题