0

I created this tree map using Matplotlib and Squarify. Is there a way to display information about each axes when the mouse hovers over the axis?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
drkyeh
  • 15
  • 1
  • 6

1 Answers1

1

The mplcursors library can be used to create custom annotations while hovering. Here is an example with a tree map:

import matplotlib.pyplot as plt
import matplotlib as mpl
import squarify
import mplcursors

sizes = [5, 20, 30, 25, 10, 12]
sumsizes = sum(sizes)
labels = ['A', 'B', 'C', 'D', 'E', 'F']

cmap = plt.cm.get_cmap('Greens')
norm = plt.Normalize(vmin=min(sizes), vmax=max(sizes))
colors = [cmap(norm(s)) for s in sizes]
squarify.plot(sizes=sizes, label=labels, color=colors)
plt.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=norm))

cursor = mplcursors.cursor(hover=True)
cursor.connect("add", lambda sel: sel.annotation.set_text(
    f"ID:{sel.target.index} '{labels[sel.target.index]}'\nSize:{sizes[sel.target.index]} ({sizes[sel.target.index] * 100.0 / sumsizes:.1f} %)"))

plt.show()

resulting plot

JohanC
  • 71,591
  • 8
  • 33
  • 66