Animate arrows in matplotlib

Viewed 769

I animated a line in matploltib, the output of the code looks like this:

enter image description here

But what I want is instead of this line the code should plot an arrow (i.e. an arrowhead at the end of the line), here is the code snippet:

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

What should I add/change in the code so that I can get an arrow instead of the line in the output?

2 Answers

Answer

You can use ax.arrow to plot the arrow.
Note that you should clear the plot with ax.cla() and adjust axes limits with ax.set() at each iteration.

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

enter image description here

Maybe have a look at here

You could simply change the line function to arrow function. But note that you would first need to calculate the end point of the arrow, since according to the docs, you can only specify the length dx,dy. By using pythagoras, the starting point would be x[0], y[0] and dx,dy is the translated endpoint.

I think you can solve that now on your own.

Related