2

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()
2
  • 1
    Crop away the borders using a slice, or set xlim and ylim on the imshow plot... Commented Jun 27, 2018 at 10:31
  • @NilsWerner For further processing I need a numpy array without white borders. Cropping away the borders is not a clean solution, since the size of the borders depends on fig.set_size_inches(()). Setting xlim or ylim has no effects on X and therefore does not solve my problem. Any other suggestion?
    – Gilfoyle
    Commented Jun 27, 2018 at 17:49

2 Answers 2

2

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

3
  • The border is still there when I use your code. Any other suggestion?
    – Gilfoyle
    Commented Jun 27, 2018 at 17:50
  • Do you mean white border?
    – swatchai
    Commented Jun 28, 2018 at 4:14
  • Yes, when I use your code, I still get a white border. Any suggestion how to remove it without using a slice?
    – Gilfoyle
    Commented Jun 28, 2018 at 9:41
2

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.