Search code examples
pythonmatplotlibsocketsgraphtcp

matplotlib pops up new graph for each new value instead of updating graph


I am very new to Python and coding in general so please go easy on me. This is my scenario:

I am trying to write a script that will communicate with the controller of a vacuum chamber through TCP over ethernet to read data (i.e. pressure, temperature, valve status, etc.) and graph the data using matplotlib. eventually I will be using a front end GUI to view all of these reading, but currently I am just trying to do a simple live graph with matplotlib and the pressure reading. The communications work like this: send a command over TCP (command for asking vacuum pressure is '?VP\r') and the controller responds with something like VP:3.58E-7\r. I am able to communicate fine with the controller over TCP and get a response like I would expect, but when I try to plot the data using matplotlib, each new reading is a new graph. Any help would be greatly appreciated!

Here is the code I am currently working with (not all of it is original, some of it I got from other threads here and tried modifying it to fit my needs as I am just learning):

import socket
import sys
import time
import binascii
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib.animation import FuncAnimation
from matplotlib import pyplot
import pylab
from datetime import datetime

#TVAC IP and Port
target_host = "10.1.2.121"
target_port = 50

print()

#trying to open a TCP socket
try:
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((target_host,target_port))
except socket.error:
    print("Socket Not Created!  ¯\(°_o)/¯")
    sys.exit()
print("Socket Created   (⌐⊙_⊙)")
print()
print("Socket Connected To " + target_host)
print()

#matplotlib setup
plt.yscale('symlog')
pyplot.grid(True)
plt.ion()

#command to read vacuum pressure
cmd = "?VP"

#carriage return
CR = "\r"

#live plot loop
while (cmd != "shutdown"):
    try:
        
        #send command and receive data ex/ VP: 3.23E-7
        client.send(bytes(cmd + CR  + '\0','ascii'))
        response = client.recv(1024).decode('ascii')
        response2 = response[3:-1]
        response3 = response2.replace("E","e")
        response4 = float(response3)
        print(response3)
        

        
        time.sleep(0.2)
    except socket.error:
        print("Failed to send command")
        

        
    #animate the data on a plot graph
    x_data, y_data = [], []
        
    figure = pyplot.figure()
    line, = pyplot.plot_date(x_data, y_data, '-')

    def update(frame):
            
        x_data.append(datetime.now())
        y_data.append(response4)
        line.set_data(x_data, y_data)
        figure.gca().relim()
        plt.gca().ticklabel_format(axis='y',style='sci',scilimits=(0,0))
        figure.gca().autoscale_view()
               
        return line,
anim = animation.FuncAnimation(figure, update, repeat=False, interval=200, cache_frame_data=False)

 
pyplot.show()           


Solution

  • Calling plt.figure will create a new figure to plot on. Move that line from the while loop to be before (outside) the loop.