【问题标题】:Picker Event to display legend labels in matplotlib在 matplotlib 中显示图例标签的选取器事件
【发布时间】: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


    【解决方案1】:

    通常,获取单击点标签的方式是print(event.artist.get_label()),但使用自定义图例标签,唯一打印的是_child0。但是,由于您的自定义标签,您可以像使用 xy 变量一样使用变量 ID,例如print('id:', ID[ind])

    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(event.artist.get_label()) # How you normally get the legend label
        print('id:', ID[ind])           # How you can get your custom legend label
        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)
    plt.show()
    

    点击黄色最点给出:

    _child0
    id: [24]
    x: [84.73899472] y: [3.07532246]
    

    单击一个非常紫色的点会给出:

    _child0
    id: [2]
    x: [99.88397652] y: [98.89144833]
    

    【讨论】:

    • 关于同一主题,我还有另一个问题,这次数据是使用“.loc”从数据框中提取的。如果您有兴趣提供帮助,请也查看这个。谢谢! stackoverflow.com/questions/73356791/…
    猜你喜欢
    • 2017-03-03
    • 2019-02-27
    • 2015-12-03
    • 2021-05-14
    • 1970-01-01
    • 2018-03-25
    • 2017-04-28
    • 1970-01-01
    相关资源
    最近更新 更多