Real-time plotting using the Matplotlib library in Python

Currently, I am attempting to visualize multiple data points being transmitted over the USART serial bus from a microcontroller using Python. It would be ideal if I could plot all this data simultaneously and in real-time.

Interestingly, when plotting a single graph, the data updates in real-time; however, when utilizing subplots, there is a noticeable delay even with only one subchannel being plotted. Can anyone shed light on why subplotting in Python seems to slow down the process?

I conducted some measurements regarding the time consumed by the update() function, which appears to be around 2ms or less. On the other hand, the data reception interval is every 5ms or longer. What steps can I take to enhance the processing speed?

Warm regards: Sebastian T.

Below is the code snippet:

import serial
import matplotlib.pyplot as plt
import matplotlib.animation as anim
import time
from collections import deque

#SERIAL#######################################################
try:
    ser = serial.Serial()
    ser.baudrate=115200;
    ser.port = 'COM7'
    ser.open()
except:
    ser.close()
    print('Problem occurred')

ser.flushInput()
ser.flushOutput()

#PLOT##########################################################

MAX_X = 250   #width of graph
MAX_Y = 70000  #height of graph

# initialize line to horizontal line on 0
line1 = deque([0.0]*MAX_X, maxlen=MAX_X)
line2 = deque([0.0]*MAX_X, maxlen=MAX_X)
line3 = deque([0.0]*MAX_X, maxlen=MAX_X)
line4 = deque([0.0]*MAX_X, maxlen=MAX_X)
line5 = deque([0.0]*MAX_X, maxlen=MAX_X)

plt.close('all')
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1)

l1, = ax1.plot([], [])
l2, = ax2.plot([], [])
l3, = ax3.plot([], [])
l4, = ax4.plot([], [])

l=[l1, l2, l3, l4]

for ax in [ax1, ax2, ax3, ax4]:
    ax.set_ylim(-(MAX_Y/2), MAX_Y/2)
    ax.set_xlim(-(MAX_X/2), MAX_X/2)
    ax.grid()

def update(fn, data):
    try:
        t = time.time()
        # prepare Data
        data_raw = ser.readline()
        data_raw = data_raw.split(',')
        data_raw = data_raw[1::2]

        # Update Plots
        line1.append(int(data_raw[0]))
        line2.append(int(data_raw[1]))
        line3.append(int(data_raw[2]))
        line4.append(int(data_raw[3]))

        # Set Data
        l[0].set_data(range(-MAX_X/2, MAX_X/2), line1)
        l[1].set_data(range(-MAX_X/2, MAX_X/2), line2)
        l[2].set_data(range(-MAX_X / 2, MAX_X / 2), line3)
        l[3].set_data(range(-MAX_X / 2, MAX_X / 2), line4)
        print(time.time() - t)

    except:
        print('exception')
        ser.close()

ani = anim.FuncAnimation(fig, update, fargs=(0,), frames=1, interval=100)
plt.show()

Answer №1

It is a common problem when the number of plotted data points increases. I encountered this issue while plotting real-time data from a D/A converter and found it necessary to clear the axis using cla() after approximately 500 data points were plotted.

The issue stems from consistently calling "def update," which results in a full refresh of the entire figure with all plotted points...it becomes evident that this process becomes increasingly inefficient over time.

Best regards, Dr Cobra

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize an npm package or Python script to convert a .3ds file to either .obj, .collada, or .g

I have a collection of .3ds format files that I need to convert into gltf format. Are there any tools available to directly convert them into either .gltf format or collada/.obj format? I have already explored npm packages for converting collada/.obj to g ...

Creating unique characters with Python Selenium

I am interested in creating drawings of characters A B C D on the canvas at using Selenium Action chains. import time from selenium.webdriver.common.action_chains import ActionChains def draw(action, offset_list): for offset in offset_list: a ...

Refresh the page with user input after a button is clicked without reloading the entire page, using Python Flask

My python/flask web page accepts user input and returns it back to the user without reloading the page. Instead of using a POST request, I have implemented Ajax/JavaScript to handle user input, process it through flask in python, and display the result to ...

I need help resolving this issue with OpenShift: ImportError - libmemcached.so.11 file cannot be located

I am using a python 2.7 cartridge with the Django framework and I want to integrate memcached into it. I have added the Memcached Cloud cartridge to my app and followed this guide to set up my project. In order to utilize the Django caching backend ' ...

What is the best way to utilize multiple gmail accounts within a python project using the gmail API?

I am currently working on a project that involves integrating multiple Gmail accounts. I have successfully added the first Gmail account and it is functioning smoothly. However, I encountered an issue when trying to add additional accounts. Upon checking G ...

Definition of a 3D array in Python 2.7

I attempted the following approach but it appears to be ineffective. If numpy is not an option, what would be the correct alternative? Appreciate your help. y = [[1]*4 for _ in range (4) for _ in range(4)] Thank you in advance, Alice ...

Only once is the field in the Odoo table

My situation involves a column labeled "Untaxed Amount" where I only want one value from the "price" field. Currently, I am receiving this value for each article instead of just once as the total price for all articles. Is there a way to achieve this in .x ...

Interacting with an iframe element using Selenium in Python

I have a webpage with an iframe embedded, and I'm using Selenium for test automation: <iframe class="wysihtml5-sandbox" security="restricted" allowtransparency="true" frameborder="0" width="0" height="0" marginwidth="0" marginheight="0" style="dis ...

Enhancing logging format with additional dictionary containing optional components

I am trying to replicate this specific outcome: # code logging.basicConfig(format='%(levelname)s: %(sublevel) %(message)s', level=logging.DEBUG) logging.debug("abc", extra={'sublevel':2}) logging.debug("def", extr ...

Learn the process of extracting data from multiple URLs and saving the results into separate Docx files using Python's Selenium, BeautifulSoup4, and Docx libraries

I've been experimenting with various methods to scrape multiple URLs using Selenium, BS4, and Docx. So far, I have managed to successfully scrape one URL and extract the desired content, saving it to a single docx file. However, I'm facing challe ...

Using Python to Automate Chromium with Selenium

I have developed a Python script that uses Selenium to gather data from various websites. It works perfectly on my Windows PC, but I'm now faced with the challenge of making it run on my Raspberry Pi. Since Chrome is not supported on the Pi, I need to ...

What is the best way to create an executable file from a Python package using pyinstaller?

I have developed a Python command line program that is open source and compatible with Python 2.7, Python3+, and works across different platforms. My goal now is to package this program into an executable for my Windows users in a more user-friendly way. ...

I am unable to see the text field when I use element.text. What could be the reason for this

As I work on collecting online reviews using Selenium Chrome Webdriver, I've encountered a challenge with TripAdvisor. The reviews are truncated and require clicking a "More" button to view the complete text. Within the html code, there is a class cal ...

Using nested function calls alongside with statements for authentication

I am currently working on creating functions for tableau that are hierarchical in nature, meaning projects contain workbooks which then contain views. This structure has led to the creation of specific functions such as get_project, get_workbook, and get_v ...

Leveraging array indexing for implementing a 2D array operation on a 3D array

I have developed a function that takes a set of randomized cartesian coordinates and outputs the subset that falls within a specific spatial domain. For example: grid = np.ones((5,5)) grid = np.lib.pad(grid, ((10,10), (10,10)), 'constant') > ...

How can I create a Python script to generate a call graph and export it as a JSON file?

My challenge is to generate a call graph of code in JSON format. I have explored various Python packages such as coverage, pycallgraph, callgraph, and unittest, but none of them offer the desired JSON output. Pycallgraph came close but fell short of provid ...

Guide on leveraging Selenium for installing a Firefox browser extension

Seeking guidance on using Selenium to add the "nopecha" extension to my Firefox browser. Any assistance on achieving this goal would be greatly appreciated. ...

Ways to have Python recognize a variable as a grouping (such as a list or set) of strings

Below is a simple code snippet: for link in links: products[link] = get_products(link) In this code, the variable links should ideally be a set of strings. However, there are cases where it is just a single string, causing Python to treat it as indiv ...

What is the best way to avoid the "/" character when using send_keys?

When running a script that writes code into a textarea on a website, I encountered an issue. The first four lines were being written correctly until var url = "https:, at which point the cursor would jump to the upper left of the text area before continuin ...

Python Selenium: Accelerate Your Character Speed

Is there a way to slow down the typing speed of my send key while inputting characters? I am struggling to control how quickly it types. I attempted using the Sleep method, but that was not effective. A('Initiating browser startup...') e=l() e.ad ...