【问题标题】:Updating contours for matplotlib animation更新 matplotlib 动画的轮廓
【发布时间】:2023-03-24 12:35:02
【问题描述】:

我正在寻找一种方法来更新动画中的轮廓线,而无需我每次都重新绘制图形。

我发现对这个问题的大多数回复都提倡回忆ax.contour,但由于我的轮廓叠加在另一张图像上,所以速度慢得无法忍受。

我发现的唯一一个看起来接近回答问题的回答是用死链接回答它:Animating a contour plot in matplotlib using FuncAnimation

编辑:this 可能是预期的链接。

示例代码:

#!/usr/bin/env python

import matplotlib.pylab as plt
import matplotlib.animation as anim
from matplotlib.colors import LinearSegmentedColormap as lsc
import numpy

#fig = 0; ax = 0; im = 0; co = 0


image_data = numpy.random.random((100,50,50))
contour_data = numpy.random.random((100,50,50))

def init():
    global fig, ax, im, co
    fig = plt.figure()
    ax = plt.axes()
    im = ax.imshow(image_data[0,:,:])
    co = ax.contour(contour_data[0,:,:])

def func(n):
    im.set_data(image_data[n,:,:])
    co.set_array(contour_data[n,:,:])

init()
ani = anim.FuncAnimation(fig, func, frames=100)
plt.show()

干杯。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    也许你现在已经想通了;不幸的是,您似乎必须重新声明整个轮廓/轮廓艺术家集在每个时间步删除旧实例。这是从this link复制的一些信息:

    set_array() 方法(我认为)只影响颜色映射 contourf 的信息,即使这样似乎也没有更新。 你需要做的是制作一个新的等高线图并删除旧的, 特别是如果您需要更改基础轮廓数据。这 应该像 C.remove() 一样简单,但由于某种原因,这并不 存在(我会在一分钟内添加它)。所以相反,你需要做 以下:

    import matplotlib.pyplot as plt 
    import numpy as np 
    
    x = np.arange(0, 2 * np.pi, 0.1) 
    X,Y = np.meshgrid(x,x) 
    f1 = np.sin(X) + np.sin(Y) 
    f2 = np.cos(X) + np.cos(Y) 
    
    plt.figure() 
    C = plt.contourf(f1) 
    plt.show() 
    for coll in C.collections: 
        plt.gca().collections.remove(coll) 
    C = plt.contourf(f2) 
    plt.draw() 
    

    This answer is probably what you're looking for.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-24
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      相关资源
      最近更新 更多