Annotate draggable Circle - python

I am looking to annotate a draggable circle with a number. The draggeable point is created from this class:
class DraggablePoint:
lock = None #only one can be animated at a time
def __init__(self, point):
self.point = point
self.press = None
self.background = None
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 point 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()
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)
I am plotting with this (circles.append + the last loop is the interesting code for this problem):
drs = []
circles = []
for team, color, sec_color in zip([hometeam.loc[frame], awayteam.loc[frame]], team_colors, sec_colors):
x_columns = [c for c in team.keys() if
c[-2:].lower() == '_x' and c != 'ball_x'] # column header for player x positions
y_columns = [c for c in team.keys() if
c[-2:].lower() == '_y' and c != 'ball_y'] # column header for player y positions
for x, y in zip(team[x_columns], team[y_columns]):
#if ctr == 0:
circles.append(patches.Circle((x, y), 1.4, fc=color, edgecolor=sec_color, linewidth=1.2, zorder=2))
for circ in circles:
ax.add_patch(circ)
dr = DraggablePoint(circ)
dr.connect()
drs.append(dr)
plt.show()
I can plot text at the circles center, however once I drag a circle, the text stays at the original position. Is there a way to add text to the circles, which would move alongside the circles when dragged?

Sure. Add a label, record the relative position to the circle, and update its position on motion.
import matplotlib.pyplot as plt
class DraggablePoint:
...
class LabelledDraggablePoint(DraggablePoint):
def __init__(self, point, label):
super().__init__(point)
self.label = label
x1, y1 = self.label.get_position()
x2, y2 = self.point.center
self.label_offset = (x1 - x2, y1 - y2)
def on_motion(self, event):
super().on_motion(event)
self.label.set_position(self.point.center + self.label_offset)
if __name__ == '__main__':
fig, ax = plt.subplots()
point = plt.Circle((0.5, 0.5), 0.1)
ax.add_patch(point)
ax.set_aspect('equal')
label = ax.text(0.5, 0.5, 'Lorem ipsum', ha='center', va='center')
instance = LabelledDraggablePoint(point, label)
instance.connect()
plt.show()
On a different note: the blitting is nausea inducing. You will get much smoother animations without it. I would cut all of that out.

Related

Moving verticle lines around in a Matplotlib plot?

I have been looking around for a while and cant seem to find much on moving elements around after they have been plotted. I have a series of vertical lines plotted and if they are to close together i would like to be able to space then out a bit more. The issue is that they cant be moved to the left ever. I have code that can evenly space all these with that constraint but now I0m focusing on just making sure they are not clumped together. here is an example picture of what I'm working with:
full view
zoomed in on a problem
Thee question really is if there is a way I am able to click and drag these red lines around so they are not to close to others? i need to be able to retrieve the new positions of all the lines after this is done after i have made them all nicely spaced but i assume this would be fairly simple after i have this mechanic in place?
I'm not looking for specific implementation just some help on places I could look to be able to make this click and drag utility possible.
This may not be possible in matplotlib itself and i may have to look outward into making some GUI to do this but i have no experience in this so probably not the best solution although probably the best.
Any insight into how I might be able to achieve the click drag utility will be greatly appreciated!
-Thank you
got it working from a movable polygon example here: https://matplotlib.org/stable/gallery/event_handling/poly_editor.html
import numpy as np
import pandas as pd
from matplotlib.lines import Line2D
from matplotlib.artist import Artist
global new_freqs
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://www.geomalgorithms.com/algorithms.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 PolygonInteractor:
"""
A 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, start_freqs):
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
x, y = zip(*self.poly.xy)
self.line = Line2D(x, y,
marker='o', markerfacecolor='r',
animated=True)
self.ax.add_line(self.line)
ax.vlines(x,linestyle="--", ymin=0.0, ymax=1, alpha=0.9, color=col, gid="new_lines")
self.original_freqs = start_freqs #variable for storing the starting frequencies
self.orig_cols = col # array or starting colours
self.new_cols = self.orig_cols # array or new colours, same as original to begin with
self.issue_spacing = 1.0e6 # variable to store the value of kids to close together
self.cid = self.poly.add_callback(self.poly_changed)
self._ind = None # the active vert
canvas.mpl_connect('draw_event', self.on_draw)
canvas.mpl_connect('button_press_event', self.on_button_press)
canvas.mpl_connect('key_press_event', self.on_key_press)
canvas.mpl_connect('button_release_event', self.on_button_release)
canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
self.canvas = canvas
def draw_new_positions(self):
for i in range(len(self.new_cols)):
if self.poly.xy[i,0] != self.original_freqs[i]:
if self.poly.xy[i,0] < self.original_freqs[i]:
self.new_cols[i] = "purple" #if the kid has moved backwward show purple
elif (self.poly.xy[i+1,0]-self.poly.xy[i,0]) < self.issue_spacing or (self.poly.xy[i,0]-self.poly.xy[i-1,0]) < self.issue_spacing :
self.new_cols[i] = "black" #if the kid to close the the ones next to it show black
else:
self.new_cols[i] = "orange" #if the kid has moved and is positioned ok show orange
else:
self.new_cols[i] = self.orig_cols[i]
new_lines = self.ax.vlines(self.poly.xy[:-1,0], ymin=-1, ymax=0, linestyle="--", color=self.new_cols, alpha=0.9, gid="new_lines") #new line to move where mouse is
self.ax.draw_artist(new_lines) # drawing the line on moving the mouse
self.canvas.blit(self.ax.bbox) # blitting the canvas to render moving
new_lines.remove()
def on_draw(self, event):
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
# 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 pathpatch 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):
"""
Return the index of the point closest to the event position or *None*
if no point is within ``self.epsilon`` to the event position.
"""
# 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 on_button_press(self, event):
"""Callback for mouse button presses."""
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 on_button_release(self, event):
"""Callback for mouse button releases."""
if not self.showverts:
return
if event.button != 1:
return
self._ind = None
def on_key_press(self, event):
"""Callback for key presses."""
if not event.inaxes:
return
if event.key == 't': #toggles the movable points on and off
self.showverts = not self.showverts
self.line.set_visible(self.showverts)
if not self.showverts:
self._ind = None
elif event.key == ' ': #prints the x vals of all polygon points (which are the new frequencies) to the console
new_freqs = self.poly.xy[:,0]
for i in range(len(new_freqs)-1):
print("{:.1f},".format(new_freqs[i]))
# print(len(new_freqs))
elif event.key == 'l': #save new frequencies to csv file and show final plot
new_freqs = self.poly.xy[:-1,0]
new_data = 0
new_data = np.zeros((len(new_freqs), 2))
new_data[:,0] = data["kid_id"]
new_data[:,1] = new_freqs
new_data_df = pd.DataFrame(data=new_data, columns=["kid_id", "f0"]) #makes a new data frame to save to csv with all new positions
new_data_df.to_csv("new_kid_positions.csv", index=False)
plt.close()
plt.figure("new array", dpi=150)
for i in range(len(new_data_df["f0"])):
if self.poly.xy[i,0] == self.original_freqs[i]:
col="green"
else:
col="orange"
plt.axvline(new_data_df["f0"][i]/1e6, color=col, linestyle="--", linewidth=1.5, alpha=0.9)
plt.plot([],[], color="orange", label="Moved")
plt.plot([],[], color="green", label="Not moved")
plt.legend(loc="best")
plt.xlabel("Frequency (MHz)")
plt.ylabel("")
plt.title("Altered array")
plt.grid()
plt.show()
if self.line.stale:
self.canvas.draw_idle()
def on_mouse_move(self, event):
"""Callback for mouse movements."""
if not self.showverts:
return
if self._ind is None:
return
if event.inaxes is None:
return
if event.button != 1:
self.moving_line.remove()
return
x, y = event.xdata, 0
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.remove_series()
# f = x
# self.add_series(f, "new_lines", len(self.poly.xy[:,0])-1)
# ax.axvline(x, ymin=-1, ymax=1, linestyle="--", color="orange", alpha=0.9, animated=True)
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
# self.moving_line = self.ax.axvline(x, ymin=-1, ymax=1, linestyle="--", color="orange", alpha=0.9) #new line to move where mouse is
# self.ax.draw_artist(self.moving_line) # drawing the line on moving the mouse
# self.moving_line.remove()
self.draw_new_positions()
self.canvas.blit(self.ax.bbox) # blitting the canvas to render moving
if __name__ == '__main__':
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
#reading in freequency positions
data = pd.read_csv("sorted_kids.csv")
#getting color for each line
col = [] #empty list
for i in range(len(data["issue"])):
if data["issue"][i] == 1:
col.append("red")
else:
col.append("green")
# col = np.array(col)
xs = data["f0"]
ys = np.zeros_like(xs)
poly = Polygon(np.column_stack([xs, ys]), animated=True)
fig, ax = plt.subplots(dpi=150, figsize=(12,6))
ax.add_patch(poly)
p = PolygonInteractor(ax, poly, xs)
ax.set_title('Click a point to drag. spacebar=print freqs. T=toggle move. L=save and show final solution')
ax.plot([],[], color="black", alpha=0.0, label=r"TOP: ORIGINAL ARRAY")
ax.plot([],[], color="red", label="to close")
ax.plot([],[], color="green", label="spacing ok")
ax.plot([],[], color="black", alpha=0.0, label="\nBOT: ALTEERED ARRAY")
ax.plot([],[], color="red", label="orig position & to close")
ax.plot([],[], color="green", label="orig position & ok")
ax.plot([],[], color="purple", label="moved backward!")
ax.plot([],[], color="black", label="to close still")
ax.plot([],[], color="orange", label="moved & ok")
ax.legend(loc=1, fontsize=6)
plt.xlabel("Frequency (Hz)")
ax.set_xlim((min(data["f0"])-10e6, max(data["f0"])+10e6))
ax.set_ylim((-1.5, 1.5))
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
ax.axes.get_yaxis().set_visible(False)
plt.show()

Python: draw an interactive line (arc) with the mouse on an image

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()

Python: key pressed event ignores conditional statement

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.

draw horizontal bars on the same line

I have to draw a gantt resource type of chart.
Idea is to draw several horizontal bars on the same line (corresponding to a resource) each length represented by start date and and date
this is the expected result:
Altogether we have around 200 resources and max. 50 task for each to display, so performance is important.
Any idea?
In addition the tasks should be draggable by mouse.
An solution (Fat GUI (pyQt, wxwidget, tkinter, ...) or web based Flask, web2py, etc) is OK
Actually, I'm gonna cheat and post you something straight from the Matplotlib Documentation. This should get you started with draggable objects in mpl. you'll have to come up with your own dynamic object creation code...
full credit to the guys over at mpl:
# draggable rectangle with the animation blit techniques; see
# http://www.scipy.org/Cookbook/Matplotlib/Animations
import numpy as np
import matplotlib.pyplot as plt
class DraggableRectangle:
lock = None # only one can be animated at a time
def __init__(self, rect):
self.rect = rect
self.press = None
self.background = None
def connect(self):
'connect to all the events we need'
self.cidpress = self.rect.figure.canvas.mpl_connect(
'button_press_event', self.on_press)
self.cidrelease = self.rect.figure.canvas.mpl_connect(
'button_release_event', self.on_release)
self.cidmotion = self.rect.figure.canvas.mpl_connect(
'motion_notify_event', self.on_motion)
def on_press(self, event):
'on button press we will see if the mouse is over us and store some data'
if event.inaxes != self.rect.axes: return
if DraggableRectangle.lock is not None: return
contains, attrd = self.rect.contains(event)
if not contains: return
print('event contains', self.rect.xy)
x0, y0 = self.rect.xy
self.press = x0, y0, event.xdata, event.ydata
DraggableRectangle.lock = self
# draw everything but the selected rectangle and store the pixel buffer
canvas = self.rect.figure.canvas
axes = self.rect.axes
self.rect.set_animated(True)
canvas.draw()
self.background = canvas.copy_from_bbox(self.rect.axes.bbox)
# now redraw just the rectangle
axes.draw_artist(self.rect)
# and blit just the redrawn area
canvas.blit(axes.bbox)
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if DraggableRectangle.lock is not self:
return
if event.inaxes != self.rect.axes: return
x0, y0, xpress, ypress = self.press
dx = event.xdata - xpress
dy = event.ydata - ypress
self.rect.set_x(x0+dx)
self.rect.set_y(y0+dy)
canvas = self.rect.figure.canvas
axes = self.rect.axes
# restore the background region
canvas.restore_region(self.background)
# redraw just the current rectangle
axes.draw_artist(self.rect)
# blit just the redrawn area
canvas.blit(axes.bbox)
def on_release(self, event):
'on release we reset the press data'
if DraggableRectangle.lock is not self:
return
self.press = None
DraggableRectangle.lock = None
# turn off the rect animation property and reset the background
self.rect.set_animated(False)
self.background = None
# redraw the full figure
self.rect.figure.canvas.draw()
def disconnect(self):
'disconnect all the stored connection ids'
self.rect.figure.canvas.mpl_disconnect(self.cidpress)
self.rect.figure.canvas.mpl_disconnect(self.cidrelease)
self.rect.figure.canvas.mpl_disconnect(self.cidmotion)
fig = plt.figure()
ax = fig.add_subplot(111)
rects = ax.bar(range(10), 20*np.random.rand(10))
drs = []
for rect in rects:
dr = DraggableRectangle(rect)
dr.connect()
drs.append(dr)
plt.show()

Draggable line with draggable points

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_())

Categories

Resources