带触发器的Matplotlib动画 [英] Matplotlib animation with trigger

查看:109
本文介绍了带触发器的Matplotlib动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此示例链接中给出的matplotlib 3d绘图动画

Consider the matplotlib 3d plot animation given in this example link

它以给定的50毫秒间隔为25帧动画.

It animates 25 frames with a given interval of 50milliseconds.

是否有其他脚本通过某种形式的触发输入来控制下一帧的移动?甚至是键盘输入?

Is there anyway to control the moving on to the next frame with some form of trigger input from another script? Or maybe even a keyboard entry?

推荐答案

如果您想手动"前进,请删除动画,然后在需要的地方直接调用 update()函数

If you want to advance "by hand", remove the animation, and simply call the update() function from wherever you need.

根据您的后端,您可能不一定必须显式重绘画布,因此我已在更新函数中添加了显式的 fig.canvas.draw_idle().

You may or may not have to explicitly redraw the canvas depending on your backend, so I've added an explicit fig.canvas.draw_idle() to the update function.

这是一个通过按键进行动画播放的示例:

Here is an example where the animation advances from a key press:

import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation

# Fixing random state for reproducibility
np.random.seed(19680801)


def Gen_RandLine(length, dims=2):
    """
    Create a line using a random walk algorithm

    length is the number of points for the line.
    dims is the number of dimensions the line has.
    """
    lineData = np.empty((dims, length))
    lineData[:, 0] = np.random.rand(dims)
    for index in range(1, length):
        # scaling the random numbers by 0.1 so
        # movement is small compared to position.
        # subtraction by 0.5 is to change the range to [-0.5, 0.5]
        # to allow a line to move backwards.
        step = ((np.random.rand(dims) - 0.5) * 0.1)
        lineData[:, index] = lineData[:, index - 1] + step

    return lineData


def update_lines(num, dataLines, lines):
    for line, data in zip(lines, dataLines):
        # NOTE: there is no .set_data() for 3 dim data...
        line.set_data(data[0:2, :num])
        line.set_3d_properties(data[2, :num])
    fig.canvas.draw_idle()
    return lines

# Attaching 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)

# Fifty lines of random 3-D lines
data = [Gen_RandLine(25, 3) for index in range(50)]

# Creating fifty line objects.
# NOTE: Can't pass empty arrays into 3d version of plot()
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]

# Setting the axes properties
ax.set_xlim3d([0.0, 1.0])
ax.set_xlabel('X')

ax.set_ylim3d([0.0, 1.0])
ax.set_ylabel('Y')

ax.set_zlim3d([0.0, 1.0])
ax.set_zlabel('Z')

ax.set_title('3D Test')

num = 0
def onkey(event):
    global num
    num += 1
    update_lines(num, data, lines)

cid = fig.canvas.mpl_connect('key_press_event', onkey)

plt.show()

这篇关于带触发器的Matplotlib动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆