Matplotlib:如何从带有其他绘制元素的轴中仅删除一个轮廓元素?

4

我正在尝试对高斯混合模型(Gaussian Mixture Models)的均值和协方差进行估计的动画化,需要在每次迭代时更新均值和协方差的绘图。

对于均值的重绘很容易,因为我使用了具有set_data方法的线条,在每次更新时可以调用此方法。不幸的是,更新协方差则更加困难,因为轮廓元素是以 QuadContourSet 对象表示的,它们没有 set_data 方法。

以下是一个示例:

import numpy as np
from matplotlib import mlab

# Toy data points (these are constant)
plt.plot(np.arange(-3,3,0.1), np.arange(-3,3,0.1))

x = np.arange(-5.0, 5.0, 0.1)
y = np.arange(-5.0, 5.0, 0.1)
X, Y = np.meshgrid(x, y)

# First toy iteration
Z1 = mlab.bivariate_normal(X, Y, 
                           1, 1, 
                           0, 0)

covariance1 = plt.contour(X, Y, Z1)

# Second toy iteration
Z2 = mlab.bivariate_normal(X, Y, 
                       1, 1, 
                       0, 3)

covariance2 = plt.contour(X, Y, Z2)

玩具示例

在实际问题中,我绘制了均值、方差和数据点,不想清除整个轴。

问题是如何去掉第一个轮廓 covariance1,而不影响其他元素?

1个回答

7
for coll in covariance1.collections:
    coll.remove()

然后更新。

非常容易!我已经尝试过 for coll in plt.gca().collections: 谢谢! - alberto
2
这似乎无法与3D轮廓(即mplot3d工具包中的contourf)一起使用:coll.remove()会出现以下错误:collection._remove_method = lambda h: self.collections.remove(h) ValueError: list.remove(x): x not in list有没有什么办法可以正确地删除这样的3D轮廓?(可以使用coll.set_visible(False),但元素仍然存在) - armando.sano
2
抱歉,我的错 - remove() 函数也适用于三维轮廓。我的问题是由于在动画的某个时刻没有创建轮廓线(对于水平平面没有水平轮廓线!)导致的。 - armando.sano
如果您使用contourf,该如何使其工作?我可以删除轮廓线,但是线之间的阴影区域仍然存在。 - Eddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接