Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing patch objects in matplotlib without them moving position

I want to automatically generate a series of plots which are clipped to patches. If I try and reuse a patch object, it moves position across the canvas.

This script (based on an answer to a previous question by Yann) demonstrates what is happening.

import pylab as plt
import scipy as sp
import matplotlib.patches as patches

sp.random.seed(100)
x = sp.random.random(100)
y = sp.random.random(100)
patch = patches.Circle((.75,.75),radius=.25,fc='none')


def doplot(x,y,patch,count):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    im = ax.scatter(x,y)
    ax.add_patch(patch)
    im.set_clip_path(patch)
    plt.savefig(str(count) + '.png')


for count in xrange(4):
    doplot(x,y,patch,count)

The first plot looks like this:Correct position of patch - first time plotted

But in the second '1.png', the patch has moved.. Wrong position of the patch

However replotting again doesn't move the patch. '2.png' and '3.png' look exactly the same as '1.png'.

Could anyone point me in the right direction of what I'm doing wrong??

In reality, the patches I'm using are relatively complex and take some time to generate - I'd prefer to not have to remake them every frame if possible.

like image 853
Hannah Fry Avatar asked Oct 09 '22 11:10

Hannah Fry


1 Answers

The problem can be avoided by using the same axes for each plot, with ax.cla() called to clear the plot after each iteration.

import pylab as plt
import scipy as sp
import matplotlib.patches as patches

sp.random.seed(100)
patch = patches.Circle((.75,.75),radius=.25,fc='none')

fig = plt.figure()
ax = fig.add_subplot(111)

def doplot(x,y,patch,count):
    ax.set_xlim(-0.2,1.2)
    ax.set_ylim(-0.2,1.2)
    x = sp.random.random(100)
    y = sp.random.random(100)
    im = ax.scatter(x,y)
    ax.add_patch(patch)
    im.set_clip_path(patch)
    plt.savefig(str(count) + '.png')
    ax.cla()

for count in xrange(4):
    doplot(x,y,patch,count)
like image 97
unutbu Avatar answered Oct 13 '22 10:10

unutbu