如何在 matplotlib 中使用带有堆叠条的 mplcursors

问题描述 投票:0回答:1

我正在尝试使用 matplotlib 创建一个堆积条,但无法使用 mplcursors。 当我运行程序时,如果我使用(没有 [sel.index]),似乎所有条形图都显示最后一个人的最后数据:

info.connect("add", lambda sel: sel.annotation.set_text(dict[nameList[i]][2]))

如果我使用:

info.connect("add", lambda sel: sel.annotation.set_text(dict[nameList[i]][2][sel.index]))

然后,当我将鼠标悬停在条形图上时,错误列表索引超出范围。 这是我到目前为止所拥有的。任何帮助将不胜感激。

import matplotlib.pyplot as plt
import mplcursors


dict = {'Tom': ([10, 20, 40], [0, 15, 40], [1, 2, 3]),
        'John': ([10, 20], [0, 12], [5, 6]),
        'Tim': ([10], [0], [7])}
nameList = ['Tom', 'John', 'Tim']
y_pos = range(len(nameList))
for i in range(len(nameList)):
  bar = plt.bar(y_pos[i], height=dict[nameList[i]][0], width=0.1, bottom=dict[nameList[i]][1])
  info= mplcursors.cursor(bar, hover=True)
  # info.connect("add", lambda sel: sel.annotation.set_text(dict[nameList[i]][2][sel.index]))
  info.connect("add", lambda sel: sel.annotation.set_text(dict[nameList[i]][2]))
plt.xticks(y_pos, nameList, rotation=90)
plt.show()
python matplotlib
1个回答
0
投票

lambda 函数中 i 变量的范围存在问题

data_dict = {'Tom': ([10, 20, 40], [0, 15, 40], [1, 2, 3]),
             'John': ([10, 20], [0, 12], [5, 6]),
             'Tim': ([10], [0], [7])}
nameList = ['Tom', 'John', 'Tim']
y_pos = range(len(nameList))

def create_bar_and_cursor(index, name, data):
    bar = plt.bar(y_pos[index], height=data[0], width=0.1, bottom=data[1])
    info = mplcursors.cursor(bar, hover=True)
    info.connect("add", lambda sel: sel.annotation.set_text(data[2]))
    return bar

for i, name in enumerate(nameList):
    create_bar_and_cursor(i, name, data_dict[name])

plt.xticks(y_pos, nameList, rotation=90)
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.