首页 > 解决方案 > 使用 python 子图绘制条形图和折线图的动画图

问题描述

我能够使用下面链接中的建议绘制动画图。

matplotlib 动画多个数据集

我的代码在这里。

tt = time_hr.values[:,0] 
yy1 =data1.values[:,0]
yy2 =data2.values[:,0]

fig, ax = plt.subplots()

line1, = ax.plot(tt, yy1, color='k')
line2, = ax.plot(tt, yy2, color='r')

def update(num, tt, yy1, yy2, line1, line2):
   line1.set_data(tt[:num], yy1[:num])
   line1.axes.axis([0, 1, 0, 2500])

   line2.set_data(tt[:num], yy2[:num])
   line2.axes.axis([0, 1, 0, 2500])

   return line1,line2

ani = animation.FuncAnimation(fig, update, len(time_hr), fargs=[tt, yy1, yy2, line1,line2],interval=25, blit=True)
plt.show()

我还有其他条形图数据集,我使用下面的代码创建了动画条形图。

x_pos = np.arange(95)
fig = plt.figure()
ax = plt.axis((-1,96,0,1000))
def animate(i):
   plt.clf()
   pic = plt.bar(x_pos, data3.iloc[i,:], color='c')
   plt.axis((-1,96,0,1000))
   return pic,
ani = animation.FuncAnimation(fig, animate, interval=25, repeat=False)
plt.show()

我的最终目标是使用 subplot 函数在一个图中绘制动画条形图和折线图,以便条形图为 (1,1),折线图位于图的 (2,1) 位置。

有人可以帮我在 python 的一个图形窗口中创建动画条形图和折线图吗?更具体地说,如何将折线图和条形图结合在一个动画函数中?

根据下面的评论,我修改了这样的代码。

x_pos = np.arange(95)
tt = time_hr.values[:,0] 
yy1 =data1.values[:,0]
yy2 =data2.values[:,0]

fig, (ax1, ax2) = plt.subplots(nrows=2)
line1, = ax2.plot(tt, yy1, color='k')
line2, = ax2.plot(tt, yy2, color='r')
rects = ax1.bar(x_pos, data3.iloc[0,:], color='c')

def update(num, tt, yy1, yy2, x_pos, data3, line1, line2, rects):
    line1.set_data(tt[:num], yy1[:num])
    line1.axes.axis([0, 1, 0, 2500])

    line2.set_data(tt[:num], yy2[:num])
    line2.axes.axis([0, 1, 0, 2500])

    ax1.clear()
    rects= ax1.bar(x_pos, data3.iloc[num,:], color='c')
    ax1.axis((-1,96,0,1000))

    return line1,line2, rects

ani = animation.FuncAnimation(fig, update, len(time_hr), fargs=[tt, yy1, yy2, x_pos,data3, line1,line2,rects], interval=25, blit=True)

plt.show()

但我收到这样的错误消息。“AttributeError:‘BarContainer’对象没有属性‘set_animated’”

你能帮我如何解决这个错误吗?

标签: pythonmatplotlibanimation

解决方案


推荐阅读