 # Python Realtime Plotting | Matplotlib Tutorial | Chapter 9

• 12834 Views var aax_size='728x90'; var aax_pubname = 'saralgyaan0d-21'; var aax_src='302';

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

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

In case of any query, you can leave the comment below.

If you want to support our work. You can do it using Patreon.

By Udit Vashisht

## Introduction

Python’s pandas library is frequently used to import, manage, and analyze datasets in a variety of formats. In this article, we’ll use it to analyze Amazon’s stock prices and perform some basic time series operations.
Stock markets play an important role in the economy of ...

##### Python Histograms | Matplotlib Tutorial in Python | Chapter 6
By Udit Vashisht

Matplotlib Tutorial in Python

Python Histograms | Chapter 6

A Python Histogram/Matplotlib Histogram is an accurate representation of the distribution of numerical data. Bar graphsrelates to two variables, however a Python Histogram relates to only one variable and shows it distribution in different range of the ...