### Basic Interactive Cursor Example Source: https://github.com/anntzer/mplcursors/blob/main/doc/source/index.rst Demonstrates how to initialize a cursor on Matplotlib artists to enable interactive data selection and annotation. ```python 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.\nAnnotations can be dragged.") mplcursors.cursor(lines) plt.show() ``` -------------------------------- ### Install mplcursors Source: https://github.com/anntzer/mplcursors/blob/main/doc/source/index.rst Commands to install the mplcursors package from PyPI or directly from the GitHub repository. ```shell pip install mplcursors pip install git+https://github.com/anntzer/mplcursors ``` -------------------------------- ### Global Environment Variable Activation Source: https://context7.com/anntzer/mplcursors/llms.txt Configures mplcursors globally using environment variables and Matplotlib figure hooks for automatic installation. ```python import matplotlib as mpl mpl.rcParams["figure.hooks"].append("mplcursors:install") ``` -------------------------------- ### Configure Cursor class with advanced options Source: https://context7.com/anntzer/mplcursors/llms.txt Shows how to instantiate the Cursor class directly to control selection behavior, highlighting, custom key bindings, and annotation styling. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors x = np.linspace(0, 10, 100) fig, ax = plt.subplots() # Plot multiple lines lines = [] for i in range(1, 10): line, = ax.plot(x, i * x, label=f"y = {i}x") lines.append(line) # Create cursor with multiple options cursor = mplcursors.Cursor( lines, multiple=True, highlight=True, hover=False, bindings={ "select": 1, "deselect": 3, "toggle_enabled": "e", "toggle_visible": "v", }, annotation_kwargs=dict( bbox=dict(boxstyle="round,pad=.5", fc="yellow", alpha=0.5), arrowprops=dict(arrowstyle="->", connectionstyle="arc3"), ), highlight_kwargs=dict(color="red", linewidth=3), ) plt.show() ``` -------------------------------- ### Runtime Cursor Control and Properties Source: https://context7.com/anntzer/mplcursors/llms.txt Illustrates how to access cursor properties and manipulate state at runtime, such as enabling/disabling the cursor or clearing selections via keyboard events. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors fig, ax = plt.subplots() lines = ax.plot(np.random.rand(10, 3)) ax.set_title("Cursor control demonstration") cursor = mplcursors.cursor(lines, multiple=True) print(f"Selectable artists: {cursor.artists}") print(f"Cursor enabled: {cursor.enabled}") print(f"Annotations visible: {cursor.visible}") def toggle_cursor(event): if event.key == "d": cursor.enabled = not cursor.enabled elif event.key == "c": for sel in list(cursor.selections): cursor.remove_selection(sel) elif event.key == "r": cursor.remove() fig.canvas.mpl_connect("key_press_event", toggle_cursor) plt.show() ``` -------------------------------- ### mplcursors Highlighting: Automatic and Manual Methods Source: https://context7.com/anntzer/mplcursors/llms.txt Shows how to enable automatic highlighting of selected artists in mplcursors using the 'highlight=True' option. It also demonstrates manual highlighting by creating paired artists and customizing highlight styles using 'highlight_kwargs'. This visually emphasizes the selected data points or lines. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors fig, axes = plt.subplots(1, 2, figsize=(10, 4)) # Automatic highlighting x = np.linspace(0, 10, 100) for i in range(1, 6): axes[0].plot(x, i * np.sin(x / i), label=f"Line {i}") axes[0].set_title("Automatic highlight (highlight=True)") mplcursors.cursor(axes[0], highlight=True, highlight_kwargs={ "color": "yellow", "linewidth": 4, "markeredgecolor": "yellow", "markeredgewidth": 3, }) # Manual highlighting with paired artists lines_ax1 = [] points_ax1 = [] for i in range(5): line, = axes[1].plot(np.random.rand(10), label=f"Series {i}") lines_ax1.append(line) axes[1].set_title("Manual paired highlighting") cursor2 = mplcursors.cursor(lines_ax1, highlight=True) @cursor2.connect("add") def on_add(sel): # Add custom text showing the line label sel.annotation.set_text(sel.artist.get_label()) plt.tight_layout() plt.show() ``` -------------------------------- ### Connecting Callbacks with Decorator and Direct Syntax in mplcursors Source: https://context7.com/anntzer/mplcursors/llms.txt Demonstrates how to connect callback functions to mplcursors events using both the @cursor.connect decorator and direct cursor.connect() method. It shows how to access selection properties like index, target, and artist, and how to customize annotation text and appearance. ```python import matplotlib.pyplot as plt import mplcursors # Assume 'cursor' and 'labels' are defined elsewhere # cursor = mplcursors.cursor() # labels = [...] @cursor.connect("add") def on_add(sel): # Access selection properties idx = sel.index # Index of selected point target = sel.target # (x, y) coordinates artist = sel.artist # The selected artist # Customize annotation text sel.annotation.set_text(f"{labels[int(idx)]}\nx={target[0]:.2f}, y={target[1]:.2f}") # Customize annotation appearance sel.annotation.get_bbox_patch().set(fc="lightblue", alpha=0.8) def on_remove(sel): print(f"Removed annotation at index {sel.index}") cursor.connect("remove", on_remove) plt.show() ``` -------------------------------- ### Enable Multiple Annotations with mplcursors Source: https://context7.com/anntzer/mplcursors/llms.txt Demonstrates how to enable multiple annotations simultaneously using the `multiple=True` option in `mplcursors.cursor`. Each click adds a new annotation, and annotations can be made non-draggable. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors data = np.outer(range(10), range(1, 5)) fig, ax = plt.subplots() ax.plot(data) ax.set_title("Click multiple points to add annotations\nRight-click to remove") # Enable multiple annotations and make them non-draggable cursor = mplcursors.cursor(multiple=True) @cursor.connect("add") def on_add(sel): # Make annotation non-draggable sel.annotation.draggable(False) # Add point number to text n_selections = len(cursor.selections) sel.annotation.set_text(f"#{n_selections}\n{sel.annotation.get_text()}") plt.show() ``` -------------------------------- ### Configure mplcursors via Environment and Hooks Source: https://context7.com/anntzer/mplcursors/llms.txt Shows how to programmatically configure cursor behavior using environment variables and Matplotlib figure hooks. This allows for fine-grained control over hover and highlighting features. ```python import os import matplotlib as mpl os.environ["MPLCURSORS"] = '{"hover": 1, "highlight": true}' mpl.rcParams["figure.hooks"].append("mplcursors:install") ``` -------------------------------- ### Programmatic Selection with select_at Source: https://context7.com/anntzer/mplcursors/llms.txt Shows how to trigger a cursor selection at specific data coordinates programmatically. This is useful for automated testing or pre-selecting data points. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors fig, ax = plt.subplots() x = np.linspace(0, 10, 50) y = np.sin(x) line, = ax.plot(x, y, "o-") ax.set_title("Programmatic selection at x=5") cursor = mplcursors.cursor(line) @cursor.connect("add") def on_add(sel): sel.annotation.set_text(f"Selected at\nx={sel.target[0]:.2f}\ny={sel.target[1]:.2f}") fig.canvas.draw() selection = cursor.select_at(ax, (5, np.sin(5))) plt.show() ``` -------------------------------- ### Exploring Selection Object Properties in mplcursors Source: https://context7.com/anntzer/mplcursors/llms.txt Illustrates how to use mplcursors to inspect and utilize the properties of the Selection object. This includes accessing the artist, target coordinates, point index, distance from click, annotation object, and extra artists. It also shows how to modify the annotation text using this data. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors fig, ax = plt.subplots() x = np.linspace(0, 2*np.pi, 50) y = np.sin(x) line, = ax.plot(x, y, "o-", label="sin(x)") cursor = mplcursors.cursor(line) @cursor.connect("add") def inspect_selection(sel): # Selection fields demonstration print(f"Artist: {sel.artist}") print(f"Target (x, y): {sel.target}") print(f"Index: {sel.index}") print(f"Distance from click: {sel.dist}") print(f"Annotation object: {sel.annotation}") print(f"Extra artists: {sel.extras}") # Modify annotation using selection data idx = int(sel.index) sel.annotation.set_text( f"Point #{idx}\n" f"x = {sel.target[0]:.3f}\n" f"y = {sel.target[1]:.3f}" ) plt.show() ``` -------------------------------- ### Decorator for Callback Registration Source: https://github.com/anntzer/mplcursors/blob/main/doc/source/index.rst Shows an alternative method for registering callback functions using a decorator syntax. This approach achieves the same result as the `connect` method but can be more concise for simple callbacks. ```python @cursor.connect("add") def on_add(sel): sel.extras.append(cursor.add_highlight(pairs[sel.artist])) ``` -------------------------------- ### connect Method - Event Callbacks Source: https://context7.com/anntzer/mplcursors/llms.txt The `connect` method allows you to register callback functions that are executed when a data point is selected or deselected, enabling custom annotation logic. ```APIDOC ## connect Method for Event Callbacks ### Description Registers callback functions to be executed when selection events occur (e.g., a point is added or removed). These callbacks receive a `Selection` object, allowing for dynamic modification of annotation text, position, and appearance. ### Method `cursor.connect(event, callback)` ### Parameters - **event** (str): The type of event to connect to. Common events include `"add"` (when a selection is made) and `"remove"` (when a selection is cleared). - **callback** (function): The function to be called when the specified event occurs. The callback function receives a `Selection` object as its argument. ### Usage The `connect` method can be used directly or as a decorator. ### Request Example ```python import matplotlib.pyplot as plt import numpy as np import mplcursors labels = ["Point A", "Point B", "Point C", "Point D", "Point E"] x = np.array([0, 1, 2, 3, 4]) y = np.array([1, 4, 2, 5, 3]) fig, ax = plt.subplots() line, = ax.plot(x, y, "ro-", markersize=10) ax.set_title("Click on a point to see its label") cursor = mplcursors.cursor(line) @cursor.connect("add") def on_add(selection): # Modify the annotation text based on the selected point's index selection.annotation.set_text(f"Custom Label: {labels[selection.index]}") # You can also modify position, appearance, etc. selection.annotation.set_bbox( dict(boxstyle="round,pad=.5", fc="lightblue", alpha=0.7) ) plt.show() ``` ### Response - **None**: The `connect` method modifies the cursor's behavior by registering callbacks. ``` -------------------------------- ### Customize Keyboard Bindings for mplcursors Source: https://context7.com/anntzer/mplcursors/llms.txt Demonstrates how to remap cursor interaction keys using the bindings parameter. This allows users to define custom triggers for selection, navigation, and visibility toggles. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors fig, ax = plt.subplots() x = np.linspace(0, 10, 100) ax.plot(x, np.sin(x), "o-", markersize=4) ax.set_title("Custom bindings:\n't' = toggle cursor | 'h' = hide/show annotations\nShift+arrows = navigate points | Ctrl+click = select") cursor = mplcursors.cursor(bindings={ "select": {"button": 1, "key": "control"}, "deselect": 3, "left": "shift+left", "right": "shift+right", "toggle_enabled": "t", "toggle_visible": "h", }) plt.show() ``` -------------------------------- ### Customizing Annotation Text with Callbacks Source: https://github.com/anntzer/mplcursors/blob/main/doc/source/index.rst Demonstrates how to connect a callback function to the 'add' event to customize the annotation text based on the selected point's index. This allows for dynamic labeling of selected data points. ```python 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])) ``` -------------------------------- ### Global Activation via Environment Variable Source: https://github.com/anntzer/mplcursors/blob/main/doc/source/index.rst Configures mplcursors globally by setting the MPLCURSORS environment variable and using Matplotlib figure hooks. ```shell MPLCURSORS={} python foo.py MPLCURSORS='{"hover": 1}' python foo.py ``` -------------------------------- ### Integrate mplcursors with Pandas DataFrames Source: https://context7.com/anntzer/mplcursors/llms.txt Demonstrates how to use the selection index to retrieve and display rich information from a Pandas DataFrame within cursor annotations. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors from pandas import DataFrame df = DataFrame({ "Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"], "Age": [25, 30, 35, 28, 32], "Salary": [50000, 65000, 75000, 55000, 70000], "Experience": [2, 5, 10, 4, 7], }) fig, ax = plt.subplots(figsize=(8, 6)) scatter = ax.scatter(df["Experience"], df["Salary"], c=df["Age"], s=150) cursor = mplcursors.cursor(scatter, hover=mplcursors.HoverMode.Transient) @cursor.connect("add") def show_employee_info(sel): row = df.iloc[sel.index] sel.annotation.set_text(f"Name: {row['Name']}\nAge: {row['Age']}") plt.show() ``` -------------------------------- ### Create interactive cursor with convenience function Source: https://context7.com/anntzer/mplcursors/llms.txt Demonstrates how to use the mplcursors.cursor() function to enable interactive data selection on specific Matplotlib artists or entire figures. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors # Create sample data and plot data = np.outer(range(10), range(1, 5)) fig, ax = plt.subplots() lines = ax.plot(data) ax.set_title("Click on a line to see coordinates") # Create cursor for specific artists cursor = mplcursors.cursor(lines) plt.show() ``` -------------------------------- ### Customize Annotation Appearance with mplcursors Source: https://context7.com/anntzer/mplcursors/llms.txt Illustrates how to customize the appearance of annotations using `annotation_kwargs` and callback functions. This includes changing box styles, colors, arrow properties, and positioning. ```python import matplotlib.pyplot as plt import numpy as np from matplotlib.patheffects import withSimplePatchShadow import mplcursors fig, axes = plt.subplots(1, 3, figsize=(12, 4)) # Style 1: Custom box with shadow x = np.linspace(0, 10, 50) axes[0].plot(x, np.sin(x), "b-", linewidth=2) axes[0].set_title("Shadow effect") c1 = mplcursors.cursor(axes[0], annotation_kwargs=dict( bbox=dict( boxstyle="round,pad=0.5", facecolor="white", edgecolor="#333", linewidth=1, path_effects=[withSimplePatchShadow(offset=(2, -2))], ), arrowprops=dict(arrowstyle="->", color="gray"), )) # Style 2: No box, custom position axes[1].plot(x, np.cos(x), "r-", linewidth=2) axes[1].set_title("No box, offset position") c2 = mplcursors.cursor(axes[1]) @c2.connect("add") def style_no_box(sel): sel.annotation.set(position=(15, -15)) sel.annotation.set_bbox(None) # Style 3: Fancy arrow axes[2].plot(x, np.tan(x/3), "g-", linewidth=2) axes[2].set_title("Fancy arrow style") axes[2].set_ylim(-3, 3) c3 = mplcursors.cursor(axes[2]) @c3.connect("add") def style_fancy(sel): sel.annotation.get_bbox_patch().set(fc="lightyellow", ec="orange", lw=2) sel.annotation.arrow_patch.set(arrowstyle="fancy", fc="orange", alpha=0.5) plt.tight_layout() plt.show() ``` -------------------------------- ### Cursor Class Constructor Source: https://context7.com/anntzer/mplcursors/llms.txt The `Cursor` class provides detailed control over the interactive selection behavior, including highlighting, hover modes, key bindings, and annotation styling. ```APIDOC ## Cursor Class Constructor ### Description Initializes a `Cursor` object to manage interactive data selection. It accepts artists and various configuration options to customize selection, highlighting, hover behavior, key bindings, and annotation appearance. ### Method `mplcursors.Cursor(artists, **kwargs)` ### Parameters - **artists**: A list of artists or a single artist to make selectable. - **multiple** (bool): Allow multiple annotations to be displayed simultaneously. Defaults to `False`. - **highlight** (bool): Highlight the selected artist. Defaults to `False`. - **hover** (`HoverMode` or bool): Enable selection on hover. Can be `HoverMode.NoHover` (click), `HoverMode.Persistent` (hover annotation remains), or `HoverMode.Transient` (hover annotation disappears when mouse leaves). Defaults to `HoverMode.NoHover`. - **bindings** (dict): Customize keyboard shortcuts for actions like selecting, deselecting, enabling/disabling, and toggling visibility. - **annotation_kwargs** (dict): Keyword arguments passed to the annotation object for styling. - **highlight_kwargs** (dict): Keyword arguments passed to the artist highlighting for styling. ### Request Example ```python import matplotlib.pyplot as plt import numpy as np import mplcursors x = np.linspace(0, 10, 100) fig, ax = plt.subplots() # Plot multiple lines lines = [] for i in range(1, 10): line, = ax.plot(x, i * x, label=f"y = {i}x") lines.append(line) # Create cursor with multiple options cursor = mplcursors.Cursor( lines, multiple=True, highlight=True, hover=False, bindings={ "select": 1, # Left mouse button to select "deselect": 3, # Right mouse button to deselect "toggle_enabled": "e", # 'e' to enable/disable "toggle_visible": "v", # 'v' to show/hide annotations }, annotation_kwargs=dict( bbox=dict(boxstyle="round,pad=.5", fc="yellow", alpha=0.5), arrowprops=dict(arrowstyle="->", connectionstyle="arc3"), ), highlight_kwargs=dict(color="red", linewidth=3), ) plt.show() ``` ### Response - **Cursor Instance**: A configured `mplcursors.Cursor` object. ``` -------------------------------- ### Enable Interactive Cursors in Matplotlib Source: https://context7.com/anntzer/mplcursors/llms.txt Demonstrates how to initialize a Matplotlib plot with automatic cursor support. This approach is suitable for quick exploratory analysis. ```python import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() ax.plot(np.sin(np.linspace(0, 10, 100))) ax.set_title("Cursor automatically enabled via environment") plt.show() ``` -------------------------------- ### Annotate Image Pixels with Custom Extent Source: https://context7.com/anntzer/mplcursors/llms.txt Demonstrates how to use mplcursors to annotate individual pixels in an image displayed with a custom extent. It shows how to access pixel coordinates and values for display in the annotation. ```python import matplotlib.pyplot as plt import mplcursors # Assuming 'data' is a numpy array and 'axes' is a list of matplotlib axes # For example: # fig, axes = plt.subplots(1, 2) # data = np.random.rand(10, 10) im2 = axes[1].imshow(data, origin="upper", extent=[0, 10, 0, 5], cmap="plasma") axes[1].set_title("origin='upper', custom extent") plt.colorbar(im2, ax=axes[1]) cursor = mplcursors.cursor() @cursor.connect("add") def on_add(sel): # For images, index is (y, x) tuple y_idx, x_idx = sel.index value = sel.artist.get_array()[y_idx, x_idx] sel.annotation.set_text( f"Pixel: ({x_idx}, {y_idx})\n" f"Value: {value:.2f}" ) plt.tight_layout() plt.show() ``` -------------------------------- ### Cursor Class Source: https://github.com/anntzer/mplcursors/blob/main/doc/source/mplcursors.rst Details about the Cursor class, its members, and initialization. ```APIDOC ## Cursor Class ### Description The Cursor class is the primary object for managing interactive annotations and selections within a Matplotlib plot. ### Members - **__init__**: Initializes a Cursor object. - Other members related to cursor behavior and properties (refer to specific method documentation for details). ``` -------------------------------- ### mplcursors API Overview Source: https://github.com/anntzer/mplcursors/blob/main/doc/source/mplcursors.rst This section provides an overview of the main components available in the mplcursors API. ```APIDOC ## mplcursors API ### Description The mplcursors API provides tools for interactive data exploration in Matplotlib plots. ### Core Components - **Cursor**: Represents a cursor object for interactive annotation. - **cursor**: A function to create and manage cursor instances. - **HoverMode**: Defines the mode for hovering interactions. - **Selection**: Represents a selected data point. ### Utility Functions - **compute_pick**: Computes pick information. - **get_ann_text**: Retrieves annotation text. - **move**: Moves the cursor. - **make_highlight**: Makes an element highlighted. ``` -------------------------------- ### Setting Status Bar Text from Callbacks Source: https://github.com/anntzer/mplcursors/blob/main/doc/source/index.rst Illustrates how to update the status bar text when a point is selected. It includes clearing the status bar on mouse motion and setting a custom message based on the annotation text when a selection is made. ```python 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", "; "))) ``` -------------------------------- ### Utility Functions Source: https://github.com/anntzer/mplcursors/blob/main/doc/source/mplcursors.rst Documentation for utility functions provided by the mplcursors API. ```APIDOC ## Utility Functions ### compute_pick #### Description Computes pick information for interactive events. ### get_ann_text #### Description Retrieves the text content for an annotation. ### move #### Description Moves the cursor to a specified position. ### make_highlight #### Description Applies highlighting to a plot element. ``` -------------------------------- ### Scatter Plot Highlighting with mplcursors Source: https://context7.com/anntzer/mplcursors/llms.txt Shows how to use mplcursors to highlight individual points in both simple and colormapped scatter plots. The annotation automatically includes point coordinates and, for colormapped plots, the color value. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors np.random.seed(42) n_points = 50 fig, axes = plt.subplots(1, 2, figsize=(10, 4)) # Simple scatter plot x1, y1 = np.random.rand(2, n_points) * 10 axes[0].scatter(x1, y1, s=100, alpha=0.7) axes[0].set_title("Simple scatter - click points") # Colormapped scatter plot with sizes x2 = np.random.rand(n_points) * 10 y2 = np.random.rand(n_points) * 10 colors = np.random.rand(n_points) * 100 sizes = np.random.rand(n_points) * 200 + 50 sc = axes[1].scatter(x2, y2, c=colors, s=sizes, cmap="coolwarm", alpha=0.7) axes[1].set_title("Colormapped scatter") plt.colorbar(sc, ax=axes[1], label="Value") # Point-by-point highlighting for scatter plots cursor = mplcursors.cursor(highlight=True) @cursor.connect("add") def on_add(sel): idx = sel.index x, y = sel.target sel.annotation.set_text(f"Point {idx}\nx={x:.2f}\ny={y:.2f}") plt.tight_layout() plt.show() ``` -------------------------------- ### Control hover behavior with HoverMode Source: https://context7.com/anntzer/mplcursors/llms.txt Illustrates the use of the HoverMode enum to configure how annotations appear and persist when interacting with plot elements. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors np.random.seed(42) fig, axes = plt.subplots(1, 3, figsize=(12, 4)) # NoHover mode (default) - requires clicking axes[0].scatter(*np.random.random((2, 20))) axes[0].set_title("NoHover (click to select)") mplcursors.cursor(axes[0], hover=mplcursors.HoverMode.NoHover) # Persistent hover - annotation stays after mouse leaves axes[1].scatter(*np.random.random((2, 20))) axes[1].set_title("Persistent hover") mplcursors.cursor(axes[1], hover=mplcursors.HoverMode.Persistent) # Transient hover - annotation disappears when mouse leaves axes[2].scatter(*np.random.random((2, 20))) axes[2].set_title("Transient hover") mplcursors.cursor(axes[2], hover=mplcursors.HoverMode.Transient) plt.tight_layout() plt.show() ``` -------------------------------- ### cursor Function - Create Cursor Source: https://context7.com/anntzer/mplcursors/llms.txt The `cursor` function is a convenience utility to create a Cursor instance for specified artists, containers, or axes. If no arguments are provided, it makes all artists on all pyplot-tracked figures selectable. ```APIDOC ## cursor Function ### Description Creates a Cursor for a list of artists, containers, and axes. Accepts pickable objects and returns a configured Cursor instance. When called without arguments, it makes all artists on all pyplot-tracked figures selectable. ### Method `mplcursors.cursor(*args, **kwargs)` ### Parameters - `*args`: Pickable objects (artists, containers, axes, figures) to make selectable. - `**kwargs`: Additional keyword arguments passed to the `Cursor` constructor. ### Request Example ```python import matplotlib.pyplot as plt import numpy as np import mplcursors # Create sample data and plot data = np.outer(range(10), range(1, 5)) fig, ax = plt.subplots() lines = ax.plot(data) ax.set_title("Click on a line to see coordinates") # Create cursor for specific artists cursor = mplcursors.cursor(lines) # Alternative: make all artists in figure selectable # mplcursors.cursor() # Alternative: make all artists in specific axes selectable # mplcursors.cursor(ax) plt.show() ``` ### Response - **Cursor Instance**: A configured `mplcursors.Cursor` object. ``` -------------------------------- ### HoverMode Class Source: https://github.com/anntzer/mplcursors/blob/main/doc/source/mplcursors.rst Details about the HoverMode class and its members. ```APIDOC ## HoverMode Class ### Description The HoverMode class defines different strategies for handling cursor interactions when hovering over plot elements. ### Members - Members related to hover interaction modes and configurations. ``` -------------------------------- ### Selection Class Source: https://github.com/anntzer/mplcursors/blob/main/doc/source/mplcursors.rst Details about the Selection class and its members. ```APIDOC ## Selection Class ### Description The Selection class represents a data point or region that has been selected by the user. ### Members - Members related to the properties and information of a selection. ``` -------------------------------- ### mplcursors Support for Bar Charts with BarContainer Source: https://context7.com/anntzer/mplcursors/llms.txt Explains how mplcursors integrates with Matplotlib's BarContainer objects for interactive bar charts. It shows how to access individual bar properties using 'sel.artist[sel.index]' and customize annotations to display category and value information, positioning them above the bars. ```python import matplotlib.pyplot as plt import string import mplcursors fig, ax = plt.subplots() # Create bar chart categories = list(string.ascii_uppercase[:8]) values = [23, 45, 56, 78, 32, 89, 12, 67] bars = ax.bar(categories, values, color="steelblue") ax.set_title("Hover over bars to see values") ax.set_ylabel("Value") # Use transient hover for bar charts cursor = mplcursors.cursor(hover=mplcursors.HoverMode.Transient) @cursor.connect("add") def on_add(sel): # Get the bar rectangle at the selected index bar = sel.artist[sel.index] x, y, width, height = bar.get_bbox().bounds # Position annotation above the bar sel.annotation.set( text=f"Category: {categories[sel.index]}\nValue: {int(height)}", position=(0, 10), anncoords="offset points" ) sel.annotation.xy = (x + width / 2, y + height) # Style the annotation sel.annotation.get_bbox_patch().set(fc="white", ec="gray", alpha=0.9) plt.show() ``` -------------------------------- ### HoverMode Enum Source: https://context7.com/anntzer/mplcursors/llms.txt The `HoverMode` enum defines different behaviors for selecting data points when the mouse hovers over them. ```APIDOC ## HoverMode Enum ### Description An enumeration that controls the behavior when the mouse hovers over selectable artists. It determines whether selections are made on click, persistent hover, or transient hover. ### Enum Values - **NoHover** (0): Selections are made only when the mouse is clicked on an artist. This is the default behavior. - **Persistent** (1): Annotations appear on hover and remain visible even after the mouse moves away from the artist. They persist until another selection is made or explicitly removed. - **Transient** (2): Annotations appear on hover and disappear automatically when the mouse cursor leaves the artist. ### Usage Can be used by passing the enum member or its integer value to the `hover` parameter of `mplcursors.cursor` or `mplcursors.Cursor`. ### Request Example ```python import matplotlib.pyplot as plt import numpy as np import mplcursors np.random.seed(42) fig, axes = plt.subplots(1, 3, figsize=(12, 4)) # NoHover mode (default) - requires clicking axes[0].scatter(*np.random.random((2, 20))) axes[0].set_title("NoHover (click to select)") mplcursors.cursor(axes[0], hover=mplcursors.HoverMode.NoHover) # Persistent hover - annotation stays after mouse leaves axes[1].scatter(*np.random.random((2, 20))) axes[1].set_title("Persistent hover") mplcursors.cursor(axes[1], hover=mplcursors.HoverMode.Persistent) # Equivalent: hover=True or hover=1 # Transient hover - annotation disappears when mouse leaves axes[2].scatter(*np.random.random((2, 20))) axes[2].set_title("Transient hover") mplcursors.cursor(axes[2], hover=mplcursors.HoverMode.Transient) # Equivalent: hover=2 plt.tight_layout() plt.show() ``` ### Response - **HoverMode**: The selected hover behavior for the cursor. ``` -------------------------------- ### mplcursors Support for Images (AxesImage) Source: https://context7.com/anntzer/mplcursors/llms.txt Details how mplcursors handles images plotted with 'imshow()'. For AxesImage objects, the selection index is a tuple (y, x) representing pixel coordinates. The default annotation displays the pixel value, and this snippet sets up a basic image plot for demonstration. ```python import matplotlib.pyplot as plt import numpy as np import mplcursors # Create sample image data data = np.random.rand(20, 20) * 100 fig, axes = plt.subplots(1, 2, figsize=(10, 4)) # Standard image im1 = axes[0].imshow(data, origin="lower", cmap="viridis") axes[0].set_title("origin='lower'") plt.colorbar(im1, ax=axes[0]) # Note: The rest of the image example code is missing from the input. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.