如何用相应的 RGB 数组绘制二维 numpy 坐标数组?

问题描述

我有一个 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()

我想知道是否有更好/更快的方法来绘制数据。作为参考,我还绘制了我的训练集和测试集(只是未在代码片段中显示)。

解决方法

您可以创建一个合适的 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.,1.]])

img = np.zeros(tuple(coord.max(0)+1)+(3,))

img[coord[:,coord[:,1]] = rgb
plt.imshow(img)
plt.axis('off');

出:

image from coordinates


如果您想要散点图,则无需遍历您的数组。您可以使用:

plt.scatter(coord[:,color=rgb,s=20);

出:

scatter plot of same data

,

使用矢量化代码可能会加快绘图速度:

    public Mono<Post> findPostByIdShowComments(String id) {
        return postRepo
                .findById(id)
                .switchIfEmpty(postNotFoundException())
                .flatMap(postFound -> commentService
                                 .findCommentsByPostId(postFound.getId())
                                 .collectList()
                                 .flatMap(comments -> {
                                     postFound.setListComments(comments);
                                     return Mono.just(postFound);
                                 })
                        );
    }

    public Flux<Comment> findCommentsByPostId(String id) {
        return postRepo
                .findById(id)
                .switchIfEmpty(postNotFoundException())
                .thenMany(commentRepo.findAll())
                .filter(comment1 -> comment1.getIdPost()
                                            .equals(id));

    }

请注意,f,ax = plt.subplots(figsize=(7,7)) ax.scatter(coordArray[:,coordArray[:,marker='o',c=rgbArray/255,s=1.5,alpha=1) plt.show() 的条目必须在 [0,1] 范围内。