用matplotlib在Python中绘制矩阵坐标

3 投票
1 回答
1498 浏览
提问于 2025-04-17 15:44

我有一组坐标,比如 [(2,3),(45,4),(3,65)]。我想把它们画成一个矩阵的样子,请问有没有办法在matplotlib里做到这一点?我希望它看起来像这个样子 https://i.stack.imgur.com/NctN2.jpg

1 个回答

3

编辑:我最开始的回答用了 ax.scatter,但这样有个问题:如果有两个点很靠近,ax.scatter 可能会在它们之间留出一点空隙,这取决于缩放比例。

比如说,使用

data = np.array([(2,3),(3,3)])

这里是放大后的细节:

在这里输入图片描述

所以,这里有一个替代方案可以解决这个问题:

import matplotlib.pyplot as plt
import numpy as np

data = np.array([(2,3),(3,3),(45,4),(3,65)])
N = data.max() + 5

# color the background white (1 is white)
arr = np.ones((N,N), dtype = 'bool')
# color the dots black (0)
arr[data[:,1], data[:,0]] = 0

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

ax.imshow(arr, interpolation='nearest', cmap = 'gray')
ax.invert_yaxis()
# ax.axis('off')
plt.show()

在这里输入图片描述

无论你放大多少,坐标 (2,3) 和 (3,3) 的相邻方块都会保持紧挨着。

不过,不像 ax.scatter,使用 ax.imshow 需要构建一个 N x N 的数组,所以它可能会比 ax.scatter 更占内存。不过,除非 data 里有非常大的数字,否则这应该不是问题。

撰写回答