Matplotlib:如何在单击启动动画的按钮后保存动画?

2024-10-01 13:29:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个森林火灾的小动画。我的密码在问题的最后。在

代码forestfire.py包含将把火蔓延到所有forest的函数。然后forestfire_test.pyforestfire.py导入为ff,然后我可以用鼠标点击matplotlib显示的数组来启动{}。在

在我提问之前,这里有一些信息:

  • 没有树:forest[i,j] = 0
  • 一棵树:forest[i,j] = 1
  • 着火的树:forest[i,j] = 2
  • 哈希:forest[i,j] = 3

基本上,forest是由1到0之间的数字组成的,大小为nxm的二维数组。函数onclick点燃了forest,而{}仍然有树在启动,函数spreadfire也在蔓延。在

使用函数onclick我可以让森林着火(如果我单击数组,树将变为红色),使用函数start我可以执行代码,这要归功于按钮Start。在

现在的问题是,我第一次执行代码时,它不知道什么是ani(NameError: global name 'ani' is not defined)–这很正常,因为我甚至在调用函数start之前调用了动画ani(通过尝试保存它)。但是如果我试图将ani保存在函数start中,我会得到一个空白的绘图——这也是正常的。在

总而言之,我需要在调用函数start之后保存动画,但是我不能在函数start的末尾保存它,否则我将得到一个空白的绘图。有人能告诉我该怎么做吗?在

PS:我使用Spyder和IPython控制台,如果我的解释不够清楚,请告诉我。在

森林火灾_测试.py

import forestfire as ff
import numpy as np

import matplotlib.pylab as plt
import matplotlib.colors as mcolors
from matplotlib import cm

from matplotlib.widgets import Button, Cursor


global forest
forest = np.random.rand(100,100)


# Colormap
greens = cm.Greens(np.linspace(0,1, num=50))
greensfill = cm.Greens(np.ones(25))
red = [(1,0,0,1)]*len(greens)
gray = [(.5,.5,.5,1)]*len(greens)

colors = np.vstack((greens, greensfill, red, gray))
mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

# Figure
fig, ax = plt.subplots(figsize=(10,5))
fig.subplots_adjust(right=1.3)
im = ax.imshow(forest, animated=True, cmap = mycmap, interpolation="none", origin='lower', vmin=0, vmax=3.5)


ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.tick_params(direction='out')


cursor = Cursor(ax, useblit=True, color='red', linewidth=1)
plt.show()


# Coordinates
def onclick(event):
    x, y = int(event.xdata), int(event.ydata)
    forest[y,x] = 2.
    im.set_data(forest)
    fig.canvas.draw_idle()


fig.canvas.mpl_connect('button_press_event', onclick)   


# Start button
def start(event):
    global ani
    ani = ff.forestfire(forest)

button_ax = plt.axes([0.15, 0.45, 0.2, 0.1])
button = Button(button_ax, 'Start', color='lightgrey', hovercolor='grey')
button.on_clicked(start)


# Animation
ani.save("forestfire_test.mp4", writer = 'ffmpeg', fps=5, dpi=500)

在森林火灾.py

^{pr2}$

Tags: 函数pyimporteventmatplotlibasnp森林
1条回答
网友
1楼 · 发布于 2024-10-01 13:29:26

正如评论中提到的,这里有两个问题:

  1. 您需要在start函数中移动ani.save。这是因为ani只在按下开始按钮后定义。在
  2. plt.show应该只在脚本末尾调用。在

这样我就可以正常工作了,以脚本的形式运行(在Python2.7.10上,matplotlib 2.0.2上),因为单击“开始”按钮后,动画将作为mp4文件保存到当前目录中。在

除此之外,我需要将帧速率设置为6或更高,如a previous question中所注释的那样。在

相关问题 更多 >