如何加速Matplotlib?

时间:2017-03-20 15:53:49

标签: python python-2.7 matplotlib

我是Matplotlib的新手,这就是为什么可能有一种更有效的方式来运行我的程序。

它绘制了一堆不同颜色的点(取决于某些因素)。它在当前颜色状态的循环中不断产生新图像。 基本上它看起来像这样:

import matplotlib.pyplot as plt

def getColour():
#calculate some stuff with x and y and the changing factors

while True: 
   fig = plt.figure(figsize=(17,10))
   plt.scatter(x, y , c=getColour())
   plt.show()
   plt.close(fig)

我也尝试了clf()。然而,它并没有改变节奏。有人有想法吗?我究竟做错了什么?

谢谢!

编辑: 目标是每次经过循环时产生一张图片。由于我的程序执行速度很慢,我的问题是是否有办法让它运行得更快。 我正在使用python 2.7

1 个答案:

答案 0 :(得分:0)

像动画一样:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

ms_between_frames = 100
n_points = 100
x = np.arange(n_points, dtype=float) #EDIT
y = np.random.random(n_points)
z = np.random.random(n_points)

def getColour(x, y, z):
    c = np.empty((len(x),3))
    for i in range(len(x)):
        c[i] = [x[i]/n_points, z[i], 1.-z[i]]
    return c

def update(frame_number):
    global x, y
    z = np.random.random(n_points)
    c = getColour(x, y, z)
    graph.set_color(c)

fig = plt.figure(figsize=(17,10))
ax = fig.add_subplot(111)
graph = ax.scatter(x, y , c=getColour(x, y, z))
animation = FuncAnimation(fig, update, interval=ms_between_frames)
plt.show()

编辑:使x保持浮点数,因此getColour内的除法不会返回0(也可能是/float(n_points)

顺便说一下,应该可以只定义一个函数来更新颜色,具体取决于你需要这样做的参数,以避免调用开销。

相关问题