Skip to content Skip to sidebar Skip to footer

How To Completely Remove The White Space Around A Scatter Plot

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,alp

Solution 1:

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.

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()

enter image description here

Solution 2:

This worked for expanding images to full screen in both show and savefig with no frames, spines or ticks, Note everything is done in the plt instance with no need to create the subplot, axis instance or 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

This worked for at least 600 dpi which was well beyond the original image resolution at normal display widths. This is very convenient for displaying OpenCV images without distortion using

import numpy as npim= img[:, :, ::-1]

to convert the colour formats before the plt.imshow.

Post a Comment for "How To Completely Remove The White Space Around A Scatter Plot"