简体   繁体   中英

Plot an animated line between two points (one is moving) in python

Here there´sa fixed point and a variable point, which changes his position every iteration. I would like to animate a line between these two points every iteration, as if there was a line changing his gradient.

Here is the code of these two points:

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

list_var_points = (1, 5, 4, 9, 8, 2, 6, 5, 2, 1, 9, 7, 10)

fig, ax = plt.subplots()
xfixdata, yfixdata = [14], [8]
xdata, ydata = [5], []
ln, = plt.plot([], [], 'ro', animated=True)
plt.plot([xfixdata], [yfixdata], 'bo')

def init():
    ax.set_xlim(0, 15)
    ax.set_ylim(0, 15)
    return ln,

def update(frame):
    ydata = list_var_points[frame]
    ln.set_data(xdata, ydata)
    return ln,          


ani = FuncAnimation(fig, update, frames=range(len(list_var_points)),
            init_func=init, blit=True)
plt.show()

Thank you!

The animated line can take 2 points instead of only one, such that both points are connected with a line.

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

list_var_points = (1, 5, 4, 9, 8, 2, 6, 5, 2, 1, 9, 7, 10)

fig, ax = plt.subplots()
xfixdata, yfixdata = 14, 8
xdata, ydata = 5, None
ln, = plt.plot([], [], 'ro-', animated=True)
plt.plot([xfixdata], [yfixdata], 'bo', ms=10)

def init():
    ax.set_xlim(0, 15)
    ax.set_ylim(0, 15)
    return ln,

def update(frame):
    ydata = list_var_points[frame]
    ln.set_data([xfixdata,xdata], [yfixdata,ydata])
    return ln,          


ani = FuncAnimation(fig, update, frames=range(len(list_var_points)),
            init_func=init, blit=True)
plt.show()

在此处输入图片说明

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