1

I am trying to make an interactive bar chart and cannot figure out how to label the boxes. Given a histogram I would like to have it so when the cursor is over the bar the height, or whatever label I want, is displayed. The following code displays the chart but with no labels:

hist, bins = np.histogram(df.PER, bins=15)
width = 1 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2

fig, ax = plt.subplots()
boxes = ax.bar(center, hist, align='center', width=width,alpha=0.7,facecolor="red",edgecolor='w')

tooltip = mpld3.plugins.PointHTMLTooltip(boxes[0],labels=bins.tolist(),
                                   voffset=10, hoffset=10)
mpld3.plugins.connect(fig, tooltip)

mpld3.display()

where df.PER is the data from here:

0      35.47
1      31.27
2      30.64
3      26.92
4      26.71
5      26.49
6      26.45
7      26.21
8      26.17
9      25.85
10     25.48
11     25.34
12     24.64
13     24.32
14     23.46
15     23.42
16     23.37
17     22.76
18     22.45
19     22.45
20     22.43
21     22.10
22     21.99
23     21.82
24     21.62
25     21.44
26     21.31
27     21.26
28     21.26
29     20.87

Any suggestions?

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
superhero
  • 185
  • 3
  • 16

1 Answers1

2

For me, your code creates a tooltip label for the first bar in the bar chart. You can use a loop to get the rest:

for i, box in enumerate(boxes.get_children()):
    tooltip = mpld3.plugins.LineLabelTooltip(box, label=bins[i])
    mpld3.plugins.connect(fig, tooltip)

Here is a notebook showing the results in context.

This is a feature that has been requested previously, and would be nice to offer more directly, e.g. as mpld3.plugins.BarTooltip; patches welcome!

Abraham D Flaxman
  • 2,969
  • 21
  • 39