Label for point in plots in matplotlib
If you look at the rest of the code in __call__
you'll see xdata
and ydata
are never used. You can simply delete the line
xdata, ydata = event.artist.get_data()
and the rest of Joe's beautiful code works just fine.
Add cursor to matplotlib
There is an example on the matplotlib page, which you may adapt to show a point at the position of interest.
import matplotlib.pyplot as plt
import matplotlib.widgets as widgets
import numpy as np
class SnaptoCursor(object):
def __init__(self, ax, x, y):
self.ax = ax
self.ly = ax.axvline(color='k', alpha=0.2) # the vert line
self.marker, = ax.plot([0],[0], marker="o", color="crimson", zorder=3)
self.x = x
self.y = y
self.txt = ax.text(0.7, 0.9, '')
def mouse_move(self, event):
if not event.inaxes: return
x, y = event.xdata, event.ydata
indx = np.searchsorted(self.x, [x])[0]
x = self.x[indx]
y = self.y[indx]
self.ly.set_xdata(x)
self.marker.set_data([x],[y])
self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
self.txt.set_position((x,y))
self.ax.figure.canvas.draw_idle()
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*2*np.pi*t)
fig, ax = plt.subplots()
#cursor = Cursor(ax)
cursor = SnaptoCursor(ax, t, s)
cid = plt.connect('motion_notify_event', cursor.mouse_move)
ax.plot(t, s,)
plt.axis([0, 1, -1, 1])
plt.show()
Python and Remove annotation from figure
Most matplotlib objects have a remove()
function (I think it is inherited from Artist
). Just call that on the object you want to remove.
Edit:
If you have
dc = DataCursor(...) # what ever aruguements you give it
# bunch of code
dc.annotation.remove()
del dc
plt.draw() # need to redraw to make remove visible
Python has no notion of 'private' attributes, so you can just reach inside you object and call remove on the annotation. See tutorial on classes for more details.
The down side of this is that now you have an object is a strange state. If you have any other references to it, they might behave badly. If you want to keep the DataCursor
object around you can modify the annotation
object using it's set_*
functions or change it's visibility to temporarily hide it (doc)
Related Topics
Is the Server Bundled with Flask Safe to Use in Production
Virtualenv --No-Site-Packages and Pip Still Finding Global Packages
Unpickling a Python 2 Object with Python 3
Underscore _ as Variable Name in Python
How to Plot Multiple Functions on the Same Figure, in Matplotlib
Check If Item Is in an Array/List
How to Add an Integer to Each Element in a List
Could Pandas Use Column as Index
How to Account for Period (Am/Pm) Using Strftime
Absolute VS. Explicit Relative Import of Python Module
How to Change Values in a Tuple
How to Set the Aspect Ratio in Matplotlib
Python Os.Path.Join on Windows
Format Floats with Standard JSON Module
Check If a String in a Pandas Dataframe Column Is in a List of Strings
Python: Count Repeated Elements in the List
Django Upgrading to 1.9 Error "Appregistrynotready: Apps Aren't Loaded Yet."