单击即可更改子图内拾取的数据点的颜色



美好的一天堆栈溢出,

我是一个相对的 Python 初学者,我被困在以下任务中:我想通过点击点本身来更改数据点的颜色。通过创建随机子图,我相对而言走得很远,但我可以在最后一个子图中更改点的颜色(单击其他地方也只会在最后一个子图中更改颜色(。我错过了什么?

import numpy as np
import matplotlib.pyplot as plt
import random
import sys

fig, axes = plt.subplots(nrows=5, ncols=3, sharex=True, sharey=True)
xlim = (0, 30)
ylim = (0, 15)
plt.xticks(np.arange(0, 15, 5))
plt.yticks(np.arange(0, 15, 5))
plt.xticks(np.arange(0, 30, 5))
plt.setp(axes, xlim=xlim, ylim=ylim)
for i in range(0, 5, 1):
for j in range(0, 3, 1):
X_t = np.random.rand(10, 4) * 20
points = axes[i][j].scatter(X_t[:, 0], X_t[:, 1],
facecolors=["C0"] * len(X_t), edgecolors=["C0"] * len(X_t), picker=True)

def onpick(event):
print(X_t[event.ind], "clicked")
points._facecolors[event.ind, :] = (1, 1, 0, 1)
points._edgecolors[event.ind, :] = (1, 0, 0, 1)
fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

似乎事件中包含的信息.ind不正确,我在错误的时间要求提供该信息。

我很高兴得到任何帮助!

问候!

(对建议的最佳实践进行编辑(

您需要保存不同子图的所有点并通过event.artist您当前单击的子图(请参阅此问题(

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=5, ncols=3, sharex=True, sharey=True)
xlim = (0, 30)
ylim = (0, 15)
plt.xticks(np.arange(0, 15, 5))
plt.yticks(np.arange(0, 15, 5))
plt.xticks(np.arange(0, 30, 5))
plt.setp(axes, xlim=xlim, ylim=ylim)
points_list = []   ###
for i in range(0, 5, 1):
for j in range(0, 3, 1):
X_t = np.random.rand(10, 4) * 20
points_list.append(axes[i][j].scatter(X_t[:, 0], X_t[:, 1],
facecolors=["C0"] * len(X_t), edgecolors=["C0"] * len(X_t), picker=True))   ###

def onpick(event):
print(event.artist, X_t[event.ind], "clicked")
for points in points_list:
if event.artist == points:  ###
points._facecolors[event.ind, :] = (1, 1, 0, 1)
points._edgecolors[event.ind, :] = (1, 0, 0, 1)
fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', onpick)
plt.show()

从您看到的检查event.artist == points中,您可以直接使用event.artist,而不是将所有点保存在列表中:

def onpick(event):
print(event.artist, X_t[event.ind], "clicked")
event.artist._facecolors[event.ind, :] = (1, 1, 0, 1)
event.artist._edgecolors[event.ind, :] = (1, 0, 0, 1)
fig.canvas.draw()

最新更新