Skip to main content
 首页 » 编程设计

python之Matplotlib之堆积条形图和工具提示

2024年09月07日8webabcd

这code当鼠标悬停在条形图上时返回工具提示。我想在堆叠条形图的情况下修改代码,并在鼠标悬停在条形图的部分时获取该部分的特定工具提示。 我不知道如何相应地修改 formatter。

这里是我正在努力实现的一个例子。如果鼠标悬停在第三条的蓝色部分,工具提示将包含信息“ggg, hhh, iii”,如果鼠标悬停在第三条的绿色部分,工具提示将包含信息“555, 666”。

import numpy as np 
import matplotlib.pyplot as plt 
from mpldatacursor import datacursor 
 
attendance = [['aaa', 'bbb', 'ccc'], 
              ['ddd', 'eee', 'fff'], 
              ['ggg', 'hhh', 'iii'], 
              ['jjj', 'kkk', 'lll']] 
 
attendance2 = [['111', '222'], 
              ['333', '444'], 
              ['555', '666'], 
              ['777', '888']] 
 
x = range(len(attendance)) 
y = [10, 20, 30, 40] 
y2 = [5, 10, 15, 20] 
 
fig, ax = plt.subplots() 
ax.bar(x, y, align='center', bottom=0, color='lightblue') 
ax.bar(x, y2, align='center', bottom=y, color='lightgreen') 
ax.margins(0.05) 
ax.set_ylim(bottom=0) 
 
def formatter(**kwargs): 
    dist = abs(np.array(x) - kwargs['x']) 
    i = dist.argmin() 
    return '\n'.join(attendance[i]) 
 
datacursor(hover=True, formatter=formatter) 
plt.show() 

请您参考如下方法:

mpldatacursor 格式化程序的 kwargs 包含矩形补丁的详细信息 - 特别是 bottom、left , height, width 等。在这种情况下,我们只需要知道矩形的底部在哪里 - 如果它是 0,我们可以使用attendance来设置标签,否则我们要使用attendance2。

因此,您可以将 formatter 函数更改为:

def formatter(**kwargs): 
    dist = abs(np.array(x) - kwargs['x']) 
    i = dist.argmin() 
    labels = attendance if kwargs['bottom'] == 0 else attendance2 
    return '\n'.join(labels[i]) 

结果如下: