动画Python Matplotlib图中的更新速度慢。如何让它更快?

时间:2016-01-12 08:41:30

标签: python python-3.x matplotlib

我正在使用matplotlib来运行实时船模拟器。下面的代码是一个更短的代码,用于说明我使用matplotlib创建动画图的方法。该代码在特定坐标上绘制一个简单的船并旋转它。

如果我希望这个绘图的渲染速度超过14fps,我应该使用什么方法?例如,有没有办法在matplotlib中获得GPU渲染?

import time
import math

from matplotlib import pyplot as plt
import matplotlib as mpl
from matplotlib.patches import Polygon

# boat dimensions
l = 10.0 #m
w = 3.0 #m
b = 2.0 #m

fig = plt.figure(figsize=(3,3))
subplot_def = 111
ax = fig.add_subplot(subplot_def)
plt.ion() # set plot to animated
fig.canvas.draw()

plt.show(block=False)

prev_time = time.time() # for getting fps
simulation_start_time = time.time() # how long the simulation has been running
while True:
    time_debug = time.time()
    current_time = time.time() - simulation_start_time

    # set boat coordinates
    boat_x = 100*math.sin(current_time / 100.0)
    boat_y = 10*math.sin(current_time / 100.0)
    boat_z = current_time / 2*math.pi

    # rotate the boat
    ts = ax.transData
    tr = mpl.transforms.Affine2D().rotate_around(boat_x, boat_y, boat_z)
    t = tr + ts
    print("transform: {:.3f} ms".format((time.time() - time_debug)*1000), end=', ')
    time_debug = time.time()

    # clear the previous plot
    ax.clear()
    print("clear: {:.3f} ms".format((time.time() - time_debug)*1000), end=', ')
    time_debug = time.time()

    # add boat
    boat1 = Polygon(
        [[-w/2.0 + boat_x, -l/2.0 + boat_y], [0 + boat_x, l/2.0 + boat_y], [w/2.0 + boat_x, -l/2.0 + boat_y]],
        closed=True, color='lightsteelblue', transform=t
    )
    ax.add_artist(boat1)

    # set plot limits
    ax.set_xlim([boat_x - 10, boat_x + 10])
    ax.set_ylim([boat_y - 10, boat_y + 10])

    # update plot
    fig.canvas.update()

    print("draw plot: {:.3f} ms".format((time.time() - time_debug)*1000), end=', ')
    time_debug = time.time()

    print('total plot update rate: {:.3f} ms or {:.1f} fps'.format((time.time()-prev_time)*1000, 1/(time.time()-prev_time)))
    prev_time = time.time()

    plt.pause(0.001)

运行脚本的输出:

transform: 0.000 ms, clear: 25.002 ms, draw plot: 0.000 ms, total plot update rate: 67.007 ms or 14.9 fps
transform: 0.000 ms, clear: 31.003 ms, draw plot: 1.000 ms, total plot update rate: 76.008 ms or 13.2 fps
transform: 0.000 ms, clear: 26.002 ms, draw plot: 1.000 ms, total plot update rate: 73.007 ms or 13.7 fps

1 个答案:

答案 0 :(得分:1)

使用FuncAnimation而不是在一个大循环中进行所有计算和绘图。

以下是matplotlib animation examples

的示例
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim(0, 1)

def update(data):
    line.set_ydata(data)
    return line,

def data_gen():
    while True: yield np.random.rand(10)

ani = animation.FuncAnimation(fig, update, data_gen, interval=100)
plt.show()