- Plotting live data with Matplotlib
- How to visualize real-time data with Python’s Matplotlib
- Real-Time Graphing in Python
- Python Real-Time Plotting Function
- https://github.com/engineersportal/pylive
- Python Realtime Plotting | Matplotlib Tutorial | Chapter 9
- Python live plot using a local script
- Python realtime plotting from a CSV using an API
- Create a realtime plot in Python Matlplotlib
- Matplotlib Video Tutorial Series
- Related Posts
- Python Tutorial for Beginners
Plotting live data with Matplotlib
How to visualize real-time data with Python’s Matplotlib
Whether you’re working with a sensor, continually pulling data from an API, or have a file that’s often updated, you may want to analyze your data in real-time.
This article will explore a simple way to use functions to animate our plots with Matplotlib’s FuncAnimation.
The data for this first example is from the OS, and to retrieve this information, we’ll use psutil.
We’ll handle the data with deques, but you can adapt the example to work with most collections, like dictionaries, data frames, lists, or others.
By the end of the article, I’ll quickly show another example with Pandas and Geopandas.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
import psutil
import collections
Let’s start with collecting and storing the data. We’ll define two deques filled with zeros.
cpu = collections.deque(np.zeros(10))
ram = collections.deque(np.zeros(10))print("CPU: <>".format(cpu))
print("Memory: <>".format(ram))
Then we’ll create a function to update the deques with new data. It’ll remove the last value of each deque and append a new one.
def my_function():
cpu.popleft()
cpu.append(psutil.cpu_percent(interval=1)) ram.popleft()
ram.append(psutil.virtual_memory().percent)cpu = collections.deque(np.zeros(10))
ram = collections.deque(np.zeros(10))# test
my_function()
my_function()
my_function()print("CPU: <>".format(cpu))
print("Memory: <>".format(ram))
Now we can define the figure and subplots. Besides updating the deques, our function will also need to add this data to our chart.
# function to update the data
def my_function():
cpu.popleft()
cpu.append(psutil.cpu_percent(interval=1))…
Real-Time Graphing in Python
In data visualization, real-time plotting can be a powerful tool to analyze data as it streams into the acquisition system. Whether temperature data, audio data, stock market data, or even social media data — it is often advantageous to monitor data in real-time to ensure that instrumentation and algorithms are functioning properly.
In this tutorial, I will outline a basic function written in Python that permits real-time plotting of data. The function is simple and straight-forward, but its powerful result allows any researcher or data analyst to take full advantage of data monitoring as it streams into the user’s computer!
Python Real-Time Plotting Function
The GitHub repository containing the code used in this tutorial can be found at:
https://github.com/engineersportal/pylive
import matplotlib.pyplot as plt import numpy as np # use ggplot style for more sophisticated visuals plt.style.use('ggplot') def live_plotter(x_vec,y1_data,line1,identifier='',pause_time=0.1): if line1==[]: # this is the call to matplotlib that allows dynamic plotting plt.ion() fig = plt.figure(figsize=(13,6)) ax = fig.add_subplot(111) # create a variable for the line so we can later update it line1, = ax.plot(x_vec,y1_data,'-o',alpha=0.8) #update plot label/title plt.ylabel('Y Label') plt.title('Title: <>'.format(identifier)) plt.show() # after the figure, axis, and line are created, we only need to update the y-data line1.set_ydata(y1_data) # adjust limits if new data goes beyond bounds if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]: plt.ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)]) # this pauses the data so the figure/axis can catch up - the amount of pause can be altered above plt.pause(pause_time) # return line so we can update it again in the next iteration return line1
A few notes on the function above:
- line1.set_ydata(y1_data) can also be switched to line1.set_data(x_vec,y1_data) to change both x and y data on the plots.
- plt.pause() is necessary to allow the plotter to catch up — I’ve been able to use a pause time of 0.01s without any issues
- The user will need to return line1 to control the line as it is updated and sent back to the function
- The user can also customize the function to allow dynamic changes of title, x-label, y-label, x-limits, etc.
Python Realtime Plotting | Matplotlib Tutorial | Chapter 9
In this tutorial, we will learn to plot live data in python using matplotlib. In the beginning, we will be plotting realtime data from a local script and later on we will create a python live plot from an automatically updating csv file. The csv file will be created and updated using an api. So, in the later part of this tutorial we will be creating matplotlib live/ realtime plot from a data api.
Such kind of live plots can be extremely useful to plot live data from serial ports, apis, sensors etc. etc. I hope you will find some usecase for creating python realtime plots and this tutorial would be helpful to you.
Python live plot using a local script
First of all, we will be created a python realtime linegraph using a local script. We will be using python’s inbuilt modules like random , count from itertools etc. Create a file called python_live_plot.py and start coding.
# python_live_plot.py import random from itertools import count import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation plt.style.use('fivethirtyeight') x_values = [] y_values = [] index = count() def animate(i): x_values.append(next(index)) y_values.append(random.randint(0, 5)) plt.cla() plt.plot(x_values, y_values) ani = FuncAnimation(plt.gcf(), animate, 1000) plt.tight_layout() plt.show()
In this code to create python live plot, first of all we have created two empty lists for x_values and y_values, then we have created an animate function to append values to those list. We have used index and randint function for the same. Then we have cleared the plot using plt.cla() and finally plotted it using plt.plot().
We have used FuncAnimation to keep on updating the plot using the animate function every second (1000 ms). For rest of the code, you can follow our complete tutorial series.
Python realtime plotting from a CSV using an API
Now, we will be using an API to get realtime data of Infosys (‘INFY’) and then update a CSV file with that data. And then we will create a Realtime plot of that data.
First of all, I have created a script called ‘python_live_plot_data.py’ to create ‘python_live_plot_data.csv’ file.
#python_live_plot_data.py import csv import time import pandas as pd from nsetools import Nse from pprint import pprint from datetime import datetime nse = Nse() with open('python_live_plot_data.csv', 'w') as f: writer = csv.writer(f) writer.writerow(['Time', 'Price']) while True: q = nse.get_quote('infy') now = datetime.now().strftime("%H:%M:%S") row = [now, q['lastPrice']] with open('python_live_plot_data.csv', 'a') as f: writer = csv.writer(f) writer.writerow(row) time.sleep(1)
In this script I have used nsetools to fetch the live quote price of infosys as q (which is a json) and then I have written the time (using datetime and stftime) and last price in a csv file using csv module. If you want to learn to convert a json file to csv file, you can read our tutorial here.
So, this script will update the csv file every second.
Create a realtime plot in Python Matlplotlib
Now, let us use this csv file to create the realtime plot.
# python_live_plot.py import random from itertools import count import pandas as pd import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation plt.style.use('fivethirtyeight') x_values = [] y_values = [] index = count() def animate(i): data = pd.read_csv('python_live_plot_data.csv') x_values = data['Time'] y_values = data['Price'] plt.cla() plt.plot(x_values, y_values) plt.xlabel('Time') plt.ylabel('Price') plt.title('Infosys') plt.gcf().autofmt_xdate() plt.tight_layout() ani = FuncAnimation(plt.gcf(), animate, 5000) plt.tight_layout() plt.show()
So, in the above code we have edited our animate function to read the ‘python_live_plot_data.csv’ file which is being updated every five seconds by ‘python_live_plot_data.py’. We have used pandas read_csv method to read the data from that file and plot it in realtime. You can follow our tutorial from the beginning to learn more about reading the csv files.
Matplotlib Video Tutorial Series
We are glad to inform you that we are coming up with the Video Tutorial Series of Matplotlib on Youtube. Check it out below.
Table of Contents of Matplotlib Tutorial in Python
If you have liked our tutorial, there are various ways to support us, the easiest is to share this post. You can also follow us on facebook, twitter and youtube.
In case of any query, you can leave the comment below.
If you want to support our work. You can do it using Patreon.
Related Posts
Matplotlib Stack Plots/Bars | Matplotlib Tutorial in Python | Chapter 4
Matplotlib Tutorial in Python
*Matplotlib Stack Plots/Bars | Chapter 4
In this chapter we will learn to create Matplotlib/Python Stack Plots/Bars.Stack Plots are also called area graphs/plots in general.
Matplotlib Tutorials in Python — Creating a Simple Stack Plot in Matplotlib
A good example of using a stack .
Python Tutorial for Beginners
Python Tutorial for Beginners
Have you heard a lot about Python Language? Are you looking for free and reliable resource to learn Python? If Yes, your search for the Best Python Tutorial is over.
We are excited to bring an exhaustive Python tutorial for a complete beginner. Even .
Matplotlib Subplot in Python | Matplotlib Tutorial | Chapter 10
Matplotlib Subplot in Python | Chapter 10
In this Matplotlib Subplot tutorial, we will be learning to create Matplotlib Subplots. Till now, we have been using matplotlib.pyplot() to create the plots. But now, we will be using matplotlib.pyplot.subplots() (ptl.subplots()) to create Matplotlib Subplots.
Matplotlib.pyplot() or plt was automatically .