# Blit with more than one interactor

Hi,

borrowing from the example poly editor, I wrote an example where two editable polygons are drawn.
In my example two polygons (red and blue) are drawn.

When I modify the latest polygon drawn (red), blit works well.
On the other hand, when I try to modify the first polygon (blue), the red one disappears.
It reappears only if I zoom. This is clearly due to the fact that the background is captured
before the second polygon is drawn.

There is a way to move the first polygon without making disappear the second one ?
This is the code:

``````
#!/usr/bin/env python
import numpy as np
from matplotlib.lines import Line2D
from matplotlib.artist import Artist

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 PolygonInteractor(object):
"""
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):
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=poly.get_ec(),
animated=True)

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

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(np.column_stack([xs, ys]), animated=True,
color='blue', fill=False)

xs = r * np.cos(theta) + 1
ys = r * np.sin(theta) + 1

poly2 = Polygon(np.column_stack([xs, ys]), animated=True,
color='red', fill=False)

fig, ax = plt.subplots()
p = PolygonInteractor(ax, poly)
p2 = PolygonInteractor(ax, poly2)

ax.set_title('Click and drag a point to move it')
ax.set_xlim((-3, 3))
ax.set_ylim((-3, 3))
plt.show()
``````

Redraw the canvas rather than just the current polygon in the motion_notify_callback( ) function:

Thus the following code

``````    self.canvas.restore_region(self.background)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
``````

becomes

``````    self.canvas.restore_region(self.background)
self.canvas.draw_idle()
self.canvas.blit(self.ax.bbox)
``````

Hope this helps

Laurence

If you through the `draw_idle` in, it will re-draw the whole canvas which eliminates the speed increase of blitting.

You need to push the management of the background and re-drawing up a level of organization. That is if you want to have more than one `PolygonInteractor` objects, they need to be managed by something that knows to re-draw all of them when every any of them change.

1 Like

Initially, I had wondered about that but draw_idle( ) happened to work well in this example. Perhaps only because the areas being re-drawn aren’t very different. However, you’re right that it wouldn’t generalise well to all situations.

And, in fact, the canvas.blit( ) would also be surplus to requirements in my original suggestion as well.

I couldn’t resist attempting to do this the proper way and push some things up a level as @tacaswell recommended. Here’s what I’ve come up with as a solution (minus sanity checking code - I’ll leave that to you):

First of all, in PolygonInteractor class:

1. remove the draw event declaration & draw_callback( ) function
2. remove the last 4 lines of the motion_notify_callback( ) function

Both of these things will be moved up to a new PolygonManager class.

Now define a PolygonManager class with the following code:

``````class PolygonManager(object):

def __init__(self, ax, interactor_list):
self.ax = ax
self.interactors = interactor_list
self.canvas = ax.figure.canvas
self.canvas.mpl_connect('draw_event', self.draw_callback)
self.canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)

def draw_callback(self, event):
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
for pi in self.interactors:
self.ax.draw_artist(pi.poly)
self.ax.draw_artist(pi.line)

def motion_notify_callback(self, event):
self.canvas.restore_region(self.background)
for pi in self.interactors:
self.ax.draw_artist(pi.poly)
self.ax.draw_artist(pi.line)
self.canvas.blit(self.ax.bbox)
``````

Now all you need to do is create your PolygonManager once you have created your PolygonInteractors, passing it all your PolygonInteractors to it as a list.

``````p = PolygonInteractor(ax, poly)
p2 = PolygonInteractor(ax, poly2)
p3 = PolygonInteractor(ax, poly3)

pm = PolygonManager(ax, [p, p2, p3])
``````

I dunno… is this what @tacaswell had in mind? It certainly seems to work for me but I wonder if I’ve overlooked something that more experienced folk may spot.

I integrated Laurence’s suggestion in the code for future users.
I also made the code slightly simpler using two triangles.
Cheers,
Dario

``````#!/usr/bin/env python
import numpy as np
from matplotlib.lines import Line2D
from matplotlib.artist import Artist

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 PolygonManager(object):
"""
Manager object which control the redraw of the polygon interactors
created with PolygonInteractor.
Once the polygons are drawn, the background is cached.
Each time one of the polygons is modified, the background is restored and the
polygons are updated.
"""
def __init__(self, ax, interactor_list):
self.ax = ax
self.interactors = interactor_list
self.canvas = ax.figure.canvas
self.canvas.mpl_connect('draw_event', self.draw_callback)
self.canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)

def draw_callback(self, event):
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
for pi in self.interactors:
self.ax.draw_artist(pi.poly)
self.ax.draw_artist(pi.line)

def motion_notify_callback(self, event):
self.canvas.restore_region(self.background)
for pi in self.interactors:
self.ax.draw_artist(pi.poly)
self.ax.draw_artist(pi.line)
self.canvas.blit(self.ax.bbox)

class PolygonInteractor(object):
"""
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):
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)
color = poly.get_ec()
self.line = Line2D(x, y,
marker='o', markerfacecolor=color,
color=color,
animated=True)

self._ind = None  # the active vert

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

if __name__ == '__main__':
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

theta = np.arange(0, 2*np.pi, 2*np.pi/3.)
r = 1.5
xs = r * np.cos(theta)
ys = r * np.sin(theta)

poly = Polygon(np.column_stack([xs, ys]), animated=True,
color='blue', fill=False)

theta = np.arange(0, 2*np.pi, 2*np.pi/3.) + np.pi/3.
r = 1.5
xs = r * np.cos(theta)
ys = r * np.sin(theta)

poly2 = Polygon(np.column_stack([xs, ys]), animated=True,
color='red', fill=False)

fig, ax = plt.subplots()