Skip to content Skip to sidebar Skip to footer

How To Use Funcanimation To Update And Animate Multiple Figures With Matplotlib?

Trying to create a program that reads serial data and updates multiple figures (1 line and 2 bar charts for now but could potentially be more). Using 3 separate calls to FuncAnimat

Solution 1:

Echoing @ImportanceOfBeingErnest's comment, the obvious solution would be to use 3 subplots and only one FuncAnimation() call. You simply have to make sure your callback function returns a list of ALL artists to be updated at each iteration.

One drawback is that the update will happen a the same interval in all 3 subplots (contrary to the different timings you had in your example). You could potentially work around that by using global variables that count how many time the function has been called and only do some of the plots every so often for example.

#figure 
fig = plt.figure(1)
# subplot for current
ax1 = fig.add_subplot(131, xlim = (0,100), ylim = (0,500))
line, = ax1.plot([],[])
ax1.set_ylabel('Current (A)')

#subplot for voltage
ax2 = fig.add_subplot(132)
rects1 = ax2.bar(ind1, voltV, width1)
ax2.grid(True)
ax2.set_ylim([0,6])
ax2.set_xlabel('Cell Number')
ax2.set_ylabel('Voltage (V)')
ax2.set_title('Real Time Voltage Data')
ax2.set_xticks(ind1)

#subplot for temperature
ax3 = fig.add_subplot(133)
rects2 = ax3.bar(ind2, tempC, width2)
ax3.grid(True)
ax3.set_ylim([0,101])
ax3.set_xlabel('Sensor Number')
ax3.set_ylabel('temperature (C)')
ax3.set_title('Real Time Temperature Data')
ax3.set_xticks(ind2)

defupdateAmps(frameNum):

    try:
    #error check for bad serial data
        serialString = serialData.readline()
        serialLine = [float(val) for val in serialString.split()]
        print (serialLine)

        if (len(serialLine) == 5):
            voltV[int(serialLine[1])] = serialLine[2]
            tempC[int(serialLine[3])] = serialLine[4]
            currentA.append(serialLine[0])
            if (len(currentA)>100):
                currentA.popleft()

        line.set_data(range(100), currentA)

    except ValueError as e:
    #graphs not updated for bad serial dataprint (e)

    return line,

#function to update real-time voltage datadefupdateVolts(frameNum):

    for rects, h inzip(rects1,voltV):
        rects.set_height(h)

    return rects1

#function to update real-time temperature datadefupdateTemp(frameNum):

    for rects, h inzip(rects2,tempC):
        rects.set_height(h)

    return rects2

defupdateALL(frameNum):
    a = updateAmps(frameNum)
    b = updateVolts(frameNum)
    c = updateTemp(frameNum)
    return a+b+c

animALL = animation.FuncAnimation(fig, updateALL,
                                interval = 20, blit = True)

Post a Comment for "How To Use Funcanimation To Update And Animate Multiple Figures With Matplotlib?"