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()
the
kwargs
for thempldatacursor
formatter include details of the rectangle patch - specifically, thebottom
,left
,height
,width
, etc. In this case, we just need to know where the bottom of the rectangle is - if its0
, we can useattendance
to set the label, otherwise we want to useattendance2
.So, you can change your
formatter
function to:Which gives this result: