Udit Vashisht
Author: Udit Vashisht


Python Realtime Plotting | Matplotlib Tutorial | Chapter 9

  • Sept. 9, 2019, 11:40 a.m.
  • 5 minutes read
  • 933 Views
Python Realtime Plotting | Matplotlib Tutorial | Chapter 9

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().

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_live_plot.gif

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()

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.

python_live_plot.gif

Table of Contents of Matplotlib Tutorial in Python

Matplotlib Tutorial in Python | Chapter 1 | Introduction

Matplotlib Tutorial in Python | Chapter 2 | Extracting Data from CSVs and plotting Bar Charts

Pie Charts in Python | Matplotlib Tutorial in Python | Chapter 3

Matplotlib Stack Plots/Bars | Matplotlib Tutorial in Python | Chapter 4

Filling Area on Line Plots | Matplotlib Tutorial in Python | Chapter 5

Python Histograms | Matplotlib Tutorial in Python | Chapter 6

Scatter Plotting in Python | Matplotlib Tutorial | Chapter 7

Plot Time Series in Python | Matplotlib Tutorial | Chapter 8

Python Realtime Plotting | Matplotlib Tutorial | Chapter 9

Matplotlib Subplot in Python | Matplotlib Tutorial | Chapter 10

Python Candlestick Chart | Matplotlib Tutorial | Chapter 11

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 Subplot in Python | Matplotlib Tutorial | Chapter 10
By Udit Vashisht | 2 months ago

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 ...

Read More
Chapter 4 - Print function
By Udit Vashisht | 9 months, 1 week ago

In the early days of your python, one function that you are going to use the most is the print() function. So, I have decided to add it in the opening chapter of this tutorial. In addition to the print function, you will be learning about commenting out and escape ...

Read More
Chapter 1 - Introduction
By Udit Vashisht | 9 months, 3 weeks ago

Curiosity and zeal to learn something new have probably brought you here. It doesn’t matter whether you are new to programming or switching from some other redundant or less useful language, you must be having a few very important question in your mind. We will be answering most of them ...

Read More
Search