A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mplcursors.readthedocs.io below:

mplcursors – Interactive data selection cursors for Matplotlib — mplcursors 0.6 documentation

mplcursors – Interactive data selection cursors for Matplotlib#

mplcursors provides interactive data selection cursors for Matplotlib. It is inspired from mpldatacursor, with a much simplified API.

mplcursors requires Matplotlib≥3.1.

Installation#

Pick one among:

$ pip install mplcursors  # from PyPI
$ pip install git+https://github.com/anntzer/mplcursors  # from Github
Basic example#

Basic examples work similarly to mpldatacursor:

import matplotlib.pyplot as plt
import numpy as np
import mplcursors

data = np.outer(range(10), range(1, 5))

fig, ax = plt.subplots()
lines = ax.plot(data)
ax.set_title("Click somewhere on a line.\nRight-click to deselect.\n"
             "Annotations can be dragged.")

mplcursors.cursor(lines)  # or just mplcursors.cursor()

plt.show()

The cursor convenience function makes a collection of artists selectable. Specifically, its first argument can either be a list of artists or axes (in which case all artists in each of the axes become selectable); or one can just pass no argument, in which case all artists in all figures become selectable. Other arguments (which are all keyword-only) allow for basic customization of the Cursor’s behavior; please refer to that class’ documentation.

Activation by environment variable#

It is possible to use mplcursors without modifying any source code: setting the MPLCURSORS environment variable to a JSON-encoded dict will patch Figure.draw to automatically call cursor (with the passed keyword arguments, if any) after the figure is drawn for the first time (more precisely, after the first draw that includes a selectable artist). Typical settings include:

$ MPLCURSORS={} python foo.py

and:

$ MPLCURSORS='{"hover": 1}' python foo.py

Note that this will only work if mplcursors has been installed, not if it is simply added to the PYTHONPATH.

Note that this will not pick up artists added to the figure after the first draw, e.g. through interactive callbacks.

Default UI#

These bindings are all customizable via Cursor’s bindings keyword argument. Note that the keyboard bindings are only active if the canvas has the keyboard input focus.

Customization#

Instead of providing a host of keyword arguments in Cursor’s constructor, mplcursors represents selections as Selection objects and lets you hook into their addition and removal.

Specifically, a Selection has the following fields:

The exact meaning of index depends on the selected artist:

(Note that although Selection is implemented as a namedtuple, only the field names should be considered stable API. The number and order of fields is subject to change with no notice.)

Thus, in order to customize, e.g., the annotation text, one can call:

lines = ax.plot(range(3), range(3), "o")
labels = ["a", "b", "c"]
cursor = mplcursors.cursor(lines)
cursor.connect(
    "add", lambda sel: sel.annotation.set_text(labels[sel.index]))

Whenever a point is selected (resp. deselected), the "add" (resp. "remove") event is triggered and the registered callbacks are executed, with the Selection as only argument. Here, the only callback updates the text of the annotation to a per-point label. (cursor.connect("add") can also be used as a decorator to register a callback, see below for an example.) For an example using pandas’ DataFrames, see Extracting data and labels from a DataFrame.

For additional examples of customization of the position and appearance of the annotation, see Display a bar’s height and name on top of it upon hovering and Changing properties of the popup.

Note

When the callback is fired, the position of the annotating text is temporarily set to (nan, nan). This allows us to track whether a callback explicitly sets this position, and, if none does, automatically compute a suitable position.

Likewise, if the text alignment is not explicitly set but the position is, then a suitable alignment will be automatically computed.

Callbacks can also be used to make additional changes to the figure when a selection occurs. For example, the following snippet (extracted from Linked artists) ensures that whenever an artist is selected, another artist that has been “paired” with it (via the pairs map) also gets selected:

@cursor.connect("add")
def on_add(sel):
    sel.extras.append(cursor.add_highlight(pairs[sel.artist]))

Note that the paired artist will also get de-highlighted when the “first” artist is deselected.

In order to set the status bar text from a callback, it may be helpful to clear it during “normal” mouse motion, e.g.:

fig.canvas.mpl_connect(
    "motion_notify_event",
    lambda event: fig.canvas.toolbar.set_message(""))
cursor = mplcursors.cursor(hover=True)
cursor.connect(
    "add",
    lambda sel: fig.canvas.toolbar.set_message(
        sel.annotation.get_text().replace("\n", "; ")))
Complex plots#

Some complex plots, such as contour plots, may be partially supported, or not at all. Typically, it is because they do not subclass Artist, and thus appear to cursor as a collection of independent artists (each contour level, in the case of contour plots).

It is usually possible, again, to hook the "add" signal to provide additional information in the annotation text. See Contour plots for an example.

Animations#

Matplotlib’s animation blitting mode assumes that the animation object is entirely in charge of deciding what artists to draw and when. In particular, this means that the animated property is set on certain artists. As a result, when mplcursors tries to blit an animation on top of the image, the animated artists will not be drawn, and disappear. More importantly, it also means that once an annotation is added, mplcursors cannot remove it (as it needs to know what artists to redraw to restore the original state).

As a workaround, either switch off blitting, or unset the animated property on the relevant artists before using a cursor. (The only other fix I can envision is to walk the entire tree of artists, record their visibility status, and try to later restore them; but this would fail for ArtistAnimations which themselves fiddle with artist visibility).

Indices and tables#

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4