I would like to implement something like MATLAB's drawfreehand in Python.
I have something that is similar below where the user draws a poly gone which is then simplified using Shapely and then has an interactive spline fit to it. the issue is that the spline fit will often bulge out beyond the limits of the original polygon. My code is below:
from matplotlib.patches import Polygon
from matplotlib.widgets import AxesWidget
from matplotlib.lines import Line2D
import matplotlib as mpl
from matplotlib import path
import matplotlib.pyplot as plt
from scipy import interpolate
from shapely.geometry import LinearRing, Polygon as shapelyPolygon
import numpy as np
import copy
class AxManager:
def __init__(self, ax):
self.artists = []
self.ax = ax
self.canvas = self.ax.figure.canvas
self.useblit = self.canvas.supports_blit
self.canvas.mpl_connect('draw_event', self.update_background)
self.background = None
def update(self):
"""draw using newfangled blit or oldfangled draw depending on
useblit
"""
if not self.ax.get_visible():
return False
if self.useblit:
if self.background is not None:
self.canvas.restore_region(self.background)
for artist in self.artists:
if artist.get_visible():
self.ax.draw_artist(artist)
self.canvas.blit(self.ax.bbox)
else:
self.canvas.draw_idle()
return False
def draw(self):
self.canvas.draw_idle()
def update_background(self, event):
"""force an update of the background"""
# If you add a call to `ignore` here, you'll want to check edge case:
# `release` can call a draw event even when `ignore` is True.
if self.useblit:
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
class mySelectorWidget(AxesWidget):
def __init__(self, axMan, button=None, state_modifier_keys=None):
AxesWidget.__init__(self, axMan.ax)
self.visible = True
self.axMan = axMan
self.artists=[]
self.connect_event('motion_notify_event', self.onmove)
self.connect_event('button_press_event', self.press)
self.connect_event('button_release_event', self.release)
self.connect_event('key_press_event', self.on_key_press)
self.connect_event('key_release_event', self.on_key_release)
self.connect_event('scroll_event', self.on_scroll)
self.state_modifier_keys = dict(move=' ', clear='escape',
square='shift', center='control')
self.state_modifier_keys.update(state_modifier_keys or {})
if isinstance(button, int):
self.validButtons = [button]
else:
self.validButtons = button
# will save the data (position at mouseclick)
self.eventpress = None
# will save the data (pos. at mouserelease)
self.eventrelease = None
self._prev_event = None
self.state = set()
def set_active(self, active):
AxesWidget.set_active(self, active)
if active:
self.axMan.update_background(None)
def ignore(self, event):
"""return *True* if *event* should be ignored"""
if not self.active or not self.ax.get_visible():
return True
# If canvas was locked
if not self.canvas.widgetlock.available(self):
return True
if not hasattr(event, 'button'):
event.button = None
# Only do rectangle selection if event was triggered
# with a desired button
if self.validButtons is not None:
if event.button not in self.validButtons:
return True
# If no button was pressed yet ignore the event if it was out
# of the axes
if self.eventpress is None:
return event.inaxes != self.ax
# If a button was pressed, check if the release-button is the
# same.
if event.button == self.eventpress.button:
return False
# If a button was pressed, check if the release-button is the
# same.
return (event.inaxes != self.ax or
event.button != self.eventpress.button)
def _get_data(self, event):
"""Get the xdata and ydata for event, with limits"""
if event.xdata is None:
return None, None
x0, x1 = self.ax.get_xbound()
y0, y1 = self.ax.get_ybound()
xdata = max(x0, event.xdata)
xdata = min(x1, xdata)
ydata = max(y0, event.ydata)
ydata = min(y1, ydata)
return xdata, ydata
def _clean_event(self, event):
"""Clean up an event
Use prev event if there is no xdata
Limit the xdata and ydata to the axes limits
Set the prev event
"""
if event.xdata is None:
event = self._prev_event
else:
event = copy.copy(event)
event.xdata, event.ydata = self._get_data(event)
self._prev_event = event
return event
def press(self, event):
"""Button press handler and validator"""
if not self.ignore(event):
event = self._clean_event(event)
self.eventpress = event
self._prev_event = event
key = event.key or ''
key = key.replace('ctrl', 'control')
# move state is locked in on a button press
if key == self.state_modifier_keys['move']:
self.state.add('move')
self._press(event)
return True
return False
def _press(self, event):
"""Button press handler"""
pass
def release(self, event):
"""Button release event handler and validator"""
if not self.ignore(event) and self.eventpress:
event = self._clean_event(event)
self.eventrelease = event
self._release(event)
self.eventpress = None
self.eventrelease = None
self.state.discard('move')
return True
return False
def _release(self, event):
"""Button release event handler"""
pass
def onmove(self, event):
"""Cursor move event handler and validator"""
if not self.ignore(event):
event = self._clean_event(event)
if self.eventpress:
self._ondrag(event)
else:
self._onhover(event)
return True
return False
def _ondrag(self, event):
"""Cursor move event handler"""
pass
def _onhover(self, event):
pass
def on_scroll(self, event):
"""Mouse scroll event handler and validator"""
if not self.ignore(event):
self._on_scroll(event)
def _on_scroll(self, event):
"""Mouse scroll event handler"""
pass
def on_key_press(self, event):
"""Key press event handler and validator for all selection widgets"""
if self.active:
key = event.key or ''
key = key.replace('ctrl', 'control')
if key == self.state_modifier_keys['clear']:
for artist in self.artists:
artist.set_visible(False)
self.update()
return
for (state, modifier) in self.state_modifier_keys.items():
if modifier in key:
self.state.add(state)
self._on_key_press(event)
def _on_key_press(self, event):
"""Key press event handler - use for widget-specific key press actions.
"""
pass
def on_key_release(self, event):
"""Key release event handler and validator"""
if self.active:
key = event.key or ''
for (state, modifier) in self.state_modifier_keys.items():
if modifier in key:
self.state.discard(state)
self._on_key_release(event)
def _on_key_release(self, event):
"""Key release event handler"""
pass
def set_visible(self, visible):
""" Set the visibility of our artists """
self.visible = visible
for artist in self.artists:
artist.set_visible(visible)
def addArtist(self, artist):
self.axMan.artists.append(artist)
self.artists.append(artist)
class myLasso(mySelectorWidget):
def __init__(self, axMan, onselect=None, button=None):
super().__init__(axMan, button=button)
self.onselect = onselect
self.verts = None
self.polygon = Polygon([[0,0]], facecolor=(0,0,1,.1), animated=True, edgecolor=(0,0,1,.8))
self.polygon.set_visible(False)
self.ax.add_patch(self.polygon)
self.addArtist(self.polygon)
# self.set_active(True) #needed for blitting to work
def _press(self, event):
self.verts = [self._get_data(event)]
self.set_visible(True)
def _release(self, event):
self.disconnect_events()
if (self.verts is not None) and (self.onselect is not None):
self.onselect(self.verts)
self.set_visible(False)
self.axMan.draw()
def _ondrag(self, event):
if self.verts is None:
return
self.verts.append(self._get_data(event))
self.polygon.set_xy(self.verts)
self.axMan.update()
class PolygonInteractor(mySelectorWidget):
"""
A polygon editor.
https://matplotlib.org/gallery/event_handling/poly_editor.html
Key-bindings
't' toggle vertex markers on and off. When vertex markers are on,
you can move them, delete them
'd' delete the vertex under point
'i' insert a vertex at point. You must be within epsilon of the
line connecting two existing vertices
"""
showverts = True
epsilon = 5 # max pixel distance to count as a vertex hit
def __init__(self, axMan):
super().__init__(axMan, None)
self.line = Line2D([0],[0], ls="",
marker='o', markerfacecolor='r',
animated=True)
self.ax.add_line(self.line)
self._ind = None # the active vert
self._hoverInd = None
self.line2 = Polygon([[0,0]], animated=True, facecolor=(0,0,1,.1), edgecolor=(0,0,1,.9))
self.ax.add_patch(self.line2)
self.addArtist(self.line2)
self.addArtist(self.line)
self.set_visible(False)
def initialize(self, verts):
x, y = zip(*verts)
self.line.set_data(x,y)
# xy=[[0,0],[100,100],[0,100]]
xy = self.interpolate()
self.line2.set_xy(xy)
self.set_visible(True)
# self.axMan.update()
def interpolate(self):
x,y = self.line.get_data()
tck, u = interpolate.splprep([x, y], s=0, per=True)
# evaluate the spline fits for 1000 evenly spaced distance values
xi, yi = interpolate.splev(np.linspace(0, 1, 1000), tck)
return list(zip(xi,yi))
def get_ind_under_point(self, event):
'get the index of the vertex under point if within epsilon tolerance'
# display coords
xy = np.asarray(list(zip(*self.line.get_data())))
xyt = self.line.get_transform().transform(xy)
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.hypot(xt - event.x, yt - event.y)
indseq, = np.nonzero(d == d.min())
ind = indseq[0]
if d[ind] >= self.epsilon:
ind = None
return ind
def _press(self, event):
'whenever a mouse button is pressed'
if not self.showverts:
return
if event.inaxes is None:
return
if event.button != 1:
return
self._ind = self.get_ind_under_point(event)
def _release(self, event):
'whenever a mouse button is released'
if not self.showverts:
return
if event.button != 1:
return
self._ind = None
def _on_key_press(self, event):
'whenever a key is pressed'
# if not event.inaxes:
# return
if event.key == 't':
self.showverts = not self.showverts
self.line.set_visible(self.showverts)
if not self.showverts:
self._ind = None
elif event.key == 'd':
ind = self.get_ind_under_point(event)
if ind is not None:
self.poly.xy = np.delete(self.poly.xy,
ind, axis=0)
self.line.set_data(zip(*self.poly.xy))
elif event.key == 'i':
xys = self.poly.get_transform().transform(self.poly.xy)
p = np.array([event.x, event.y]) # display coords
for i in range(len(xys) - 1):
s0 = xys[i]
s1 = xys[i + 1]
d = np.linalg.norm(np.cross(s0-s1, s1-p))/np.linalg.norm(s0-s1) #distance from line to click point
if d <= self.epsilon:
self.line.set_data(np.insert(self.line.get_data, i+1, [event.ydata, event.xdata], axis=0))
break
elif event.key == 'enter':
self.done = True
self.close()
return
if self.line.stale:
self.canvas.draw_idle()
def _onhover(self, event):
lastHoverInd = self._hoverInd
self._hoverInd = self.get_ind_under_point(event)
if lastHoverInd != self._hoverInd:
if self._hoverInd is not None:
self.line.set_markerfacecolor((0,.9,1,1))
else:
self.line.set_markerfacecolor('r')
self.axMan.update()
def _ondrag(self, event):
'on mouse movement'
if self._ind is None:
return
x, y = event.xdata, event.ydata
d = list(zip(*self.line.get_data()))
d[self._ind] = (x,y)
if self._ind == 0:
d[-1] = (x, y)
elif self._ind == len(d) - 1:
d[0] = (x, y)
self.line.set_data(list(zip(*d)))
xy = self.interpolate()
self.line2.set_xy(xy)
self.axMan.update()
if __name__ == '__main__':
fig, ax = plt.subplots()
def onselect(verts):
l = shapelyPolygon(LinearRing(verts))
l = l.buffer(0)
l=l.simplify(l.length/2e2, preserve_topology=False)
p.active=True
p.initialize(l.exterior.coords)
axm = AxManager(ax)
l = myLasso(axm, onselect=onselect)
p = PolygonInteractor(axm)
p.active = False
Does anyone know how I can more closely implement the reshaping functionality of MATLAB's freehand object?
Related
I'm doing a Python program to fit Bezier curves to the eye contour (for example one curve that is adapted to the bottom line of the brow and the other to the lid's contour ). In order to achieve this, I'm trying to put the image of the eye as the background of a plot, and then interactive draw a line with the mousse that fits the best. My problem is that I need an arc and not a circle as I have done but I don't know how to solve this.
My initial image and the circle I have to fit but I only want an arc. The line fits the brow after using my mouse (the pink part is what I want). It's important to say I have to convert this arc or line into a Bézier curve, I have a program that does this function but It will be better If I could directly draw a Bezier line in the image but I don't know-how so the main problem is to have an arc or line but nos a circle because I need an open curve. I have to use the Bezier lines because I have to calculate some medical parameters with them, so I need their coordinates.
import numpy as np
import matplotlib
import shapely
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from matplotlib.lines import Line2D
from matplotlib.artist import Artist
from matplotlib.bezier import find_control_points
class PolygonInteractor(object):
"""
A polygon editor.
https://matplotlib.org/gallery/event_handling/poly_editor.html
Key-bindings
't' toggle vertex markers on and off. When vertex markers are on,
you can move them, delete them
'd' delete the vertex under point
'i' insert a vertex at point. You must be within epsilon of the
line connecting two existing vertices
"""
showverts = True
epsilon = 5 # max pixel distance to count as a vertex hit
def __init__(self, ax, poly, visible=False):
if poly.figure is None:
raise RuntimeError('You must first add the polygon to a figure '
'or canvas before defining the interactor')
self.ax = ax
canvas = poly.figure.canvas
self.poly = poly
self.poly.set_visible(visible)
x, y = zip(*self.poly.xy)
self.line = Line2D(x, y, ls="",
marker='*', linewidth=1, markerfacecolor='green',
animated=True)
self.ax.add_line(self.line)
self.cid = self.poly.add_callback(self.poly_changed)
self._ind = None # the active vert
canvas.mpl_connect('draw_event', self.draw_callback)
canvas.mpl_connect('button_press_event', self.button_press_callback)
canvas.mpl_connect('key_press_event', self.key_press_callback)
canvas.mpl_connect('button_release_event', self.button_release_callback)
canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
self.canvas = canvas
x,y = self.interpolate()
self.line2 = Line2D(x, y, animated=True)
self.ax.add_line(self.line2)
def interpolate(self):
x, y = self.poly.xy[:].T
i = np.arange(len(x))
interp_i = np.linspace(0, i.max(), 100 * i.max())
xi = interp1d(i, x, kind='cubic')(interp_i)
yi = interp1d(i, y, kind='cubic')(interp_i)
return xi,yi
def draw_callback(self, event):
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.ax.draw_artist(self.line2)
# do not need to blit here, this will fire before the screen is
# updated
def poly_changed(self, poly):
'this method is called whenever the polygon object is called'
# only copy the artist props to the line (except visibility)
vis = self.line.get_visible()
Artist.update_from(self.line, poly)
self.line.set_visible(vis) # don't use the poly visibility state
def get_ind_under_point(self, event):
'get the index of the vertex under point if within epsilon tolerance'
# display coords
xy = np.asarray(self.poly.xy)
xyt = self.poly.get_transform().transform(xy)
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.hypot(xt - event.x, yt - event.y)
indseq, = np.nonzero(d == d.min())
ind = indseq[0]
if d[ind] >= self.epsilon:
ind = None
return ind
def button_press_callback(self, event):
'whenever a mouse button is pressed'
if not self.showverts:
return
if event.inaxes is None:
return
if event.button != 1:
return
self._ind = self.get_ind_under_point(event)
def button_release_callback(self, event):
'whenever a mouse button is released'
if not self.showverts:
return
if event.button != 1:
return
self._ind = None
def key_press_callback(self, event):
'whenever a key is pressed'
if not event.inaxes:
return
if event.key == 't':
self.showverts = not self.showverts
self.line.set_visible(self.showverts)
if not self.showverts:
self._ind = None
elif event.key == 'd':
ind = self.get_ind_under_point(event)
if ind is not None:
self.poly.xy = np.delete(self.poly.xy,
ind, axis=0)
self.line.set_data(zip(*self.poly.xy))
elif event.key == 'i':
xys = self.poly.get_transform().transform(self.poly.xy)
p = event.x, event.y # display coords
for i in range(len(xys) - 1):
s0 = xys[i]
s1 = xys[i + 1]
d = dist_point_to_segment(p, s0, s1)
if d <= self.epsilon:
self.poly.xy = np.insert(
self.poly.xy, i+1,
[event.xdata, event.ydata],
axis=0)
self.line.set_data(zip(*self.poly.xy))
break
if self.line.stale:
self.canvas.draw_idle()
def motion_notify_callback(self, event):
'on mouse movement'
if not self.showverts:
return
if self._ind is None:
return
if event.inaxes is None:
return
if event.button != 1:
return
x, y = event.xdata, event.ydata
self.poly.xy[self._ind] = x, y
if self._ind == 0:
self.poly.xy[-1] = x, y
elif self._ind == len(self.poly.xy) - 1:
self.poly.xy[0] = x, y
self.line.set_data(zip(*self.poly.xy))
x,y = self.interpolate()
self.line2.set_data(x,y)
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.ax.draw_artist(self.line2)
self.canvas.blit(self.ax.bbox)
if __name__ == '__main__':
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
theta = np.arange(0, 2*np.pi, 0.1)
r = 1.5
xs = r*np.cos(theta)
ys = r*np.sin(theta)
xs = (921, 951, 993, 1000)
ys = (1181, 1230, 1243, 257)
poly = Polygon(list(zip(xs, ys)), animated=True)
#poly = LineString([(0, 0), (1, 1)])
img = plt.imread("/Users/raquel/Desktop/TFG/IMÁGENES/Unknown.jpeg")
fig, ax = plt.subplots()
img = ax.imshow(img, extent=[0, 1300, 0, 1300])
ax.add_patch(poly)
p = PolygonInteractor(ax, poly, visible=False)
ax.set_title('Click and drag a point to move it')
x = ax.set_xlim((0, 1300))
y = ax.set_ylim((0, 1300))
plt.show()
I’m a novice working on my first python project. I started with this "poly_editor.py" example from the matplotlib documentation since my program is doing similar things with an interactive graph. I’ve commented the 3 locations where I made additions and modifications. Basically, I just made the list of vertices (self.d) visible so I could check to not add more than 100.
"""
This is an example to show how to build cross-GUI applications using
matplotlib event handling to interact with objects on the canvas
"""
import numpy as np
from matplotlib.lines import Line2D
from matplotlib.artist import Artist
from matplotlib.mlab import dist_point_to_segment
class PolygonInteractor(object):
"""
An polygon editor.
Key-bindings
't' toggle vertex markers on and off. When vertex markers are on,
you can move them, delete them
'd' delete the vertex under point
'i' insert a vertex at point. You must be within epsilon of the
line connecting two existing vertices
"""
showverts = True
epsilon = 5 # max pixel distance to count as a vertex hit
def __init__(self, ax, poly):
if poly.figure is None:
raise RuntimeError('You must first add the polygon to a figure or canvas before defining the interactor')
self.ax = ax
canvas = poly.figure.canvas
self.poly = poly
######### added ########
self.d = []
######## end add #######
x, y = zip(*self.poly.xy)
self.line = Line2D(x, y, marker='o', markerfacecolor='r', animated=True)
self.ax.add_line(self.line)
#self._update_line(poly)
cid = self.poly.add_callback(self.poly_changed)
self._ind = None # the active vert
canvas.mpl_connect('draw_event', self.draw_callback)
canvas.mpl_connect('button_press_event', self.button_press_callback)
canvas.mpl_connect('key_press_event', self.key_press_callback)
canvas.mpl_connect('button_release_event', self.button_release_callback)
canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
self.canvas = canvas
def draw_callback(self, event):
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
def poly_changed(self, poly):
'this method is called whenever the polygon object is called'
# only copy the artist props to the line (except visibility)
vis = self.line.get_visible()
Artist.update_from(self.line, poly)
self.line.set_visible(vis) # don't use the poly visibility state
def get_ind_under_point(self, event):
'get the index of the vertex under point if within epsilon tolerance'
#################### changed code ######################
# display coords
xy = np.asarray(self.poly.xy)
xyt = self.poly.get_transform().transform(xy)
xt, yt = xyt[:, 0], xyt[:, 1]
self.d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2)
indseq = np.nonzero(np.equal(self.d, np.amin(self.d)))[0]
ind = indseq[0]
print(len(self.d))
if self.d[ind] >= self.epsilon:
ind = None
#################### end changes #######################
return ind
def button_press_callback(self, event):
'whenever a mouse button is pressed'
if not self.showverts:
return
if event.inaxes is None:
return
if event.button != 1:
return
self._ind = self.get_ind_under_point(event)
def button_release_callback(self, event):
'whenever a mouse button is released'
if not self.showverts:
return
if event.button != 1:
return
self._ind = None
def key_press_callback(self, event):
'whenever a key is pressed'
if not event.inaxes:
return
if event.key == 't':
self.showverts = not self.showverts
self.line.set_visible(self.showverts)
if not self.showverts:
self._ind = None
elif event.key == 'd':
ind = self.get_ind_under_point(event)
if ind is not None:
self.poly.xy = [tup for i, tup in enumerate(self.poly.xy) if i != ind]
self.line.set_data(zip(*self.poly.xy))
elif event.key == 'i':
########### added ###########
if len(self.d) < 100:
########## end add ##########
xys = self.poly.get_transform().transform(self.poly.xy)
p = event.x, event.y # display coords
for i in range(len(xys) - 1):
s0 = xys[i]
s1 = xys[i + 1]
d = dist_point_to_segment(p, s0, s1)
if d <= self.epsilon:
self.poly.xy = np.array(
list(self.poly.xy[:i]) +
[(event.xdata, event.ydata)] +
list(self.poly.xy[i:]))
self.line.set_data(zip(*self.poly.xy))
break
self.canvas.draw()
def motion_notify_callback(self, event):
'on mouse movement'
if not self.showverts:
return
if self._ind is None:
return
if event.inaxes is None:
return
if event.button != 1:
return
x, y = event.xdata, event.ydata
self.poly.xy[self._ind] = x, y
if self._ind == 0:
self.poly.xy[-1] = x, y
elif self._ind == len(self.poly.xy) - 1:
self.poly.xy[0] = x, y
self.line.set_data(zip(*self.poly.xy))
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
if __name__ == '__main__':
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
theta = np.arange(0, 2*np.pi, 0.1)
r = 1.5
xs = r*np.cos(theta)
ys = r*np.sin(theta)
poly = Polygon(list(zip(xs, ys)), animated=True)
fig, ax = plt.subplots()
ax.add_patch(poly)
p = PolygonInteractor(ax, poly)
#ax.add_line(p.line)
ax.set_title('Click and drag a point to move it')
ax.set_xlim((-2, 2))
ax.set_ylim((-2, 2))
plt.show()
The problem is: if you click on an edge and hold down the “i” key to insert vertices, it will just continue to add beyond 100, ignoring the “if len(self.d) < 100:” statement.
I found this “bug” by accidentally leaning on the keyboard… lol. Is there any way to fix this behavior? My current work around is to bind it to the release event, but rapidly pressing the key can still cause the issue. My next option is to just allow additional points by a popup menu I guess, but I’d prefer a solution to a work around.
I'm trying to make an interactive plot using matplotlib that creates a line segment with two handles at the endpoints. You can click and drag the handles and the line will refresh to match the positions specified in this way, in a similar fashion to this matplotlib example poly_editor: (if you see the example, imagine that I want the same thing but with just one edge of the polygon).
I have tried altering the poly_editor code to work with just the Line2D element, and my program runs without any errors, except that it doesn't draw anything on the axis at all. I think it might be an error in the scope of the variables or something to do with the draw calls from matplotlib. Any guidance as to what the errors are would be greatly appreciated.
Edit: I advanced some more, simplified the code and now I can get it to draw the line and print the index of the nearest vertex within epsilon distance, but the line stays stationary and does not animate. The updated code is bellow
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import Line2D
class LineBuilder(object):
epsilon = 0.5
def __init__(self, line):
canvas = line.figure.canvas
self.canvas = canvas
self.line = line
self.axes = line.axes
self.xs = list(line.get_xdata())
self.ys = list(line.get_ydata())
self.ind = None
canvas.mpl_connect('button_press_event', self.button_press_callback)
canvas.mpl_connect('button_release_event', self.button_release_callback)
canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
def get_ind(self, event):
x = np.array(self.line.get_xdata())
y = np.array(self.line.get_ydata())
d = np.sqrt((x-event.xdata)**2 + (y - event.ydata)**2)
if min(d) > self.epsilon:
return None
if d[0] < d[1]:
return 0
else:
return 1
def button_press_callback(self, event):
if event.button != 1:
return
self.ind = self.get_ind(event)
print(self.ind)
self.line.set_animated(True)
self.canvas.draw()
self.background = self.canvas.copy_from_bbox(self.line.axes.bbox)
self.axes.draw_artist(self.line)
self.canvas.blit(self.axes.bbox)
def button_release_callback(self, event):
if event.button != 1:
return
self.ind = None
self.line.set_animated(False)
self.background = None
self.line.figure.canvas.draw()
def motion_notify_callback(self, event):
if event.inaxes != self.line.axes:
return
if event.button != 1:
return
if self.ind is None:
return
self.xs[self.ind] = event.xdata
self.ys[self.ind] = event.ydata
self.line.set_data(self.xs, self.ys)
self.canvas.restore_region(self.background)
self.axes.draw_artist(self.line)
self.canvas.blit(self.axes.bbox)
if __name__ == '__main__':
fig, ax = plt.subplots()
line = Line2D([0,1], [0,1], marker='o', markerfacecolor='red')
ax.add_line(line)
linebuilder = LineBuilder(line)
ax.set_title('click to create lines')
ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
plt.show()
Thanks in advance, Kevin.
Okay, I solved the problem. The new code (above) actually works, there was a mistake in it. The mpl_connect call for the motion notify event had the wrong event type, now it is working as intended.
I am new here so hope I don't make to many mistakes by replying to this self.replied question. :)
First thanks for posting this, it helped me a lot by saving some time, I wanted almost exactly this code. I did some updates that I propose here, so that it's possible to manipulate more than two points, and use the key handling events to create or delete points in the line, as the PolygonInteractor does.
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import numpy as np
def dist(x, y):
"""
Return the distance between two points.
"""
d = x - y
return np.sqrt(np.dot(d, d))
def dist_point_to_segment(p, s0, s1):
"""
Get the distance of a point to a segment.
*p*, *s0*, *s1* are *xy* sequences
This algorithm from
http://geomalgorithms.com/a02-_lines.html
"""
v = s1 - s0
w = p - s0
c1 = np.dot(w, v)
if c1 <= 0:
return dist(p, s0)
c2 = np.dot(v, v)
if c2 <= c1:
return dist(p, s1)
b = c1 / c2
pb = s0 + b * v
return dist(p, pb)
class LineBuilder(object):
epsilon = 30 #in pixels
def __init__(self, line):
canvas = line.figure.canvas
self.canvas = canvas
self.line = line
self.axes = line.axes
self.xs = list(line.get_xdata())
self.ys = list(line.get_ydata())
self.ind = None
canvas.mpl_connect('button_press_event', self.button_press_callback)
canvas.mpl_connect('button_release_event', self.button_release_callback)
canvas.mpl_connect('key_press_event', self.key_press_callback)
canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
def get_ind(self, event):
xy = np.asarray(self.line._xy)
xyt = self.line.get_transform().transform(xy)
x, y = xyt[:, 0], xyt[:, 1]
d = np.sqrt((x-event.x)**2 + (y - event.y)**2)
indseq, = np.nonzero(d == d.min())
ind = indseq[0]
if d[ind] >= self.epsilon:
ind = None
return ind
def button_press_callback(self, event):
if event.button != 1:
return
if event.inaxes is None:
return
self.ind = self.get_ind(event)
print(self.ind)
self.line.set_animated(True)
self.canvas.draw()
self.background = self.canvas.copy_from_bbox(self.line.axes.bbox)
self.axes.draw_artist(self.line)
self.canvas.blit(self.axes.bbox)
def button_release_callback(self, event):
if event.button != 1:
return
self.ind = None
self.line.set_animated(False)
self.background = None
self.line.figure.canvas.draw()
def motion_notify_callback(self, event):
if event.inaxes != self.line.axes:
return
if event.button != 1:
return
if self.ind is None:
return
self.xs[self.ind] = event.xdata
self.ys[self.ind] = event.ydata
self.line.set_data(self.xs, self.ys)
self.canvas.restore_region(self.background)
self.axes.draw_artist(self.line)
self.canvas.blit(self.axes.bbox)
def key_press_callback(self, event):
"""Callback for key presses."""
if not event.inaxes:
return
elif event.key == 'd':
ind = self.get_ind(event)
if ind is not None and len(self.xs) > 2:
self.xs = np.delete(self.xs, ind)
self.ys = np.delete(self.ys, ind)
self.line.set_data(self.xs, self.ys)
self.axes.draw_artist(self.line)
self.canvas.draw_idle()
elif event.key == 'i':
p = np.array([event.x, event.y]) # display coords
xy = np.asarray(self.line._xy)
xyt = self.line.get_transform().transform(xy)
for i in range(len(xyt) - 1):
s0 = xyt[i]
s1 = xyt[i+1]
d = dist_point_to_segment(p, s0, s1)
if d <= self.epsilon:
self.xs = np.insert(self.xs, i+1, event.xdata)
self.ys = np.insert(self.ys, i+1, event.ydata)
self.line.set_data(self.xs, self.ys)
self.axes.draw_artist(self.line)
self.canvas.draw_idle()
break
if __name__ == '__main__':
fig, ax = plt.subplots()
line = Line2D([0,0.5,1], [0,0.5,1], marker = 'o', markerfacecolor = 'red')
ax.add_line(line)
linebuilder = LineBuilder(line)
ax.set_title('click to create lines')
ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
plt.show()
This actually leads to a question/problem i have but it will be in another message.
Kristen
Based on combination of mouse button and key events, different functionalities are applied to the points of a scatter plot. When the left mouse button is pressed matplotlib's Lasso widget is called and with the included points functionality 1 takes place. When Shift+LMB are pressed a Lasso is drawn and functionality 2 takes place with the included points. When Alt+LMB are pressed a Lasso is drawn and with the included points functionality 3 takes place. Last, but not least, when I press the RMB a pick event is triggered and the index of the selected point in the scatter plot is given.
Since I added the pick event, the aforementioned functionalities work correctly until a pick event is triggered for the first time. When it is triggered it seems that the canvas gets locked and I can not use any other functionality. Although, I get the index of the selected point, I do not get any errors, and the canvas becomes unresponsive.
I modified the code taken from this question, which is actually what I want to do.
Code:
import logging
import matplotlib
from matplotlib.widgets import Lasso
from matplotlib.colors import colorConverter
from matplotlib.collections import RegularPolyCollection
from matplotlib import path
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import rand
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
class Datum(object):
colorin = colorConverter.to_rgba('red')
colorShift = colorConverter.to_rgba('cyan')
colorCtrl = colorConverter.to_rgba('pink')
colorout = colorConverter.to_rgba('blue')
def __init__(self, x, y, include=False):
self.x = x
self.y = y
if include:
self.color = self.colorin
else:
self.color = self.colorout
class LassoManager(object):
def __init__(self, ax, data):
self.axes = ax
self.canvas = ax.figure.canvas
self.data = data
self.Nxy = len(data)
facecolors = [d.color for d in data]
self.xys = [(d.x, d.y) for d in data]
fig = ax.figure
self.collection = RegularPolyCollection(fig.dpi, 6, sizes=(100,),facecolors=facecolors, offsets = self.xys, transOffset = ax.transData)
ax.add_collection(self.collection)
self.pick=self.canvas.mpl_connect('pick_event', self.onpick)
self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
self.keyPress = self.canvas.mpl_connect('key_press_event', self.onKeyPress)
self.keyRelease = self.canvas.mpl_connect('key_release_event', self.onKeyRelease)
self.lasso = None
self.shiftKey = False
self.ctrlKey = False
def callback(self, verts):
logging.debug('in LassoManager.callback(). Shift: %s, Ctrl: %s' % (self.shiftKey, self.ctrlKey))
facecolors = self.collection.get_facecolors()
p = path.Path(verts)
ind = p.contains_points(self.xys)
for i in range(len(self.xys)):
if ind[i]:
if self.shiftKey:
facecolors[i] = Datum.colorShift
elif self.ctrlKey:
facecolors[i] = Datum.colorCtrl
else:
facecolors[i] = Datum.colorin
print self.xys[i]
else:
facecolors[i] = Datum.colorout
self.canvas.draw_idle()
self.canvas.widgetlock.release(self.lasso)
del self.lasso
def onpress(self, event):
if self.canvas.widgetlock.locked(): return
if event.inaxes is None: return
self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback)
# acquire a lock on the widget drawing
self.canvas.widgetlock(self.lasso)
def onKeyPress(self, event):
logging.debug('in LassoManager.onKeyPress(). Event received: %s (key: %s)' % (event, event.key))
if event.key == 'alt':
self.ctrlKey = True
if event.key == 'shift':
self.shiftKey = True
def onKeyRelease(self, event):
logging.debug('in LassoManager.onKeyRelease(). Event received: %s (key: %s)' % (event, event.key))
if event.key == 'alt':
self.ctrlKey = False
if event.key == 'shift':
self.shiftKey = False
def onpick(self,event):
if event.mouseevent.button == 3:
index = event.ind
print('onpick scatter:', index, np.take(x, index), np.take(y, index))
if __name__ == '__main__':
x,y =rand(2,100)
data = [Datum(*xy) for xy in zip(x,y)]
fig = plt.figure()
ax = plt.axes()
ax.scatter(x,y,picker=True)
lman = LassoManager(ax, data)
plt.show()
Any suggestions on what might be causing this malfunction? Thanks in advance.
The problem you're having this time is that you have both a PickEvent and a MouseEvent that are generated at the same time when you click on an artist. The MouseEvent locks the canvas and prevents you from doing anything else afterward.
The best solution would be to prevent the MouseEvent from being fired after the PickEvent, but I don't know if there's a way to do that. Instead, I added a test to check whether onpress() was called after onpick() to disable the locking mechanism.
import logging
import matplotlib
from matplotlib.widgets import Lasso
from matplotlib.colors import colorConverter
from matplotlib.collections import RegularPolyCollection
from matplotlib import path
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import rand
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
class Datum(object):
colorin = colorConverter.to_rgba('red')
colorShift = colorConverter.to_rgba('cyan')
colorCtrl = colorConverter.to_rgba('pink')
colorout = colorConverter.to_rgba('blue')
def __init__(self, x, y, include=False):
self.x = x
self.y = y
if include:
self.color = self.colorin
else:
self.color = self.colorout
class LassoManager(object):
def __init__(self, ax, data):
self.axes = ax
self.canvas = ax.figure.canvas
self.data = data
self.Nxy = len(data)
facecolors = [d.color for d in data]
self.xys = [(d.x, d.y) for d in data]
fig = ax.figure
self.collection = RegularPolyCollection(fig.dpi, 6, sizes=(100,),facecolors=facecolors, offsets = self.xys, transOffset = ax.transData)
ax.add_collection(self.collection)
self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
self.keyPress = self.canvas.mpl_connect('key_press_event', self.onKeyPress)
self.keyRelease = self.canvas.mpl_connect('key_release_event', self.onKeyRelease)
self.pick=self.canvas.mpl_connect('pick_event', self.onpick)
self.lasso = None
self.shiftKey = False
self.ctrlKey = False
self.pickEvent = False
def callback(self, verts):
logging.debug('in LassoManager.callback(). Shift: %s, Ctrl: %s' % (self.shiftKey, self.ctrlKey))
facecolors = self.collection.get_facecolors()
p = path.Path(verts)
ind = p.contains_points(self.xys)
for i in range(len(self.xys)):
if ind[i]:
if self.shiftKey:
facecolors[i] = Datum.colorShift
elif self.ctrlKey:
facecolors[i] = Datum.colorCtrl
else:
facecolors[i] = Datum.colorin
print self.xys[i]
else:
facecolors[i] = Datum.colorout
self.canvas.draw_idle()
self.canvas.widgetlock.release(self.lasso)
del self.lasso
def onpress(self, event):
logging.debug('in LassoManager.onpress(). Event received: %s' % event)
if self.pickEvent:
self.pickEvent = False
return
if self.canvas.widgetlock.locked(): return
if event.inaxes is None: return
self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback)
# acquire a lock on the widget drawing
self.canvas.widgetlock(self.lasso)
def onKeyPress(self, event):
logging.debug('in LassoManager.onKeyPress(). Event received: %s (key: %s)' % (event, event.key))
if event.key == 'alt':
self.ctrlKey = True
if event.key == 'shift':
self.shiftKey = True
def onKeyRelease(self, event):
logging.debug('in LassoManager.onKeyRelease(). Event received: %s (key: %s)' % (event, event.key))
if event.key == 'alt':
self.ctrlKey = False
if event.key == 'shift':
self.shiftKey = False
def onpick(self, event):
logging.debug('in LassoManager.onpick(). Event received: %s' % event)
self.pickEvent = True
if event.mouseevent.button == 3:
index = event.ind
print 'onpick scatter: ', index, np.take(x, index), np.take(y, index)
if __name__ == '__main__':
x,y =rand(2,100)
data = [Datum(*xy) for xy in zip(x,y)]
fig = plt.figure()
ax = plt.axes()
ax.scatter(x,y,picker=True)
lman = LassoManager(ax, data)
plt.show()
I need to have 2 draggable points in a figureCanvas. But I have a supplementary constraint: the 2 points must be linked by a line.
When I drag a point, of course (it wouldn't be funny otherwise), the line must be dynamically drawn, and still linked to the 2 points.
I managed to create the 2 draggable points, with this topic:
Matplotlib drag overlapping points interactively
I modified a bit the code to use it trough a subclass of FigureCanvas (to later include the graph in a PyQt application):
import matplotlib.pyplot as plt
import matplotlib.patches as patches
class DraggablePoint:
# https://stackoverflow.com/questions/21654008/matplotlib-drag-overlapping-points-interactively
lock = None # only one can be animated at a time
def __init__(self, parent, x=0.1, y=0.1):
self.parent = parent
self.point = patches.Ellipse((x, y), 0.01, 0.03, fc='r', alpha=0.5)
self.x = x
self.y = y
parent.fig.axes[0].add_patch(self.point)
self.press = None
self.background = None
self.connect()
def connect(self):
'connect to all the events we need'
self.cidpress = self.point.figure.canvas.mpl_connect('button_press_event', self.on_press)
self.cidrelease = self.point.figure.canvas.mpl_connect('button_release_event', self.on_release)
self.cidmotion = self.point.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)
def on_press(self, event):
if event.inaxes != self.point.axes: return
if DraggablePoint.lock is not None: return
contains, attrd = self.point.contains(event)
if not contains: return
self.press = (self.point.center), event.xdata, event.ydata
DraggablePoint.lock = self
# draw everything but the selected rectangle and store the pixel buffer
canvas = self.point.figure.canvas
axes = self.point.axes
self.point.set_animated(True)
canvas.draw()
self.background = canvas.copy_from_bbox(self.point.axes.bbox)
# now redraw just the rectangle
axes.draw_artist(self.point)
# and blit just the redrawn area
canvas.blit(axes.bbox)
def on_motion(self, event):
if DraggablePoint.lock is not self:
return
if event.inaxes != self.point.axes: return
self.point.center, xpress, ypress = self.press
dx = event.xdata - xpress
dy = event.ydata - ypress
self.point.center = (self.point.center[0]+dx, self.point.center[1]+dy)
canvas = self.point.figure.canvas
axes = self.point.axes
# restore the background region
canvas.restore_region(self.background)
# redraw just the current rectangle
axes.draw_artist(self.point)
# blit just the redrawn area
canvas.blit(axes.bbox)
def on_release(self, event):
'on release we reset the press data'
if DraggablePoint.lock is not self:
return
self.press = None
DraggablePoint.lock = None
# turn off the rect animation property and reset the background
self.point.set_animated(False)
self.background = None
# redraw the full figure
self.point.figure.canvas.draw()
self.x = self.point.center[0]
self.y = self.point.center[1]
def disconnect(self):
'disconnect all the stored connection ids'
self.point.figure.canvas.mpl_disconnect(self.cidpress)
self.point.figure.canvas.mpl_disconnect(self.cidrelease)
self.point.figure.canvas.mpl_disconnect(self.cidmotion)
There will only be 2 points on the future graph, and I can access the other point from the class DraggablePoint trough self.parent.
I think I need to draw a line between the 2 points, in the function on_motion. But I tried and found nothing.
Do you have an idea about how to achieve that ?
Ok I finally found the solution. I post it here for those who might need it. This code basically allow to have 2 draggable points linked by a line. If you move one of the points, the line follows. Very useful to make a baseline in scientific applications.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.lines import Line2D
class DraggablePoint:
# http://stackoverflow.com/questions/21654008/matplotlib-drag-overlapping-points-interactively
lock = None # only one can be animated at a time
def __init__(self, parent, x=0.1, y=0.1, size=0.1):
self.parent = parent
self.point = patches.Ellipse((x, y), size, size * 3, fc='r', alpha=0.5, edgecolor='r')
self.x = x
self.y = y
parent.fig.axes[0].add_patch(self.point)
self.press = None
self.background = None
self.connect()
if self.parent.list_points:
line_x = [self.parent.list_points[0].x, self.x]
line_y = [self.parent.list_points[0].y, self.y]
self.line = Line2D(line_x, line_y, color='r', alpha=0.5)
parent.fig.axes[0].add_line(self.line)
def connect(self):
'connect to all the events we need'
self.cidpress = self.point.figure.canvas.mpl_connect('button_press_event', self.on_press)
self.cidrelease = self.point.figure.canvas.mpl_connect('button_release_event', self.on_release)
self.cidmotion = self.point.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)
def on_press(self, event):
if event.inaxes != self.point.axes: return
if DraggablePoint.lock is not None: return
contains, attrd = self.point.contains(event)
if not contains: return
self.press = (self.point.center), event.xdata, event.ydata
DraggablePoint.lock = self
# draw everything but the selected rectangle and store the pixel buffer
canvas = self.point.figure.canvas
axes = self.point.axes
self.point.set_animated(True)
if self == self.parent.list_points[1]:
self.line.set_animated(True)
else:
self.parent.list_points[1].line.set_animated(True)
canvas.draw()
self.background = canvas.copy_from_bbox(self.point.axes.bbox)
# now redraw just the rectangle
axes.draw_artist(self.point)
# and blit just the redrawn area
canvas.blit(axes.bbox)
def on_motion(self, event):
if DraggablePoint.lock is not self:
return
if event.inaxes != self.point.axes: return
self.point.center, xpress, ypress = self.press
dx = event.xdata - xpress
dy = event.ydata - ypress
self.point.center = (self.point.center[0]+dx, self.point.center[1]+dy)
canvas = self.point.figure.canvas
axes = self.point.axes
# restore the background region
canvas.restore_region(self.background)
# redraw just the current rectangle
axes.draw_artist(self.point)
if self == self.parent.list_points[1]:
axes.draw_artist(self.line)
else:
self.parent.list_points[1].line.set_animated(True)
axes.draw_artist(self.parent.list_points[1].line)
self.x = self.point.center[0]
self.y = self.point.center[1]
if self == self.parent.list_points[1]:
line_x = [self.parent.list_points[0].x, self.x]
line_y = [self.parent.list_points[0].y, self.y]
self.line.set_data(line_x, line_y)
else:
line_x = [self.x, self.parent.list_points[1].x]
line_y = [self.y, self.parent.list_points[1].y]
self.parent.list_points[1].line.set_data(line_x, line_y)
# blit just the redrawn area
canvas.blit(axes.bbox)
def on_release(self, event):
'on release we reset the press data'
if DraggablePoint.lock is not self:
return
self.press = None
DraggablePoint.lock = None
# turn off the rect animation property and reset the background
self.point.set_animated(False)
if self == self.parent.list_points[1]:
self.line.set_animated(False)
else:
self.parent.list_points[1].line.set_animated(False)
self.background = None
# redraw the full figure
self.point.figure.canvas.draw()
self.x = self.point.center[0]
self.y = self.point.center[1]
def disconnect(self):
'disconnect all the stored connection ids'
self.point.figure.canvas.mpl_disconnect(self.cidpress)
self.point.figure.canvas.mpl_disconnect(self.cidrelease)
self.point.figure.canvas.mpl_disconnect(self.cidmotion)
UPDATE:
How to use the DraggablePoint class, with PyQt5:
#!/usr/bin/python
# -*-coding:Utf-8 -*
import sys
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtWidgets, QtGui
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
# Personnal modules
from drag import DraggablePoint
class MyGraph(FigureCanvas):
"""A canvas that updates itself every second with a new plot."""
def __init__(self, parent=None, width=5, height=4, dpi=100):
self.fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = self.fig.add_subplot(111)
self.axes.grid(True)
FigureCanvas.__init__(self, self.fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
# To store the 2 draggable points
self.list_points = []
self.show()
self.plotDraggablePoints([0.1, 0.1], [0.2, 0.2], [0.1, 0.1])
def plotDraggablePoints(self, xy1, xy2, size=None):
"""Plot and define the 2 draggable points of the baseline"""
# del(self.list_points[:])
self.list_points.append(DraggablePoint(self, xy1[0], xy1[1], size))
self.list_points.append(DraggablePoint(self, xy2[0], xy2[1], size))
self.updateFigure()
def clearFigure(self):
"""Clear the graph"""
self.axes.clear()
self.axes.grid(True)
del(self.list_points[:])
self.updateFigure()
def updateFigure(self):
"""Update the graph. Necessary, to call after each plot"""
self.draw()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = MyGraph()
sys.exit(app.exec_())
Here is my simple solution with the additionnal feature to add or remove points.
You have then a draggable segmented line with controls on points.
The code is simple despite events handling. Improvements are welcome.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.lines import Line2D
#------------------------------------------------
listLabelPoints = []
point_alpha_default = 0.8
mousepress = None
currently_dragging = False
current_artist = None
offset = [0,0]
n = 0
line_object = None
#------------------------------------------------
def on_press(event):
global currently_dragging
global mousepress
currently_dragging = True
if event.button == 3:
mousepress = "right"
elif event.button == 1:
mousepress = "left"
#------------------------------------------------
def on_release(event):
global current_artist, currently_dragging
current_artist = None
currently_dragging = False
#------------------------------------------------
def on_pick(event):
global current_artist, offset, n
global listLabelPoints
if current_artist is None:
current_artist = event.artist
#print("pick ", current_artist)
if isinstance(event.artist, patches.Circle):
if event.mouseevent.dblclick:
if mousepress == "right":
#print("double click right")
if len(ax.patches) > 2:
#print("\ndelete", event.artist.get_label())
event.artist.remove()
xdata = list(line_object[0].get_xdata())
ydata = list(line_object[0].get_ydata())
for i in range(0,len(xdata)):
if event.artist.get_label() == listLabelPoints[i]:
xdata.pop(i)
ydata.pop(i)
listLabelPoints.pop(i)
break
#print('--->', listLabelPoints)
line_object[0].set_data(xdata, ydata)
plt.draw()
else:
x0, y0 = current_artist.center
x1, y1 = event.mouseevent.xdata, event.mouseevent.ydata
offset = [(x0 - x1), (y0 - y1)]
elif isinstance(event.artist, Line2D):
if event.mouseevent.dblclick:
if mousepress == "left":
#print("double click left")
n = n+1
x, y = event.mouseevent.xdata, event.mouseevent.ydata
newPointLabel = "point"+str(n)
point_object = patches.Circle([x, y], radius=50, color='r', fill=False, lw=2,
alpha=point_alpha_default, transform=ax.transData, label=newPointLabel)
point_object.set_picker(5)
ax.add_patch(point_object)
xdata = list(line_object[0].get_xdata())
ydata = list(line_object[0].get_ydata())
#print('\ninit', listLabelPoints)
pointInserted = False
for i in range(0,len(xdata)-1):
#print("--> testing inclusion %s in [%s-%s]"
# %(newPointLabel, listLabelPoints[i], listLabelPoints[i+1]))
#print('----->', min(xdata[i],xdata[i+1]), '<', x, '<', max(xdata[i],xdata[i+1]))
#print('----->', min(ydata[i],ydata[i+1]), '<', y, '<', max(ydata[i],ydata[i+1]))
if x > min(xdata[i],xdata[i+1]) and x < max(xdata[i],xdata[i+1]) and \
y > min(ydata[i],ydata[i+1]) and y < max(ydata[i],ydata[i+1]) :
xdata.insert(i+1, x)
ydata.insert(i+1, y)
listLabelPoints.insert(i+1, newPointLabel)
pointInserted = True
#print("include", newPointLabel)
break
line_object[0].set_data(xdata, ydata)
#print('final', listLabelPoints)
plt.draw()
if not pointInserted:
print("Error: point not inserted")
else:
xdata = event.artist.get_xdata()
ydata = event.artist.get_ydata()
x1, y1 = event.mouseevent.xdata, event.mouseevent.ydata
offset = xdata[0] - x1, ydata[0] - y1
#------------------------------------------------
def on_motion(event):
global current_artist
if not currently_dragging:
return
if current_artist == None:
return
if event.xdata == None:
return
dx, dy = offset
if isinstance(current_artist, patches.Circle):
cx, cy = event.xdata + dx, event.ydata + dy
current_artist.center = cx, cy
#print("moving", current_artist.get_label())
xdata = list(line_object[0].get_xdata())
ydata = list(line_object[0].get_ydata())
for i in range(0,len(xdata)):
if listLabelPoints[i] == current_artist.get_label():
xdata[i] = cx
ydata[i] = cy
break
line_object[0].set_data(xdata, ydata)
elif isinstance(current_artist, Line2D):
xdata = list(line_object[0].get_xdata())
ydata = list(line_object[0].get_ydata())
xdata0 = xdata[0]
ydata0 = ydata[0]
for i in range(0,len(xdata)):
xdata[i] = event.xdata + dx + xdata[i] - xdata0
ydata[i] = event.ydata + dy + ydata[i] - ydata0
line_object[0].set_data(xdata, ydata)
for p in ax.patches:
pointLabel = p.get_label()
i = listLabelPoints.index(pointLabel)
p.center = xdata[i], ydata[i]
plt.draw()
#------------------------------------------------
def on_click(event):
global n, line_object
if event and event.dblclick:
if len(listLabelPoints) < 2:
n = n+1
x, y = event.xdata, event.ydata
newPointLabel = "point"+str(n)
point_object = patches.Circle([x, y], radius=50, color='r', fill=False, lw=2,
alpha=point_alpha_default, transform=ax.transData, label=newPointLabel)
point_object.set_picker(5)
ax.add_patch(point_object)
listLabelPoints.append(newPointLabel)
if len(listLabelPoints) == 2:
xdata = []
ydata = []
for p in ax.patches:
cx, cy = p.center
xdata.append(cx)
ydata.append(cy)
line_object = ax.plot(xdata, ydata, alpha=0.5, c='r', lw=2, picker=True)
line_object[0].set_pickradius(5)
plt.draw()
#================================================
fig, ax = plt.subplots()
ax.set_title("Double click left button to create draggable point\nDouble click right to remove a point", loc="left")
ax.set_xlim(0, 4000)
ax.set_ylim(0, 3000)
ax.set_aspect('equal')
fig.canvas.mpl_connect('button_press_event', on_click)
fig.canvas.mpl_connect('button_press_event', on_press)
fig.canvas.mpl_connect('button_release_event', on_release)
fig.canvas.mpl_connect('pick_event', on_pick)
fig.canvas.mpl_connect('motion_notify_event', on_motion)
plt.grid(True)
plt.show()
I needed more points in the graph, so I modified the solution done by JPFrancoia in order to have more points connected with lines. I hope somebody else could find it usefull, so the new drag.py file reads:
# drag.py
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.lines import Line2D
class DraggablePoint:
# http://stackoverflow.com/questions/21654008/matplotlib-drag-overlapping-points-interactively
lock = None # only one can be animated at a time
def __init__(self, parent, x=0.1, y=0.1, size=0.1):
self.parent = parent
self.point = patches.Ellipse((x, y), size, size * 3, fc='r', alpha=0.5, edgecolor='r')
self.x = x
self.y = y
parent.fig.axes[0].add_patch(self.point)
self.press = None
self.background = None
self.connect()
# if another point already exist we draw a line
if self.parent.list_points:
line_x = [self.parent.list_points[-1].x, self.x]
line_y = [self.parent.list_points[-1].y, self.y]
self.line = Line2D(line_x, line_y, color='r', alpha=0.5)
parent.fig.axes[0].add_line(self.line)
def connect(self):
'connect to all the events we need'
self.cidpress = self.point.figure.canvas.mpl_connect('button_press_event', self.on_press)
self.cidrelease = self.point.figure.canvas.mpl_connect('button_release_event', self.on_release)
self.cidmotion = self.point.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)
def on_press(self, event):
if event.inaxes != self.point.axes: return
if DraggablePoint.lock is not None: return
contains, attrd = self.point.contains(event)
if not contains: return
self.press = (self.point.center), event.xdata, event.ydata
DraggablePoint.lock = self
# draw everything but the selected rectangle and store the pixel buffer
canvas = self.point.figure.canvas
axes = self.point.axes
self.point.set_animated(True)
# TODO also the line of some other points needs to be released
point_number = self.parent.list_points.index(self)
if self == self.parent.list_points[0]:
self.parent.list_points[1].line.set_animated(True)
elif self == self.parent.list_points[-1]:
self.line.set_animated(True)
else:
self.line.set_animated(True)
self.parent.list_points[point_number+1].line.set_animated(True)
canvas.draw()
self.background = canvas.copy_from_bbox(self.point.axes.bbox)
# now redraw just the rectangle
axes.draw_artist(self.point)
# and blit just the redrawn area
canvas.blit(axes.bbox)
def on_motion(self, event):
if DraggablePoint.lock is not self:
return
if event.inaxes != self.point.axes: return
self.point.center, xpress, ypress = self.press
dx = event.xdata - xpress
dy = event.ydata - ypress
self.point.center = (self.point.center[0]+dx, self.point.center[1]+dy)
canvas = self.point.figure.canvas
axes = self.point.axes
# restore the background region
canvas.restore_region(self.background)
# redraw just the current rectangle
axes.draw_artist(self.point)
point_number = self.parent.list_points.index(self)
self.x = self.point.center[0]
self.y = self.point.center[1]
# We check if the point is A or B
if self == self.parent.list_points[0]:
# or we draw the other line of the point
self.parent.list_points[1].line.set_animated(True)
axes.draw_artist(self.parent.list_points[1].line)
elif self == self.parent.list_points[-1]:
# we draw the line of the point
axes.draw_artist(self.line)
else:
# we draw the line of the point
axes.draw_artist(self.line)
#self.parent.list_points[point_number+1].line.set_animated(True)
axes.draw_artist(self.parent.list_points[point_number+1].line)
if self == self.parent.list_points[0]:
# The first point is especial because it has no line
line_x = [self.x, self.parent.list_points[1].x]
line_y = [self.y, self.parent.list_points[1].y]
# this is were the line is updated
self.parent.list_points[1].line.set_data(line_x, line_y)
elif self == self.parent.list_points[-1]:
line_x = [self.parent.list_points[-2].x, self.x]
line_y = [self.parent.list_points[-2].y, self.y]
self.line.set_data(line_x, line_y)
else:
# The first point is especial because it has no line
line_x = [self.x, self.parent.list_points[point_number+1].x]
line_y = [self.y, self.parent.list_points[point_number+1].y]
# this is were the line is updated
self.parent.list_points[point_number+1].line.set_data(line_x, line_y)
line_x = [self.parent.list_points[point_number-1].x, self.x]
line_y = [self.parent.list_points[point_number-1].y, self.y]
self.line.set_data(line_x, line_y)
# blit just the redrawn area
canvas.blit(axes.bbox)
def on_release(self, event):
'on release we reset the press data'
if DraggablePoint.lock is not self:
return
self.press = None
DraggablePoint.lock = None
# turn off the rect animation property and reset the background
self.point.set_animated(False)
point_number = self.parent.list_points.index(self)
if self == self.parent.list_points[0]:
self.parent.list_points[1].line.set_animated(False)
elif self == self.parent.list_points[-1]:
self.line.set_animated(False)
else:
self.line.set_animated(False)
self.parent.list_points[point_number+1].line.set_animated(False)
self.background = None
# redraw the full figure
self.point.figure.canvas.draw()
self.x = self.point.center[0]
self.y = self.point.center[1]
def disconnect(self):
'disconnect all the stored connection ids'
self.point.figure.canvas.mpl_disconnect(self.cidpress)
self.point.figure.canvas.mpl_disconnect(self.cidrelease)
self.point.figure.canvas.mpl_disconnect(self.cidmotion)
And the excution is done like:
import sys
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtWidgets, QtGui
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
# Personnal modules
from drag import DraggablePoint
class MyGraph(FigureCanvas):
"""A canvas that updates itself every second with a new plot."""
def __init__(self, parent=None, width=5, height=4, dpi=100):
self.fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = self.fig.add_subplot(111)
self.axes.grid(True)
FigureCanvas.__init__(self, self.fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
# To store the 2 draggable points
self.list_points = []
self.show()
self.plotDraggablePoints()
def plotDraggablePoints(self, size=0.05):
"""Plot and define the 2 draggable points of the baseline"""
# del(self.list_points[:])
self.list_points.append(DraggablePoint(self, 0.1, 0.1, size))
self.list_points.append(DraggablePoint(self, 0.2, 0.2, size))
self.list_points.append(DraggablePoint(self, 0.5, 0.5, size))
self.list_points.append(DraggablePoint(self, 0.6, 0.5, size))
self.list_points.append(DraggablePoint(self, 0.7, 0.5, size))
self.updateFigure()
def clearFigure(self):
"""Clear the graph"""
self.axes.clear()
self.axes.grid(True)
del(self.list_points[:])
self.updateFigure()
def updateFigure(self):
"""Update the graph. Necessary, to call after each plot"""
self.draw()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = MyGraph()
sys.exit(app.exec_())