【问题标题】:Matplotlib - Stacked bar chart and tooltipMatplotlib - 堆叠条形图和工具提示
【发布时间】:2018-06-10 21:57:58
【问题描述】:

当鼠标悬停在条形图上时,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()

【问题讨论】:

  • 当您将鼠标悬停在栏的给定部分时,您的预期结果是什么?
  • @汤姆。我编辑了我的帖子以包含我想要实现的目标的插图。

标签: python matplotlib tooltip


【解决方案1】:

mpldatacursor 格式化程序的kwargs 包含矩形补丁的详细信息 - 具体来说,bottomleftheightwidth 等。在这种情况下,我们只需要知道其中矩形的底部是-如果是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])

这给出了这个结果:

【讨论】:

    猜你喜欢
    • 2019-10-03
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多