Gilfoyle
Gilfoyle

Reputation: 3616

Matplotlib: Convert plot to numpy array without borders

I use scatter() to produce this plot:

enter image description here

Then I convert the plot to a numpy array for further processing and get this:

enter image description here

How can I get rid of the border?

Here is my code:

import matplotlib.pyplot as plt
import numpy as np

n = 500
domain_size = 1000

x = np.random.randint(0,domain_size,(n,2))

fig, ax = plt.subplots(frameon=False)
fig.set_size_inches((5,5))
ax.scatter(x[:,0], x[:,1], c="black", s=200, marker="*")
ax.set_xlim(0,domain_size)
ax.set_ylim(0,domain_size)
fig.add_axes(ax)

fig.canvas.draw()

X = np.array(fig.canvas.renderer._renderer)
X = 0.2989*X[:,:,1] + 0.5870*X[:,:,2] + 0.1140*X[:,:,3]

plt.show()
plt.close()

plt.imshow(X, interpolation="none", cmap="gray")
plt.show()

Upvotes: 2

Views: 5184

Answers (2)

Gilfoyle
Gilfoyle

Reputation: 3616

I figured out how to get rid of the borders. Just replace

fig, ax = plt.subplots(frameon=False)

with

fig = plt.figure()
ax = fig.add_axes([0.,0.,1.,1.])

and it works just fine.

Upvotes: 2

swatchai
swatchai

Reputation: 18782

You should turn off the axis each time before rendering the plots. Here is the modified code that does so.

import matplotlib.pyplot as plt
import numpy as np

n = 500
domain_size = 100
x = np.random.randint(0,domain_size,(n,2))

fig, ax = plt.subplots()
fig.set_size_inches((5,5))
ax.scatter(x[:,0], x[:,1], c="black", s=200, marker="*")
ax.set_xlim(0,domain_size)
ax.set_ylim(0,domain_size)
ax.axis('off')

fig.add_axes(ax)
fig.canvas.draw()

# this rasterized the figure
X = np.array(fig.canvas.renderer._renderer)
X = 0.2989*X[:,:,1] + 0.5870*X[:,:,2] + 0.1140*X[:,:,3]

plt.show()
plt.close()

# plot the image array X
fig2, ax2 = plt.subplots()
plt.imshow(X, interpolation="none", cmap="gray")

ax2.axis('off')

plt.show()

The resulting plot:

enter image description here

Upvotes: 2

Related Questions