首页 > 解决方案 > Matplotlib - 堆叠条形图和工具提示

问题描述

当鼠标悬停在条形图上时,此代码返回工具提示。我想在堆积条形图的情况下修改代码,并在鼠标悬停在条形图的部分时获得该部分的特定工具提示。我不知道如何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()

标签: pythonmatplotlibtooltip

解决方案


格式化程序的包括矩形补丁的详细信息 - 具体来说,kwargs, , ,等。在这种情况下,我们只需要知道矩形的底部在哪里 - 如果是,我们可以使用它来设置标签,否则我们想用。mpldatacursorbottomleftheightwidth0attendanceattendance2

因此,您可以将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])

这给出了这个结果:

在此处输入图像描述

在此处输入图像描述


推荐阅读