python - 如何完全去除散点图周围的空白

标签 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)

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

最佳答案

通过切换到 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()

enter image description here

关于python - 如何完全去除散点图周围的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35429984/

相关文章:

python - 如何在将数据从python推送到sql server时避免bcpy(批量复制python)中的dbo

python - 解析嵌套的 json 负载 python

python - ubuntu:用 pip 卸载 matplotlib 不起作用

python - 在对数 pyplot 中同时使用 yticks 和 ylim

python - 如何使用 python 和 rpy2 控制 R 图的显示位置?

javascript - C3.js "Uncaught Error: Source data is missing a component at (1,844)!"

python - 问题 "removing".sql 文件中的行 block

python - 从 Django 中的字段中删除 autofocus 属性

python - 在 python 中绘制日期和值

plot - 如何在 ILNumerics 中有效地绘制大表面(例如 1000x1000)?