我正在尝试使用 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()
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()
• 将 2 个 y 值堆叠到堆叠条形图中,在 R 中使用误差条
• 如何用matplotlib ArtistAnimation绘制直方图或条形动画?
• 如何用matplotlib ArtistAnimation绘制直方图或条形动画?
• 带垂直线的图例
• 如何在 python 中使用 matplotlib 绘制 Quarto 棋盘游戏?
• 我如何使用 matplotlib 从随机生成的列表中创建条形图?
• 如何阻止 matplotlib 在垂直渐近线处错误地添加线条?
• 如何在 seaborn/matplotlib 中绘制带双轴的闪避条形图