简体   繁体   English

我正在尝试在 matplotlib 中制作轮廓 plot animation

[英]I am trying to make a contour plot animation in matplotlib

I have 16 contour plots with changing titles and I want to just create an animation from the 16 contour plots.我有 16 个标题不断变化的等高线图,我只想从 16 个等高线图中创建一个 animation。

I first set up the images and the data below, but I am having little luck in the animation part.我首先设置了下面的图像和数据,但我在 animation 部分运气不佳。 I am trying to follow this example but I'm struggling: Increase the speed of redrawing contour plot in matplotlib我正在尝试遵循此示例,但我很挣扎: 在 matplotlib 中增加重绘轮廓 plot 的速度

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()

在此处输入图像描述

My attempt at the animation part:我在 animation 部分的尝试:

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'

The error doesn't recognize contour or contourf... How do I make a movie/animation of the 16 contour plots?该错误无法识别轮廓或轮廓...如何制作 16 个等高线图的电影/动画?

This will give you an array with all subplots:这将为您提供一个包含所有子图的数组:

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

You have to index the ax array to plot on the subfigures:您必须将ax数组索引到子图上的 plot :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM