mplcursors | Interactive data selection cursors for Matplotlib | Data Visualization library
kandi X-RAY | mplcursors Summary
kandi X-RAY | mplcursors Summary
Interactive data selection cursors for Matplotlib.
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
- Create a Cursor from a list of artists
- Removes a selection
- Remove this widget from the widget
- Iterate through axes
- Connect a callback to the specified event
- Return a list of lines from the artist
- Compute the pick position of the artist
- Untransform axes
- Compute pick support for artist
- Show hover panel
- Add a callback to the cursor
- Decorator to register axes
- Add a highlight
- Make highlight
- Handle pick event
- Handle key press event
- Add a selection annotation
- Add a highlight to the artist
- Get the parent axes of aoc
- Return the parent figure
- Shows on add
- Return the index of the target
- Register pth hook
- Checks if an artist is alive
- Called when the mouse button press is pressed
- Notify user about hover motion
- Mouse button press event
mplcursors Key Features
mplcursors Examples and Code Snippets
Community Discussions
Trending Discussions on mplcursors
QUESTION
I am currently adding patches on to an image and would like to annotate them with mplcursors.
However, I can't get mplcursors to selectively react to the drawn patches instead to the whole image (that is, each pixel): Here is a minimal working example that I am working on, any tips on how to solve this issue?
...ANSWER
Answered 2022-Mar-21 at 18:35ax.patches
is still empty if the cursor is created before adding the rectangle to the plot. So, it would help to call ax.add_patch(rect)
earlier. The annotation function has access to the properties of the selected element ("artist"), so you could e.g. add the information as a label. As mplcursors
doesn't seem to work for circles, you could create a regular polygon to approximate one.
QUESTION
I've been working on creating a matplotlib plot that you can dynamically adjust inside of a tkinter GUI. To change aspects of the chart such as the view frame I planned on using buttons that can change the number of candles shown, and what candles are shown in a given dataset. My code is not refractored since I've been changing many things on it but it is pasted below.
...ANSWER
Answered 2022-Jan-12 at 08:12You have overwritten function loadChart()
by the following line:
QUESTION
I'm using matplotlib to make step graphs based on a dataframe, but I want one of the key/value of the dataframe to appear (signals_df['Gage']
), instead of coordinates as annotation, but I always get the error: AttributeError: 'Line2D' object has no attribute 'get_offsets'
when I click on the first subplot from bottom to top and the annotation does not appear. In fact, I commented out the annot.set_visible(False)
and replaced the ""
of the examples with val_gage
, so that it will look like I want the annotation to appear one by one, when clicking on some point within the subplots.
This is the code in question:
ANSWER
Answered 2021-Nov-04 at 11:07Without knowing much about the libraries you are using I can see you are creating these annotation objects and then assigning them to a global variable that is re-assigned later and thus you lose the right object to make it visible.
Instead you could keep the annotation objects into a dictionary and try to retrieve them later when you need them based on an object.
I used a list to show you the idea, but you need a dictionary I guess to identify the right objects.
I modified your code a bit and it shows the desired behaviour if you resize the window...I guess you have to find a way to refresh the plot also:
QUESTION
I want to create a network where you can hover over each label to read it interactively.
I am using jupyter lab, specs are: Selected Jupyter core packages...
...ANSWER
Answered 2021-Oct-23 at 21:18The problem seems to be that G.nodes()
isn't a list of labels. You can get the node numbers or labels via converting it to a list (list(G.nodes())
).
An updated version could look like:
QUESTION
import pandas as pd
import matplotlib.pyplot as plt
import mplcursors
df = pd.DataFrame(
{'Universe': ['Darvel', 'MC', 'MC', 'Darvel', 'MC', 'Other', 'Darvel'],
'Value': [10, 11, 13, 12, 9, 7, 10],
'Upper': [12.5, 11.3, 15.4, 12.2, 13.1, 8.8, 11.5],
'Lower': [4.5, 9.6, 11.8, 6, 6.5, 5, 8]})
df['UpperError'] = df['Upper'] - df['Value']
df['LowerError'] = df['Value'] - df['Lower']
colors = ['r', 'g', 'b']
fig, ax = plt.subplots()
for i, universe in enumerate(df['Universe'].unique()):
to_plot = df[df['Universe'] == universe]
ax.scatter(to_plot.index, to_plot['Value'], s=16, c=colors[i])
error = to_plot[['LowerError', 'UpperError']].transpose().to_numpy()
ax.errorbar(to_plot.index, to_plot['Value'], yerr=error, fmt='o',
markersize=0, capsize=6, color=colors[i])
ax.scatter(to_plot.index, to_plot['Upper'], c='w', zorder=-1)
ax.scatter(to_plot.index, to_plot['Lower'], c='w', zorder=-1)
mplcursors.cursor(hover=True)
plt.show()
...ANSWER
Answered 2021-Sep-03 at 18:05To have mplcursors only interact with some elements, a list of those elements can be given as the first parameter to mplcursors.cursor()
. The list could be built from the return values of the calls to ax.scatter
.
To modify the annotation text shown, a custom function can be connected. In the example below, the label and the y-position are extracted from the selected element and put into the annotation text. Such label can be added via ax.scatter(..., label=...)
.
(Choosing 'none'
as the color for the "invisible" elements makes them really invisible. To make the code more "Pythonic" explicit indices can be avoided, working with zip
instead of with enumerate
.)
QUESTION
I'm plotting two columns of a Pandas DataFrame on a scatterplot and I want each point to show all the row values of the DataFrame. I've looked at this post, and tried to do something similar with mplcursors:
...ANSWER
Answered 2021-Aug-16 at 01:21- The
IndexError
occurs because ofdf.columns.tolist()[x.target.index]
df.columns.tolist()
is a list of 7 columns, which is then indexed by[x.target.index]
.
df.iloc[x.target.index, :].to_dict()
will get the desired row data for the point as adict
- A
list comprehension
creates a list of strings for eachkey
value
pair '\n'.join(...)
creates a string with each column separated by a\n
- A
QUESTION
Dears,
I wrote this code to calculate the distance between two mouse clicks on the plot. Now I am trying to move the plot to the left or to the right with regards to the calculated offset so that the two plots are exactly match. any idea how to achieve that? I tried to add and subtract normally but it did not work.
...ANSWER
Answered 2021-Jul-13 at 12:55Here is an approach, moving the first curve over the given distance. Numpy arrays are used to simplify the loops. relim()
and autoscale_view()
recalculate the x and y limits to fit everything again inside a margin (this step can be skipped if the expected displacement is small).
QUESTION
I am trying to use the following code to calculate the distance whenever I click the mouse, but I am receiving this error: TypeError: 'numpy.float64' object cannot be interpreted as an integer I have tried to follow this solution but didn't work with me: sudo pip install -U numpy==1.11.0
...ANSWER
Answered 2021-Jul-06 at 15:26QUESTION
from nptdms import TdmsFile as td
from matplotlib import pyplot as plt
import numpy as np
import skimage.color
import skimage.filters
import mplcursors
from skimage.feature import corner_harris,corner_peaks
file = 'sample.tdms'
with td.open(file) as tdms_file:
img = tdms_file.as_dataframe()
cropped_list = []
sel=cropped_list.append(img.iloc[700:1250,450:1550:])
coords=corner_peaks(corner_harris(sel),min_distance=10,threshold_rel=0.02)
fig, ax = plt.subplots()
ax.imshow(sel, cmap='gray')
plotted_points =ax.plot(coords[:, 1], coords[:, 0], color='cyan', marker='o',linestyle='None', markersize=2)
mplcursors.cursor(plotted_points, hover=True)
plt.show(
...ANSWER
Answered 2021-Apr-11 at 00:59mplcursors automatically create annotations with the x and y positions. Only when you need extra information, you'd need to write a function to change the annotation depending on the selected point.
Here is some code, using a random image to show how it would work:
QUESTION
I currently have a figure with three subplots that all share the y-axis but not the x-axis. For each subplot, I generated the data points using a for-loop that created a BrokenBarHCollection. The for loop I used is below (the function "f" just creates the xranges and yrange for each subplot):
...ANSWER
Answered 2021-Apr-15 at 16:14It's a bit unclear how you create your plot and how it looks like. The approach below assigns a label to each of the little bars. A broken_barh
can only have one label for the whole set, so instead of drawing ax.broken_barh()
, individual rectangles are created, each with their own label. An additional possibility is to also assign individual colors to each rectangle (the example below supposes a maximum of 20 colors).
In that case, mplcursors
default generates an annotation with label, x and y position of the cursor. You can change the default annotation, for example only using the label.
Note that mplcursors.cursor(..., hover=True)
shows an annotation while hovering. The default only shows the annotation when clicking.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install mplcursors
You can use mplcursors like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page