Matplotlib:将图转换为无边界的numpy数组

时间:2018-06-27 09:47:12

标签: python matplotlib

我使用scatter()来绘制此图:

enter image description here

然后我将图转换为numpy数组以进行进一步处理,并得到以下结果:

enter image description here

我如何摆脱边界?

这是我的代码:

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 个答案:

答案 0 :(得分:2)

渲染图之前,您应每次关闭axis。这是修改后的代码。

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

结果图:

enter image description here

答案 1 :(得分:0)

我想出了摆脱边界的方法。只需替换

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

使用

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

它工作正常。