在matplotlib中重用补丁对象,而不使用它们的移动位置 [英] Reusing patch objects in matplotlib without them moving position

查看:309
本文介绍了在matplotlib中重用补丁对象,而不使用它们的移动位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自动生成一系列曲线图,这些曲线图被修剪成补丁。如果我尝试和重用一个补丁对象,它移动位置在画布上。

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.

此脚本(基于Yann上一个问题的答案)演示了正在发生的事情。

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:

但是在第二个1.png中,补丁已经移动。 。

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

然而,再次重绘不移动补丁。 '2.png'和'3.png'看起来与'1.png'完全相同。

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.

推荐答案

通过对每个图使用相同的轴可以避免这个问题, ax.cla )调用以在每次迭代后清除图。

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)

这篇关于在matplotlib中重用补丁对象,而不使用它们的移动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆