如何完全消除散点图周围的空白? [英] How to completely remove the white space around a scatterplot?
问题描述
我正在尝试在图像上绘制散点图,而周围没有任何空白.
I am trying to plot a scatterplot over an image without having any white space around it.
如果仅按以下方式绘制图像,则没有空格:
If I plot just the image as follows, then there is no white space:
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)
但是当我在图像上添加散点图时,如下所示:
but as I add a scatter plot over the image as follows:
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命令,将在图像周围添加空白:
At this point, by using the following savefig command, the white space is added around the image:
plt.savefig(im_filename,format="png",bbox_inches='tight',pad_inches=0)
关于绝对删除空白的任何想法吗?
Any idea on how to remove the white space definitely?
推荐答案
通过切换到mpl面向对象的样式,您可以在同一轴上绘制图像和散点图,因此只需设置空白一次,使用ax.imshow
和ax.scatter
.
By switching to the mpl object-oriented style, you can plot both the image and the scatter plot on the same axes, and hence only have to set the whitespace once, by using ax.imshow
and ax.scatter
.
在下面的示例中,我使用了 subplots_adjust
删除轴周围的空白,并ax.axis('tight')
设置轴限制为数据范围.
In the example below, I've used subplots_adjust
to remove the whitespace around the axes, and ax.axis('tight')
to set the axis limits to the data range.
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()
这篇关于如何完全消除散点图周围的空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!