numpy 如何从不同形状的数组中散点图相交值

e0bqpujr  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(106)

我有两个数组,我需要在散点图中使用它们,并考虑它们的成员资格。例如,B的第一行位于A的第二行,从第2列到第3列。

#A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

#B
array([[ 5,  6],
       [12, 13],
       [16, 17]])

我做了下面的代码:

import numpy as np
import matplotlib.pyplot as plt

A = np.arange(20).reshape(5, 4)
B = np.array([[5, 6], [12, 13], [16, 17]])
x, y = np.meshgrid(range(A.shape[0]), range(A.shape[1]))

fig, ax = plt.subplots()
ax.scatter(x, y, facecolor='none', edgecolor='k', s=70, marker='s')

for ix, iy, a in zip(x.ravel(), y.ravel(), A.ravel()):
    plt.annotate(a, (ix,iy), textcoords='offset points', xytext=(0,7), ha='center', fontsize=14)

plt.axis("off")
ax.invert_yaxis()

plt.show()

现在,我可以用np.isin(A, B)检查B是否在A中,但有两个问题:
1.不反映A形状的网格(右侧有一个额外的列)

  1. True值必须是一个填充的x 'X',带有黑色边缘,大小和宽度与红色相同

你有什么办法吗

b5lpy0ml

b5lpy0ml1#

根据@chrslg的评论,x, y = np.meshgrid(range(A.shape[1]), range(A.shape[0]))而不是x, y = np.meshgrid(range(A.shape[0]), range(A.shape[1]))
np.isin(A, B)创建一个布尔数组,可用于索引xy,以便在's'标记中插入'x'标记,以获得重叠值。

np.isin(A, B)
array([[False, False, False, False],
       [False,  True,  True, False],
       [False, False, False, False],
       [ True,  True, False, False],
       [ True,  True, False, False]])
import numpy as np
import matplotlib.pyplot as plt

A = np.arange(20).reshape(5, 4)
B = np.array([[5, 6], [12, 13], [16, 17]])

# reversed 1 and 0 on this line
x, y = np.meshgrid(range(A.shape[1]), range(A.shape[0]))

# create a Boolean of overlapping values
idx_bool = np.isin(A, B)

fig, ax = plt.subplots()
ax.scatter(x, y, facecolor='r', edgecolor='k', s=70, marker='s')

# use idx_bool to on x and y
ax.scatter(x[idx_bool], y[idx_bool], facecolor='k', s=70, marker='x')

for ix, iy, a in zip(x.ravel(), y.ravel(), A.ravel()):
    plt.annotate(a, (ix,iy), textcoords='offset points', xytext=(0,7), ha='center', fontsize=14)

plt.axis("off")
ax.invert_yaxis()

plt.show()

使用idx_bool的逆函数有选择地添加facecolor

fig, ax = plt.subplots()

# selectively plot red squares
ax.scatter(x[~idx_bool], y[~idx_bool], facecolor='r', edgecolor='k', s=70, marker='s')

# use idx_bool on x and y
ax.scatter(x[idx_bool], y[idx_bool], facecolor='none', edgecolor='k', s=70, marker='s')  # remove this line if you don't want any squares on the True values
ax.scatter(x[idx_bool], y[idx_bool], facecolor='k', s=70, marker='x')

for ix, iy, a in zip(x.ravel(), y.ravel(), A.ravel()):
    plt.annotate(a, (ix,iy), textcoords='offset points', xytext=(0,7), ha='center', fontsize=14)

plt.axis("off")
ax.invert_yaxis()

plt.show()

删除ax.scatter(x[idx_bool], y[idx_bool], facecolor='none', edgecolor='k', s=70, marker='s')

相关问题