DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


Python Realtime Plotting | Matplotlib Tutorial | Chapter 9

  • 5 minutes read
  • 36665 Views
Python Realtime Plotting | Matplotlib Tutorial | Chapter 9

    Table of Contents

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

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.

python_live_plot.gif

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

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

How to fill area between the Line Plots? | Matplotlib Tutorial in Python | Chapter 5
By Udit Vashisht

How to fill area between the line plots in Matplotlib?

You can easily fill the area with any color between the lines or under a curve in Matplotlib Line Plots using plt.fill_between().

Parameters of matplotlib.pyplot.fill_between() or plt.fill_between()

The syntax for plt.fill_between() is :

matplotlib.pyplot.fill_between(x, y1, y2=0, where=None, interpolate=False, ...

Read More
Venv Python - A complete tutorial on Virtual Environments in Python
By Udit Vashisht

What is Virtual Environment in Python ?

Virtual Environment is a kind of a container which runs specific version of Python and its modules. And it is used in the cases where you are working on two different project which has different dependencies. Say one of your project uses Django ...

Read More
Scatter Plotting in Python | Matplotlib Tutorial | Chapter 7
By Udit Vashisht

Scatter Plot in Python using Pandas and Matplotlib

In this tutorial we will learn to create a Scatter Plot in Python using Matplotlib and Pandas. We will use matplotlib.pyplot()’s plt.scatter() to create the scatter plot

What is a Scatter Plot?

Scatter Plot also known as scatter plots ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python