.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "examples/bar.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_examples_bar.py: Display a bar's height and name on top of it upon hovering ========================================================== Using an event handler to change the annotation text and position. .. GENERATED FROM PYTHON SOURCE LINES 7-29 .. image-sg:: /examples/images/sphx_glr_bar_001.png :alt: Hover over a bar :srcset: /examples/images/sphx_glr_bar_001.png :class: sphx-glr-single-img .. code-block:: Python import string import matplotlib.pyplot as plt import mplcursors fig, ax = plt.subplots() ax.bar(range(9), range(1, 10), align="center") labels = string.ascii_uppercase[:9] ax.set(xticks=range(9), xticklabels=labels, title="Hover over a bar") # With HoverMode.Transient, the annotation is removed as soon as the mouse # leaves the artist. Alternatively, one can use HoverMode.Persistent (or True) # which keeps the annotation until another artist gets selected. cursor = mplcursors.cursor(hover=mplcursors.HoverMode.Transient) @cursor.connect("add") def on_add(sel): x, y, width, height = sel.artist[sel.index].get_bbox().bounds sel.annotation.set(text=f"{x+width/2}: {height}", position=(0, 20), anncoords="offset points") sel.annotation.xy = (x + width / 2, y + height) plt.show() .. _sphx_glr_download_examples_bar.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: bar.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: bar.py ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_