Matplotlib - Stacked bar chart and tooltip

2019-07-13 05:51发布

问题:

This code returns a tooltip when the mouse hovers over a bar chart. I would like to modify the code in the case of a stacked bar chart and get a specific tooltip of the section when the mouse hovers the section of the bar chart. I can't figure out how to modify the formatter accordingly.

Here an illustration of what I am trying to achieve. If the mouse hovers the blue section of the third bar, the tooltip will contain the information "ggg, hhh, iii" and if the mouse hovers the green section of the third bar, the tooltip will contain the information "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()

回答1:

the kwargs for the mpldatacursor formatter include details of the rectangle patch - specifically, the bottom, left, height, width, etc. In this case, we just need to know where the bottom of the rectangle is - if its 0, we can use attendance to set the label, otherwise we want to use attendance2.

So, you can change your formatter function to:

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])

Which gives this result: