【发布时间】:2022-08-17 23:35:48
【问题描述】:
当我单击散点图上的任何点时,我希望选择器事件仅显示图例标签。这就是我所拥有的,看起来像:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# x y data and legend labels
x = np.random.uniform(0, 100, 50)
y = np.random.uniform(0, 100, 50)
ID = np.random.randint(0,25,50)
# define the event
def onpick(event):
ind = event.ind
print(\'x:\', x[ind], \'y:\', y[ind])
# create the plot
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, c = ID, picker=True)
ax.set_xlabel(\'x\')
ax.set_ylabel(\'y\')
ax.legend(*scatter.legend_elements(num=list(np.unique(ID))),
loc=\"center left\",
title=\'ID\',
bbox_to_anchor=(1, 0.5),
ncol=2
)
ax.ticklabel_format(useOffset=False)
ax.tick_params(axis = \'x\',labelrotation = 45)
plt.tight_layout()
# call the event
fig.canvas.mpl_connect(\'pick_event\', onpick)
散点图:
点击时的当前输出:
我希望它打印如下内容:
x: [76.25650514] y: [59.85198124] ID: 11 # the corresponding legend label
我一直在网上搜索,找不到太多可以复制的内容。
标签: matplotlib event-handling picker