Displaying Real-Time Data on a Gauge in Python

What will you learn?

In this tutorial, you will learn how to visualize real-time data on a gauge using Python. By the end of this guide, you will be able to effectively display dynamic data in a visually appealing manner.

Introduction to the Problem and Solution

At times, it is essential to monitor and display data that changes over time in our applications. For example, displaying temperature readings from a sensor or updating stock market prices. A gauge chart is an excellent way to represent this dynamic data visually, providing an immediate and intuitive understanding of your values at any given moment.

To accomplish this task, we will leverage Python libraries such as matplotlib for creating the gauge chart and threading or asyncio for managing real-time data updates without causing any blocking issues. The goal is to continuously fetch or listen for new data points and update our gauge in real-time. This approach can be applied across various scenarios where monitoring live data plays a critical role.


import matplotlib.pyplot as plt
import numpy as np
from random import randrange
import time

def draw_gauge(current_value):
    N = 1   # Number of sectors in the gauge (Just one sector)
    bottom = 2  # Starting point of our gauge (the width)
    max_val = 100  # Max value of our meter

    theta = np.linspace(0.0, np.pi, N+1) 
    radii = np.array([max_val]*N)

    fig, ax = plt.subplots(subplot_kw={'projection':'polar'})

    bars = ax.bar(theta[:-1], radii,width=(2.*np.pi)/N,bottom=bottom,color='green')

    bars[0].set_facecolor('r') if current_value >= 75 else bars[0].set_facecolor('g') if current_value > 25 else bars[0].set_facecolor('y')


# Simulate updating the gauge with new values every second.
if __name__ == "__main__":
    while True:
        new_value = randrange(101)  

# Copyright PHD


The provided code simulates receiving real-time data by generating a random number (between 0 and 100) every second as the current value displayed on the gauge. The draw_gauge function takes this current value as input and visualizes it using a semi-circle polar plot divided into three zones with different colors representing various value ranges (red for high values [>=75], yellow for low [<25], and green for medium).

We utilize Matplotlib’s capabilities to create polar plots for drawing our gauge-like visualization. The angles represented by ‘theta’ determine where each bar starts (in this case just one bar representing our needle pointing towards the current value starting from zero), while ‘radii’ specifies the lengths of these bars extending outward from the center based on the maximum possible value (max_val). This indicates where along its length each segment should reach relative to its magnitude compared against the total possible outcomes/values range.

Each iteration within the loop updates the figure with a new simulated reading, closely mimicking ongoing live updates by pausing briefly (time.sleep(1)), resembling scenarios involving continuous monitoring like tracking resource usage levels within IT infrastructures.

    How do I install Matplotlib?

    To install Matplotlib, you can use pip:

    pip install matplotlib
    # Copyright PHD

    Can I customize colors used in the gauge?

    Yes! You can modify color settings inside the draw_gauge function according to your preferences by adjusting bars[0].set_facecolor() calls.

    Is there any way to make updates smoother?

    For smoother updates, consider utilizing animation capabilities provided by Matplotlib instead of redrawing the entire figure each time.

    How does threading improve real-time data handling?

    Threading allows fetching and updating operations to run concurrently without freezing UI or main program flow. This concurrency is crucial for maintaining responsiveness during continuous monitoring tasks.

    What’s asyncio and when should I use it over threading?

    Asyncio offers a higher-level API designed around coroutines that promise more efficient scheduling, particularly beneficial under IO-bound conditions compared to CPU-heavy tasks. It is suitable for leveraging parallelism benefits over threads or multiprocessing approaches when dealing with asynchronous operations.

    Can I apply similar techniques beyond gauges?

    Absolutely! The principles demonstrated here extend well beyond gauges and can be applied across various visualization forms like line graphs, pie charts, etc., aiming to represent evolving datasets dynamically.

    How do I fetch real-time data from an external source instead of simulating it?

    To fetch real-time data from an external source, replace the simulation logic inside your main loop with actual fetching operations such as HTTP requests accessing REST APIs or polling sensors depending on your specific use case.


    Mastering how to display real-time data on a gauge in Python opens up endless possibilities for monitoring dynamic information effectively. By combining libraries like matplotlib with threading or asyncio for handling updates seamlessly, you can create visually engaging dashboards that provide valuable insights at a glance.

    Leave a Comment