Python Realtime Plotting in Matplotlib
Python Realtime Plotting | 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().
Python realtime plotting from a CSV using an API
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() 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.
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(): 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
In case of any query, you can leave the comment below.
If you want to support our work. You can do it using Patreon.