Real-Time Plotting using python—matplotlib

Saurabh Singh
2 min readAug 4, 2021

Python is a very powerful language used extensively by the data engineers, analyst and scientist for there day-to-day work. Working with big data is tough we need to plot them to understand the data behaviour as step 1.

matplotlib is very famous python library used for plotting with strong support from open community. FuncAnimation is used to plot real-time graph using python.

Syntax -

FuncAnimation( <figure>, <user-defined-function>, <interval>)

Explanation —

Above syntax could be breakdown into below statement in simple words.

“ Execute <user-defined-function> after every <interval> and plot it on <figure>”

FuncAnimation is similar to a looping function with no end-statement it will keep running the <user-defined-function> passed as parameter after every given <interval>. It ends only once the python code is stopped externally.

Sample —

Let’s code to plot the price of a stock on real time.

First lets get all the required libraries exported. We will be using yfinance to get the stock price details.

import yfinance as yf
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.axis import Axis

Before calling the FuncAnimation we need to define the user-defined-function. We are capturing the current price of the stock of UBER.

def get_data(i):            
data = yf.download(tickers='UBER', period='1d', interval='1m') ax.plot(data.index.values, data['Open'])

Calling the FuncAnimation to call the above defined function after every 10 second.

ani = FuncAnimation(fig, get_data, interval=10)

Output —

Hope it was helpful !! 😁

Feel free to leave your queries on comment or suggestions.

--

--

Saurabh Singh

Cloud Data Engineer | 1 x GCP | 3 x AWS | Big Query | Redshift | Airflow | Python | PySpark | Ab Initio | BI | Analytics |