简体   繁体   中英

Matplotlib: Update positions and velocities in quiver()

I have a large number of files that contain data from a simulation. I want to use each file to save an image of a vector field using quiver(). Unfortunately, my method is really slow.

Here is a minimal working example of my code:

import time
import numpy as np
import matplotlib.pyplot as plt

# Number of files
N = 100000

n_points = 10000

for k in range(N):
    t0 = time.time()

    fig, ax = plt.subplots(1,1, figsize=(5,5))
    ax.axis("off")

    # Get data
    data = np.random.uniform(-1,1,size=(n_points, 4))
    x,y,vx,vy = data[:,0], data[:,1], data[:,2], data[:,3]

    # Normalize and scale velocities
    norm = np.hypot(vx,vy)
    vx = vx / norm 
    vy = vy / norm 
    vx *= 0.05
    vy *= 0.05

    # Plot vectorfield
    ax.quiver(x, y, vx, vy, scale=1., width=0.001, units="xy")

    plt.subplots_adjust(bottom=0, right=1, top=1, left=0)
    plt.savefig("image_" + str(k) + ".png", dpi=300)
    plt.close()

    print("%.2f" % (100.*(k+1.)/N) + " %" + " %.2f" % (time.time()-t0) + " images/s", end="\r")

Any ideas how I can speed things up? Right now I can save about one image every second. Given the large amount of data files, this takes several hours on my machine to complete.

Thank you!

EDIT

I modified the code above according to the recommendations of @ImportanceOfBeingErnest. However, the code is still really slow.

import time
import numpy as np
import matplotlib.pyplot as plt

# Number of files
N = 20

n_points = 20000

fig, ax = plt.subplots(1,1, figsize=(5,5))
ax.axis("off")
plt.subplots_adjust(bottom=0, right=1, top=1, left=0)

for k in range(N):
    t0 = time.time()

    # Get data
    data = np.random.uniform(-1,1,size=(n_points, 4))
    x,y,vx,vy = data[:,0], data[:,1], data[:,2], data[:,3]

    # Normalize and scale velocities
    norm = np.hypot(vx,vy)
    vx = vx / norm 
    vy = vy / norm 
    vx *= 0.05
    vy *= 0.05

    # Plot vectorfield
    q = ax.quiver(x, y, vx, vy, scale=1., width=0.001, units="xy")
    plt.savefig("image_" + str(k) + ".png", dpi=300)
    #q.remove()
    ax.clear()

    #plt.close()
    t.append(time.time()-t0)
    print("%.2f" % (100.*(k+1.)/N) + " %" + " %.2f" % (time.time()-t0) + " s/images", end="\r")

Before any improvements it took about 1.71 seconds for one image on average. Using ax.clear() is even slower with 1.81 seconds per image. Using q.remove() is a little bit faster and results in 1.61 seconds per image. Any further suggestions?

将dpi更改为None,可将图像创建速度提高2。

plt.savefig("image_" + str(k) + ".png", dpi=None)

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