猿问

matplotlib 中的动画箭头

我在 matploltib 中对一行进行了动画处理,代码的输出如下所示:


但我想要的是代码应该绘制一个箭头(即行尾的箭头),而不是这一行,这是代码片段:


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

我应该在代码中添加/更改什么,以便我可以在输出中获得箭头而不是行?

墨色风雨
浏览 199回答 2
2回答

缥缈止盈

回答您可以用来ax.arrow绘制箭头。请注意,您应该在每次迭代时使用 清除绘图ax.cla()并调整轴限制ax.set()。代码import numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animationfig, 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 = 50x = 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()

长风秋雁

您只需将线函数更改为箭头函数即可。但请注意,您首先需要计算箭头的终点,因为根据文档,您只能指定长度 dx,dy。通过使用毕达哥拉斯,起点为x[0],y[0],为转换后的终点。dxdy我认为你现在可以自己解决这个问题。
随时随地看视频慕课网APP

相关分类

Python
我要回答