我想在 python 动画中添加一个图例,如下line.set_label()所示。它类似于plt.plot(x,y,label='%d' %*variable*).
但是,我发现代码在这里不起作用。动画仅显示线条变化,但没有可用的标签或图例。我该如何解决这个问题?
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(0, 100))
N = 3
lines = [plt.plot([], [])[0] for _ in range(N)]
def init():
for line in lines:
line.set_data([], [])
return lines
def animate(i):
for j,line in enumerate(lines):
line.set_data([0, 2], [10*j,i])
line.set_label('line %d, stage %d'%(j,i))
return lines
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)
plt.show()
Run Code Online (Sandbox Code Playgroud) 我有一个来自 matplotlib 示例的非常简单的代码:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim(0, 1)
def update(data):
line.set_ydata(data)
return line,
def data_gen():
while True: yield np.random.rand(10)
ani = animation.FuncAnimation(fig, update, data_gen, interval=1000)
anim.save('basic_animation.mp4', fps=30)
plt.show()
Run Code Online (Sandbox Code Playgroud)
如果我不使用 anim.save() 函数,一切都是正确的。但是,当我想保存它时,它会报告:
IOError Traceback (most recent call last)
<ipython-input-6-8948bc3b3f5c> in <module>()
16
17 ani = animation.FuncAnimation(fig, update, data_gen, interval=1000)
---> 18 anim.save('basic_animation.mp4', fps=30)
19 plt.show()
....(traceback details are omitted here)
/home/xin/anaconda2/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in print_raw(self, filename_or_obj, *args, …Run Code Online (Sandbox Code Playgroud) int main()
{
int a;
int* b;
a = 40;
b = &a;
printf("the address of a is %p, and the value of a is %d \n",&a, a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我发现,无论(void*)&a和&a打印相同的事情.那么人们为什么还要加(void*)?这只是一种习惯吗?
我正在学习 python,我发现 a=[1,2,3] 与 a=array([1,2,3]) 几乎相同,尽管后者在打印时会显示 [1 2 3] 。它们之间有什么区别?