【问题标题】:I am trying to make a contour plot animation in matplotlib我正在尝试在 matplotlib 中制作等高线图动画
【发布时间】:2021-06-23 08:12:33
【问题描述】:

我有 16 个标题不断变化的等高线图,我只想从 16 个等高线图中创建一个动画。

我首先设置了下面的图像和数据,但我在动画部分运气不佳。 我正在尝试遵循此示例,但我很挣扎: Increase the speed of redrawing contour plot in matplotlib

import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
import time 
import pandas as pd 



title = pd.date_range('1968-1-1','1969-04-01', 
                  freq='MS').strftime("%b %Y").tolist()
    
    data = np.random.rand(16,30,40)
    
    fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(15,10)) #15, 25 
    for i,t,ax in zip(range(16),title, axes.ravel()):
        x = ax.contourf(data[i],levels = np.arange(-.6,.6,.03), extend='both')
        ax.set_title(t)
        ax.grid()
    cbaxes = fig.add_axes([1.02,.5,.05,.2]) # [left, bottom, width, height],
    cbar = fig.colorbar(x, cax = cbaxes, fraction=.02)
    cbar.set_label('cb', labelpad=15, y=.5, rotation=90)
    plt.tight_layout()
    plt.show()

我在动画部分的尝试:

levels = np.arange(-.6,.6,.03)

fig, ax = plt.subplots(nrows=4, ncols=4, figsize=(15,10)) #15, 25

p = [ax.contour(data[0],levels=levels)]

def update(i):
    for tp in range(16):
        tp.remove()
    p[0] = ax.contour(data[i], levels) 
    t[1:] = t[0:-1]
    t[0] = time.time()
    timelabel.set_text("{:.3f} fps".format(-1./np.diff(t).mean()))  
    return p[0]

ani = matplotlib.animation.FuncAnimation(fig, update, frames=16, 
                                         interval=30, blit=True, repeat=True) ## increasing interval slows it down!
ani.save("test.mp4")
plt.show()


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-57-d70067088c5b> in <module>
      3 fig, ax = plt.subplots(nrows=4, ncols=4, figsize=(15,10)) #15, 25
      4 
----> 5 p = [ax.contour(data[0],levels=levels)]
      6 
      7 def update(i):

AttributeError: 'numpy.ndarray' object has no attribute 'contour'

错误无法识别轮廓或轮廓...如何制作 16 个轮廓图的电影/动画?

【问题讨论】:

    标签: python numpy matplotlib animation jupyter


    【解决方案1】:

    这将为您提供一个包含所有子图的数组:

    fig, ax = plt.subplots(nrows=4, ncols=4, figsize=(15,10)) #15, 25
    

    您必须索引ax 数组才能在子图上绘图:

    # plot on the upper left subfigure
    ax[0,0].contour(data[0],levels=levels)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多