我有一个带线条的动画,现在我想标记点。
我尝试了 plt.annotate()
并尝试了 plt.text()
但标签没有移动。
这是我的示例代码:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_line(num, data, line):
newData = np.array([[1+num,2+num/2,3,4-num/4,5+num],[7,4,9+num/3,2,3]])
line.set_data(newData)
plt.annotate('A0', xy=(newData[0][0],newData[1][0]))
return line,
fig1 = plt.figure()
data = np.array([[1,2,3,4,5],[7,4,9,2,3]])
l, = plt.plot([], [], 'r-')
plt.xlim(0, 20)
plt.ylim(0, 20)
plt.annotate('A0', xy=(data[0][0], data[1][0]))
# plt.text( data[0][0], data[1][0], 'A0')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
interval=200, blit=True)
plt.show()
你能帮帮我吗?
我的下一步是: 我在这些点中有原点的向量。这些向量在每个动画步骤中改变它们的长度和方向。 我怎样才能使这些动画化?
没有动画,这个工作:
soa =np.array( [ [data[0][0],data[1][0],F_A0[i][0][0],F_A0[i][1][0]],
[data[0][1],data[1][1],F_B0[i][0][0],F_B0[i][1][0]],
[data[0][2],data[1][2],F_D[i][0][0],F_D[i][1][0]] ])
X,Y,U,V = zip(*soa)
ax = plt.gca()
ax.quiver(X,Y,U,V,angles='xy',scale_units='xy',scale=1)
首先非常感谢您快速且非常有帮助的回答!
我用这个解决了我的矢量动画问题:
annotation = ax.annotate("C0", xy=(data[0][2], data[1][2]), xycoords='data',
xytext=(data[0][2]+1, data[1][2]+1), textcoords='data',
arrowprops=dict(arrowstyle="->"))
在我写的“更新函数”中:
annotation.xytext = (newData[0][2], newData[1][2])
annotation.xy = (data[0][2]+num, data[1][2]+num)
更改向量的开始和结束位置(箭头)。
但是,如果我有 100 个或更多向量,那是什么?写是不可行的:
annotation1 = ...
annotation2 = ...
.
:
annotation100 = ...
我尝试了一个列表:
...
annotation = [annotation1, annotation2, ... , annotation100]
...
def update(num):
...
return line, annotation
并得到这个错误: AttributeError: 'list' 对象没有属性 'axes'
我能做什么?你有什么想法吗?
最佳答案
我来自 this question ,其中应更新同时使用 xy
和 xytext
的注释。看起来,为了正确更新注释,需要设置注释的属性 .xy
来设置注释点的位置并使用 .set_position()
注解的方法来设置注解的位置。设置 .xytext
属性没有任何效果——在我看来有些困惑。下面是一个完整的例子:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
fig, ax = plt.subplots()
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
L = 50
theta = np.linspace(0,2*np.pi,L)
r = np.ones_like(theta)
x = r*np.cos(theta)
y = r*np.sin(theta)
line, = ax.plot(1,0, 'ro')
annotation = ax.annotate(
'annotation', xy=(1,0), xytext=(-1,0),
arrowprops = {'arrowstyle': "->"}
)
def update(i):
new_x = x[i%L]
new_y = y[i%L]
line.set_data(new_x,new_y)
##annotation.xytext = (-new_x,-new_y) <-- does not work
annotation.set_position((-new_x,-new_y))
annotation.xy = (new_x,new_y)
return line, annotation
ani = animation.FuncAnimation(
fig, update, interval = 500, blit = False
)
plt.show()
结果看起来像这样:
如果版本很重要,此代码已在 Python 2.7 和 3.6 上使用 matplotlib 版本 2.1.1 进行了测试,在这两种情况下设置 .xytext
没有效果,而 .set_position ()
和 .xy
按预期工作。
关于python - 使用 matplotlib 为带有标签的点设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18351932/