在 matplolib 中插入矩阵

时间:2020-12-27 15:15:25

标签: python numpy matplotlib

我想在 numpy 图中导入一个 matplotlib 矩阵。假设我有这个矩阵:

[[ 1, 2, 3, 4],
 [ 5, 6, 7, 8],
 [ 9,10,11,12]]

在 x 轴的 0 到 3 范围内,我想绘制点

(0,1), (0,5), (0,9), 
(1,2), (1,6), (1,10), 
(2,3), (2,7), (2,11), 
(3,4), (3,8), (3,12)

这是我使用的代码:

import numpy as np
import matplotlib.pyplot as plt

matrix = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
plt.grid(True)
for i in range(matrix.shape[0]):
    for j in range(matrix.shape[1]):
    plt.plot(j,matrix[i][j],'ro')

plt.show()

这是结果:

enter image description here

然而,如果我必须使用一个大数组,比如(1000x1000)个元素或更多,这个过程将非常缓慢。如果 matplotlib 中有一种方法可以将数组插入到图中而不需要“手动”插入每个元素,我会徘徊。

另外(我知道这应该是一个不同的问题)如果上述问题解决了,是否有一种简单的方法可以清除绘图以使用新矩阵进行更新?

1 个答案:

答案 0 :(得分:2)

a = np.array([
    [ 1, 2, 3, 4],
    [ 5, 6, 7, 8],
    [ 9,10,11,12]])
b = np.tile(np.arange(a.shape[1]), (a.shape[0], 1))

plt.scatter(b, a)

enter image description here

相关问题