fst*_*tab 3 python plot matplotlib 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)
Run Code Online (Sandbox Code Playgroud)
但是当我在图像上添加散点图时,如下所示:
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)
Run Code Online (Sandbox Code Playgroud)
此时,通过使用以下savefig命令,在图像周围添加了空格:
plt.savefig(im_filename,format="png",bbox_inches='tight',pad_inches=0)
Run Code Online (Sandbox Code Playgroud)
关于如何去除空白区域的任何想法?
通过切换到mpl面向对象的样式,您可以在同一轴上绘制图像和散点图,因此只需要使用ax.imshow和设置一次空白ax.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()
Run Code Online (Sandbox Code Playgroud)