Matplotlib鼠标单击获取yticklabel

时间:2019-02-18 14:47:49

标签: matplotlib

我有一个非常简单的水平条形图。 (bar) 我想做的是单击栏时打印yticklabel。这有可能吗?

假设我有以下代码

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


plt.rcdefaults()
fig, ax = plt.subplots()

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center',
        color='green', ecolor='black')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()

我想要做的就是每当单击图表上的对应条时打印“ Jim”。

1 个答案:

答案 0 :(得分:0)

您可能想在picker中定义一个bar。然后将pick_event连接到一个函数,该函数在您提供的刻度标签列表中找到对应条形的索引。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center',
        color='green', ecolor='black', picker=True)
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

def onpick(event):
    if isinstance(event.artist, plt.Rectangle):
        y = people[int(np.round(event.artist.get_y()))]
        print(y)

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

plt.show()