How can I dynamically update my Matplotlib figure as the data file changes?

To dynamically update a Matplotlib figure when data changes, you can use animation techniques or real-time plotting methods. This is useful for monitoring live data feeds, sensor readings, or files that update continuously.

Basic Dynamic Update Example

Here's a simple approach using plt.pause() to create animated subplots with random data ?

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

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

m = 2
n = 4

fig, axes = plt.subplots(nrows=m, ncols=n)
hexadecimal_alphabets = '0123456789ABCDEF'

# Generate random colors for each subplot
colors = ["#" + ''.join([random.choice(hexadecimal_alphabets)
                        for j in range(6)]) for i in range(m*n)]

for update in range(5):  # Update 5 times
    for i in range(m):
        for j in range(n):
            axes[i][j].clear()
            x_data = np.random.rand(10)
            y_data = np.random.rand(10)
            color_index = (i * n + j) % len(colors)
            axes[i][j].plot(x_data, y_data, color=colors[color_index], marker='o')
            axes[i][j].set_title(f'Plot {i+1},{j+1}')
    
    plt.draw()
    plt.pause(0.5)  # Pause for 0.5 seconds between updates

plt.show()

File Monitoring with Dynamic Updates

For real file monitoring, you can check file modification times and update the plot accordingly ?

import numpy as np
import matplotlib.pyplot as plt
import time
import os

def simulate_data_file():
    """Simulate creating/updating a data file"""
    data = np.random.randn(20, 2)  # 20 points, x and y columns
    np.savetxt('data.txt', data, delimiter=',')
    return data

def read_data_file(filename):
    """Read data from file"""
    try:
        return np.loadtxt(filename, delimiter=',')
    except FileNotFoundError:
        return np.array([[0, 0]])

# Create initial plot
fig, ax = plt.subplots(figsize=(8, 6))
plt.ion()  # Turn on interactive mode

# Simulate file updates
for i in range(3):
    # Simulate file update
    data = simulate_data_file()
    
    # Clear and update plot
    ax.clear()
    ax.scatter(data[:, 0], data[:, 1], alpha=0.7, s=50)
    ax.set_title(f'Dynamic Plot Update #{i+1}')
    ax.set_xlabel('X Values')
    ax.set_ylabel('Y Values')
    ax.grid(True, alpha=0.3)
    
    plt.draw()
    plt.pause(1.0)  # Wait 1 second between updates

plt.ioff()  # Turn off interactive mode
plt.show()

Using matplotlib.animation for Smooth Updates

For more professional animations, use the animation module ?

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

def animate_plot():
    fig, ax = plt.subplots(figsize=(8, 6))
    
    def update_data(frame):
        ax.clear()
        # Generate new random data for each frame
        x = np.random.randn(50)
        y = np.random.randn(50)
        colors = np.random.rand(50)
        
        ax.scatter(x, y, c=colors, alpha=0.6, s=100)
        ax.set_xlim(-3, 3)
        ax.set_ylim(-3, 3)
        ax.set_title(f'Animated Plot - Frame {frame}')
        ax.grid(True, alpha=0.3)
    
    # Create animation that updates every 200ms
    ani = animation.FuncAnimation(fig, update_data, frames=range(10), 
                                  interval=200, repeat=False)
    
    plt.show()
    return ani

# Run the animation
ani = animate_plot()

Key Points

  • plt.pause() − Simple way to create timed updates
  • plt.ion() and plt.ioff() − Control interactive mode
  • ax.clear() − Clear previous plot data before updating
  • animation.FuncAnimation() − Professional animation framework
  • File monitoring − Check modification times or use file watchers

Conclusion

Use plt.pause() for simple dynamic updates or animation.FuncAnimation() for smooth animations. For file monitoring, combine file system checks with plot updates to create responsive data visualizations.

Updated on: 2026-03-25T23:04:09+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements