How do I display real-time graphs in a simple UI for a Python program?

To display real-time graphs in a simple UI for a Python program, we can use matplotlib with FuncAnimation to create animated plots that update continuously. This approach is perfect for visualizing changing data streams or simulated real-time data.

Required Libraries

First, ensure you have the necessary libraries installed ?

pip install matplotlib numpy

Basic Real-Time Line Plot

Here's a simple example that displays a real-time line graph with updating sine wave data ?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Set up the figure and axis
fig, ax = plt.subplots()
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1.1, 1.1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Real-Time Sine Wave')

# Initialize empty line
line, = ax.plot([], [], 'b-', linewidth=2)
x_data = np.linspace(0, 2*np.pi, 100)

def animate(frame):
    # Generate new y data with phase shift
    y_data = np.sin(x_data + frame * 0.1)
    line.set_data(x_data, y_data)
    return line,

# Create animation
ani = animation.FuncAnimation(fig, animate, frames=200, interval=50, blit=True)
plt.show()

Real-Time Contour Plot

For more complex visualizations, you can create animated contour plots that update with new data ?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Configure figure settings
plt.rcParams["figure.figsize"] = [8.00, 6.00]
plt.rcParams["figure.autolayout"] = True

# Generate sample data (simulating real-time data)
data = np.random.randn(1000).reshape(10, 10, 10)
fig, ax = plt.subplots()

def animate(frame):
    ax.clear()
    ax.contourf(data[:, :, frame], cmap="viridis", levels=20)
    ax.set_title(f'Real-Time Contour Plot - Frame {frame}')
    ax.set_xlabel('X Coordinate')
    ax.set_ylabel('Y Coordinate')

# Create animation with 10 frames
ani = animation.FuncAnimation(fig, animate, frames=10, interval=200, repeat=True)
plt.show()

Real-Time Data Stream Simulation

Here's an example that simulates real-time data streaming, useful for monitoring applications ?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from collections import deque

# Setup for scrolling data
max_points = 100
x_data = deque(maxlen=max_points)
y_data = deque(maxlen=max_points)

fig, ax = plt.subplots()
line, = ax.plot([], [], 'r-', linewidth=2)
ax.set_xlim(0, max_points)
ax.set_ylim(-2, 2)
ax.set_title('Real-Time Data Stream')
ax.set_xlabel('Time Points')
ax.set_ylabel('Value')

def animate(frame):
    # Simulate new data point
    if len(x_data) == 0:
        x_data.append(0)
    else:
        x_data.append(x_data[-1] + 1)
    
    # Generate random data with some trend
    new_value = np.sin(frame * 0.1) + np.random.normal(0, 0.1)
    y_data.append(new_value)
    
    # Update plot
    line.set_data(list(x_data), list(y_data))
    
    # Adjust x-axis if needed
    if len(x_data) > max_points:
        ax.set_xlim(x_data[0], x_data[-1])
    
    return line,

ani = animation.FuncAnimation(fig, animate, interval=100, blit=True, cache_frame_data=False)
plt.show()

Key Parameters for Real-Time Animation

Parameter Description Recommended Value
interval Delay between frames (ms) 50-200 for smooth animation
blit Optimize drawing performance True for better performance
repeat Loop animation continuously True for real-time monitoring
cache_frame_data Cache frame data False for live data

Performance Tips

  • Use blit=True for better performance by only redrawing changed parts

  • Limit the number of data points displayed to prevent memory issues

  • Use appropriate intervals (50-200ms) to balance smoothness and performance

  • Clear axes with ax.clear() when plot structure changes significantly

Conclusion

Real-time graphs in Python are efficiently created using matplotlib's FuncAnimation class. Use line plots for streaming data, contour plots for 2D data visualization, and optimize performance with appropriate parameters like blit=True and reasonable update intervals.

Updated on: 2026-03-25T21:48:17+05:30

916 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements