[我有一个称为vars
的数据框,我试图绘制一个动画的折线图,每一列都是一条线(日期列除外,它是x轴)。
data var_brl var_ars var_bob var_clp var_cop var_mxn var_pen var_pyg var_uyu
0 01/01/2020 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
1 02/01/2020 0.17 -0.10 0.14 -0.36 -1.01 -0.49 -0.41 0.41 0.16
2 03/01/2020 1.19 -0.22 0.07 1.65 -1.01 -0.04 0.11 0.49 -0.38
3 04/01/2020 1.19 -0.22 0.07 1.65 -1.01 -0.04 0.11 0.49 -0.38
4 05/01/2020 1.19 -0.22 0.07 1.65 -1.01 -0.04 0.11 0.49 -0.38
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
135 15/05/2020 45.71 13.03 -0.07 10.07 18.98 26.43 3.78 1.81 18.19
136 16/05/2020 45.71 13.03 -0.07 10.07 18.98 26.43 3.78 1.81 18.19
137 17/05/2020 45.71 13.03 -0.07 10.07 18.98 26.43 3.78 1.81 18.19
138 18/05/2020 42.32 13.28 0.00 8.92 17.20 25.49 3.47 2.09 18.06
139 19/05/2020 43.20 13.43 0.00 8.88 16.69 25.08 3.46 2.10 18.06
我正在使用的代码:
fig, ax = plt.subplots(figsize=(16, 8))
plt.style.use('ggplot')
months = mdates.MonthLocator()
months_fmt = mdates.DateFormatter('%m/%Y')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)
limx_i = vars.iloc[0, 0]
limx_f = vars.iloc[-1, 0]
limy_f = vars.iloc[:, 1:].max().max()
limy_i = vars.iloc[:, 1:].min().min()
ax.set_xlim(limx_i, limx_f + dt.timedelta(days=30))
ax.set_ylim(limy_i, limy_f)
line, = [ax.plot([], [], lw=2)]
for i in range(1, vars.shape[1]):
def animate(i):
line.set_data(vars['data'], vars.iloc[:, i])
return line,
ani = animation.FuncAnimation(fig, animate, frames=140, interval=20, blit=True)
ax.tick_params(bottom=False, top=False, right=False, left=False)
ax.set_ylabel('Oscilação acumulada %')
plt.grid(False)
for key, spine in ax.spines.items():
spine.set_visible(False)
plt.tight_layout()
plt.show()
我需要遍历数据框,因为无论列数如何,代码都必须有效。
它绘制上面的图像(没有线条),然后引发以下错误:
AttributeError: 'list' object has no attribute 'set_data'
我对动画没有任何经验,因此将不胜感激。谁能看到我在做什么错?
您要避免使用vars
作为变量名,因为它是Python中的内置函数。您可以按下面的for循环所示遍历各列。可以通过以下方式使用matplotlib的交互模式来实现动画:
import pandas as pd
import matplotlib
matplotlib.use("nbagg")
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
#your dataframe which will be different than what I have used here
df = pd.read_csv('example.txt',sep='\s+')
fig, ax = plt.subplots()
plt.style.use('ggplot')
months = mdates.MonthLocator()
months_fmt = mdates.DateFormatter('%m/%Y')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)
limx_i = df.iloc[0, 0]
limx_f = df.iloc[-1, 0]
limy_f = df.iloc[:, 1:].max().max()
limy_i = df.iloc[:, 1:].min().min()
#ax.set_xlim(limx_i, limx_f + dt.timedelta(days=30))
#ax.set_ylim(limy_i, limy_f)
ax.tick_params(bottom=False, top=False, right=False, left=False)
ax.set_ylabel('y')
ax.set_xlabel('x')
plt.grid(False)
line = ax.plot([], [], lw=2)
plt.ion() # set interactive mode
plt.show()
for column in df.loc[:, df.columns != 'data']:
line = ax.plot(df['data'], df[column], lw=2,label=column)
plt.legend()
plt.gcf().canvas.draw()
plt.pause(1)# set the time to desired interval, currently set at 1 second.