简体   繁体   中英

How to speed up Matplotlib?

I am new to Matplotlib and that's why there might be a more efficient way to run my program.

It is plotting a bunch of points with different colours (depending on some factors). It is constantly producing new pictures in a loop of the current colour state. Basically it looks like this:

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)

I was trying out clf() as well. However, it didn't change the pace at all. Does anyone have ideas? What am I doing wrong?

Thank you!

Edit: The target is to produce a picture each time it goes through the loop. Since my program is doing this quite slowly, my question is whether there is a way to make it run faster. I am working with python 2.7

Something like an animation:

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

EDIT: made x hold floats so the division inside getColour would not return 0 (could also have made /float(n_points) )

By the way, it should be possible to define only one function to update the colours, depending on the arguments you require to do so, to avoid the call overhead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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