Animer les flèches dans matplotlib

Sep 16 2020

J'ai animé une ligne dans matploltib, la sortie du code ressemble à ceci:

Mais ce que je veux, c'est qu'au lieu de cette ligne, le code doit tracer une flèche (c'est-à-dire une pointe de flèche à la fin de la ligne), voici l'extrait de code:

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

fig, ax = plt.subplots(figsize=(12, 8))
ax.set(xlim=(0, 104), ylim=(0, 68))

x_start, y_start = (50, 35)
x_end, y_end = (90, 45)

x = np.linspace(x_start, x_end, 50)
y = np.linspace(y_start, y_end, 50)

line, = ax.plot(x, y)

def animate(i):
    line.set_data(x[:i], y[:i])
    return line,


ani = animation.FuncAnimation(
    fig, animate, interval=20, blit=True, save_count=50)


plt.show()

Que dois-je ajouter / modifier dans le code afin que je puisse obtenir une flèche au lieu de la ligne dans la sortie?

Réponses

3 Konqui Sep 16 2020 at 08:10

Répondre

Vous pouvez utiliser ax.arrowpour tracer la flèche.
Notez que vous devez effacer le graphique avec ax.cla()et ajuster les limites des axes avec ax.set()à chaque itération.

Code

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

fig, ax = plt.subplots(figsize=(12, 8))
ax.set(xlim=(0, 104), ylim=(0, 68))

x_start, y_start = (50, 35)
x_end, y_end = (90, 45)

N = 50
x = np.linspace(x_start, x_end, N)
y = np.linspace(y_start, y_end, N)

def animate(i):
    ax.cla()
    ax.arrow(x_start, y_start,
             x[i] - x_start, y[i] - y_start,
             head_width = 2, head_length = 2, fc = 'black', ec = 'black')
    ax.set(xlim = (0, 104), ylim = (0, 68))

ani = animation.FuncAnimation(fig, animate, interval=20, frames=N, blit=False, save_count=50)

plt.show()

Animation

V.Hunon Sep 16 2020 at 06:41

Jetez peut-être un coup d'oeil ici

Vous pouvez simplement changer la fonction de ligne en fonction de flèche. Mais notez que vous devez d'abord calculer le point final de la flèche, car selon la documentation, vous ne pouvez spécifier que la longueur dx, dy. En utilisant Pythagoras, le point de départ serait x[0], y[0]et dx, dyest le point final traduit.

Je pense que vous pouvez résoudre ce problème maintenant par vous-même.