我一直在尝试创建水平条形图,其中标题和数据在每一帧中都会发生变化。我遇到的问题是,如果我使用blit=True
,则数据会更新,但标题不会更新。当我使用blit=False
时,标题会更改,但数据不会更改(仅会增加)。
我已经阅读了数十个答案,并尝试了所有内容,包括 set_title 和 set_text ,但是我在总体损耗。谢谢您的帮助。
%matplotlib
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import csv
people = ('','Jim', 'Dan')
plt.rcdefaults()
fig, ax = plt.subplots()
y_pos = np.arange(len(people))
ax.set_xlim(0,10)
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()
ax.set_xlabel('Skill')
titleList=['Basketball','Hockey']
df=[[0,5,7],[0,4,9]]
title = ax.text(0.5,0.95, "Test", bbox={'facecolor':'w', 'alpha':0.5, 'pad':5},transform=ax.transAxes, ha="center")
def animate(i):
# Example data
while i<2:
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel(titleList[i])
performance=df[i]
title.set_text(str(titleList[i]))
line= ax.barh(y_pos, performance, align='center',
color='blue', ecolor='None')
return line
ani = animation.FuncAnimation(fig,animate, frames=5, blit=True
,interval=2000,repeat=False)
plt.show()
答案 0 :(得分:1)
您用FuncAnimation()
呼叫frames=5
,因此animate(i)
会尝试通过titleList[i]
设置标签和标签,但是只有2个条目。特别是对于blit=True
,这会引发错误。
您的animate()
函数返回line
;如果我们print(line)
,则发现它更像是<BarContainer object of 3 artists>
而不是一条线,即barh()
的三个矩形。您应该将barh()
存储在rects
中,然后再存储return [rect for rect in rects]
,请参见this question
完整代码:
import pandas as pd
import matplotlib as mpl ## uncomment this if you are running this on a Mac
mpl.use('TkAgg') ## and want to use blit=True
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import csv
people = ('','Jim', 'Dan')
plt.rcdefaults()
fig, ax = plt.subplots()
y_pos = np.arange(len(people))
ax.set_xlim(0,10)
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()
ax.set_xlabel('Skill')
titleList=['Basketball','Hockey']
df=[[0,5,7],[0,4,9]]
def animate(i):
# Example data
while i<2:
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel(titleList[i])
performance=df[i]
title = ax.text(0.5,0.95,str(titleList[i]), bbox={'facecolor':'w', 'alpha':0.5, 'pad':5},transform=ax.transAxes, ha="center")
rects = ax.barh(y_pos, performance, align='center',
color='blue', ecolor='None')
return [rect for rect in rects] + [title]
ani = animation.FuncAnimation(fig,animate, frames=2, blit=True
,interval=2000,repeat=False)
plt.show()