Live graphing multiple subplots with matplotlib (python, raspberry pi)

Status
Not open for further replies.
Hello Ars, may I have your input?

I'm working on a project with python 2.7 and Raspberry Pi wherein I'm polling some sensors and upon determining which value is being received, logging the data and then updating a plot with the new value and a timestamp. Also note that commenting out the second if-statement block for temperature as well as the lines at the bottom for 'ax2' makes the program function properly and will update the pressure subplot(ax1) every time the pressure value is received. My problem is when I want to graph both pressure(ax1) and temperature(ax2) I always get this error:

ValueError: x and y must have same first dimension

At this point I just don't know how to say "Okay, grab whatever sensor value is being received at the moment, log the value locally, make sure the arrays you need are the same dimension, then update the respective subplot with a current timestamp and the value that was last received, and repeat."
Finally, is there a more graceful way around "global arrayCounter" in the way that I am using it? The purpose is to avoid this error:
UnboundLocalError: local variable 'arrayCounter' referenced before assignment
The impression I get is to avoid globals if possible.

Code:
import os
import serial
import time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

cwd = os.getcwd()
ser = serial.Serial('/dev/ttyAMA0')

arrayCounter = 0

pressure_log = open(cwd + '/logs/pressure','a')
temperature_log = open(cwd + '/logs/temperature', 'a')

unixtimeArray = []
pressureArray = []
temperatureArray = []

#create a figure with two subplots
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)

#define the function for use in matplotlib.animation.funcAnimation
def animate(i):
    #global arrayCounter is to fix: "UnboundLocalError: local variable 'arrayCounter' referenced before assignment"
    global arrayCounter

    #grab preformatted data from serial connection
    data = ser.readline()

    #split data to check which value it is. then log respective value locally and get timestamps
    if data.split(":")[0] == "Pressure":
        timestamp = (time.strftime("%H:%M:%S"))
        pressure_log.write('{0},{1}\n'.format(timestamp, data.split(":")[1]))
        unixtime = time.mktime(time.localtime())
        unixtimeArray.append(float(unixtime))
        pressureArray.append(float(data.split(":")[1].rstrip()))

        #increment arrayCounter to keep the subplots from exceeding 30 displayed values at a time
        arrayCounter=arrayCounter+1
        if(arrayCounter>29):
            unixtimeArray.pop(0)
            pressureArray.pop(0)
    if data.split(":")[0] == "Temperature":
        timestamp = (time.strftime("%H:%M:%S"))
        pressure_log.write('{0},{1}\n'.format(timestamp, data.split(":")[1]))
        unixtime = time.mktime(time.localtime())
        unixtimeArray.append(float(unixtime))
        temperatureArray.append(float(data.split(":")[1].rstrip()))
        arrayCounter=arrayCounter+1
        if(arrayCounter>29):
            unixtimeArray.pop(0)
            temperatureArray.pop(0)

    #populate variables for display in the subplots
    xar = unixtimeArray
    yar = pressureArray
    zar = temperatureArray
    ax1.clear()
    ax1.plot(xar,yar)
    ax2.clear()
    ax2.plot(xar,zar)

while True:
    ani = animation.FuncAnimation(fig, animate, interval=1000)
    plt.show()
 
I think you can fix the ValueError: error by making a separate time array for the pressure and the temperature. I think the problem is that the size your time array is is the size of the pressure array plus the size of the temperature array because you are adding an element to the time array whenever you read either the temperature or the pressuree. That's why it works when you only read and plot one of the arrays.
 

ahankinson

Wise, Aged Ars Veteran
117
A few things, some relatively minor:

1. A pet peeve of mine, so take it with a grain of salt, but I feel all executable scripts should be called using:
Code:
if __name__ == "__main__":

2. I caught a couple bugs just by using an editor with syntax checking. For example, your temperature_log variable is declared but not used, since you are actually writing to your pressure_log in that section. You might try Sublime with the Anaconda plugin.

3. You can use a mutable variable to store a count and mutate that if you want to avoid using globals.

Code:
arrayCounter = {'count':0}

def animate(i):
    count = arrayCounter['count']
    ... magic
    count += 1

4. You can save a few operations by storing the log type and data first:

Code:
        log = data.split(":")
        logtype = log[0]
        logdata = log[1].rstrip()

5. Your inner if is a mutually exclusive one so you can use elif instead of two separate ifs.
 

ahankinson

Wise, Aged Ars Veteran
117
I suspect the problem is that matplotlib needs constant-length arrays to plot two on the same plot. For each 'tick' of the animate function it will need to know what value to write for that instant. So if there are no updated values for the 'pressure' plot, for example, it will need to assume that the graph value for that tick is constant. Right now you're popping the values out independently once they reach 29 frames, so you get mismatched array lengths.

If you need to, you can also make use of the fargs argument to the animation function to pass in a counter value to the animation.

I'm not sure you need the `while` loop -- shouldn't the animation function be polling every 1000ms anyway?
 
Status
Not open for further replies.