如何用相应的 RGB 数组绘制 2D numpy 坐标数组?
How to plot 2D numpy coordinate array with corresponding RGB array?
我有一个 2D numpy 坐标数组 (x, y),尺寸为 40000x2,我 运行 通过机器学习模型。我将预测转换为尺寸为 40000x3 的 RGB numpy 数组。 RGB 数组中的每个条目(行)对应于坐标数组中的相同条目。
我希望能够快速绘制所有内容。之前尝试使用scatter()函数,但是耗时太长
# Fragment of code I used before
# coordArray (40000x2), rgbArray (40000x3)
f, ax = plt.subplots(figsize=(7, 7))
for i in range(len(coordArray)):
ax.scatter(coordArray[i, 0], coordArray[i, 1], marker='o',
c=rgbArray[i], s=1.5, alpha=1)
plt.show()
我想知道是否有 better/quicker 绘制数据的方法。作为参考,我还绘制了我的训练集和测试集(代码片段中未显示)。
您可以创建一个合适的 np.array
并用 rgbArray
中的值填充坐标。然后用 plt.imshow
绘制数组。缺少的坐标将绘制为黑色。
import numpy as np
import matplotlib.pyplot as plt
#Example with 3 coordinates in a 2x2 array
# [0,0] -> red
# [0,1] -> green
# [1,1] -> blue
# [1,0] -> 'no information'
coord = np.array([[0,0],[0,1],[1,1]])
rgb = np.array([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]])
img = np.zeros(tuple(coord.max(0)+1)+(3,))
img[coord[:,0],coord[:,1]] = rgb
plt.imshow(img)
plt.axis('off');
输出:
如果您想要散点图,则无需遍历数组。您可以使用:
plt.scatter(coord[:,0],coord[:,1], color=rgb, s=20);
输出:
使用矢量化代码可能会加快绘图速度:
f, ax = plt.subplots(figsize=(7, 7))
ax.scatter(coordArray[:, 0], coordArray[:, 1],
marker='o', c=rgbArray/255, s=1.5, alpha=1)
plt.show()
请注意 rgbArray
的条目必须在 [0,1] 范围内。
我有一个 2D numpy 坐标数组 (x, y),尺寸为 40000x2,我 运行 通过机器学习模型。我将预测转换为尺寸为 40000x3 的 RGB numpy 数组。 RGB 数组中的每个条目(行)对应于坐标数组中的相同条目。
我希望能够快速绘制所有内容。之前尝试使用scatter()函数,但是耗时太长
# Fragment of code I used before
# coordArray (40000x2), rgbArray (40000x3)
f, ax = plt.subplots(figsize=(7, 7))
for i in range(len(coordArray)):
ax.scatter(coordArray[i, 0], coordArray[i, 1], marker='o',
c=rgbArray[i], s=1.5, alpha=1)
plt.show()
我想知道是否有 better/quicker 绘制数据的方法。作为参考,我还绘制了我的训练集和测试集(代码片段中未显示)。
您可以创建一个合适的 np.array
并用 rgbArray
中的值填充坐标。然后用 plt.imshow
绘制数组。缺少的坐标将绘制为黑色。
import numpy as np
import matplotlib.pyplot as plt
#Example with 3 coordinates in a 2x2 array
# [0,0] -> red
# [0,1] -> green
# [1,1] -> blue
# [1,0] -> 'no information'
coord = np.array([[0,0],[0,1],[1,1]])
rgb = np.array([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]])
img = np.zeros(tuple(coord.max(0)+1)+(3,))
img[coord[:,0],coord[:,1]] = rgb
plt.imshow(img)
plt.axis('off');
输出:
如果您想要散点图,则无需遍历数组。您可以使用:
plt.scatter(coord[:,0],coord[:,1], color=rgb, s=20);
输出:
使用矢量化代码可能会加快绘图速度:
f, ax = plt.subplots(figsize=(7, 7))
ax.scatter(coordArray[:, 0], coordArray[:, 1],
marker='o', c=rgbArray/255, s=1.5, alpha=1)
plt.show()
请注意 rgbArray
的条目必须在 [0,1] 范围内。