条形图的鼠标悬停事件

2024-10-02 00:37:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用matplotlib制作一个交互式绘图,在这里我可以点击条形图的索引。这样,我就可以使用索引访问存储在数组中的一些细节,并将其打印出来。我有一个下面的代码示例,可以用于线形图

    if isinstance(event.artist, Line2D):
        thisline = event.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()
        ind = event.ind
        print('onpick1 line:', np.column_stack([xdata[ind], ydata[ind]]))

但是,我无法为条形图获取任何此类索引/索引。附近有工作吗


Tags: 代码event绘图示例getartistmatplotlib数组
1条回答
网友
1楼 · 发布于 2024-10-02 00:37:58

这些条是单独的补丁。您可以从返回的列表中获取修补程序的索引

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.random.rand(len(x))
info = list("ABDCEFGHIJ")

bars = plt.bar(x,y, picker=True)

def on_pick(evt):
    ind = bars.index(evt.artist)
    print(ind, info[ind])

plt.gcf().canvas.mpl_connect("pick_event", on_pick)


plt.show()

相关问题 更多 >

    热门问题