matplotlib
plotting
data visualization
Python
tutorial

How to update a plot in matplotlib

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Updating an existing matplotlib plot is a common requirement for monitoring dashboards, simulations, and streaming data tools. The key is to update artist objects instead of recreating the entire figure repeatedly. This keeps rendering smooth and avoids unnecessary CPU usage.

Update Line Data and Redraw

For many cases, keep a line reference, update its data, and redraw the canvas. This is easy to reason about and works in scripts and notebooks.

python
1import numpy as np
2import matplotlib.pyplot as plt
3
4x = np.linspace(0, 2 * np.pi, 200)
5y = np.sin(x)
6
7fig, ax = plt.subplots()
8line, = ax.plot(x, y, label="signal")
9ax.set_ylim(-1.5, 1.5)
10ax.legend()
11
12for phase in np.linspace(0, 2 * np.pi, 50):
13    line.set_ydata(np.sin(x + phase))
14    fig.canvas.draw_idle()
15    plt.pause(0.05)
16
17plt.show()

This pattern is usually enough for low-rate updates.

Use FuncAnimation for Structured Live Updates

FuncAnimation is cleaner when you want a dedicated update function and repeatable animation behavior.

python
1import numpy as np
2import matplotlib.pyplot as plt
3from matplotlib.animation import FuncAnimation
4
5x = np.linspace(0, 4 * np.pi, 400)
6fig, ax = plt.subplots()
7line, = ax.plot(x, np.cos(x))
8ax.set_ylim(-1.2, 1.2)
9
10
11def update(frame):
12    line.set_ydata(np.cos(x + frame / 8.0))
13    return (line,)
14
15
16ani = FuncAnimation(fig, update, frames=200, interval=30, blit=True)
17plt.show()

Using blit=True can improve performance by redrawing only changed artists.

Keep Axes and Limits Stable

Frequent autoscaling can make visual interpretation difficult. Set stable limits when possible and update only what users need to see. If limits must change, do it intentionally with clear logic.

python
1import numpy as np
2import matplotlib.pyplot as plt
3
4fig, ax = plt.subplots()
5line, = ax.plot([], [])
6ax.set_xlim(0, 100)
7ax.set_ylim(0, 1)
8
9buffer = []
10for i in range(100):
11    value = np.random.rand()
12    buffer.append(value)
13    line.set_data(range(len(buffer)), buffer)
14    fig.canvas.draw_idle()
15    plt.pause(0.02)
16
17plt.show()

Stable axes produce charts that are easier to track in real time.

Real-Time Windowed Plot Pattern

For streaming data, plot only a moving window instead of the full history. This keeps redraw cost stable and improves responsiveness over long runtimes.

python
1from collections import deque
2import random
3import matplotlib.pyplot as plt
4
5window = 200
6values = deque(maxlen=window)
7
8fig, ax = plt.subplots()
9line, = ax.plot([], [])
10ax.set_xlim(0, window)
11ax.set_ylim(0, 100)
12
13for _ in range(1000):
14    values.append(random.randint(0, 100))
15    y = list(values)
16    x = list(range(len(y)))
17
18    line.set_data(x, y)
19    fig.canvas.draw_idle()
20    plt.pause(0.01)
21
22plt.show()

This pattern is especially useful in telemetry tools where the latest few seconds are more important than the full trace. It also helps avoid memory growth in long-running desktop utilities.

Pick the Right Update Frequency

Update frequency should match human perception and data change rate. Many dashboards feel smooth at about ten to twenty updates per second, and higher rates can waste resources. Start with a modest interval, measure CPU usage, then tune based on actual needs.

Verify with Small Reproducible Scripts

When plotting issues appear, isolate them in a tiny script with synthetic data. A reproducible script makes it easier to identify whether the issue comes from data, rendering backend, or update logic.

Common Pitfalls

  • Recreating figure and axes inside the update loop, which is slow and flickers.
  • Forgetting plt.pause or canvas redraw calls in interactive loops.
  • Enabling autoscale on every frame, which causes distracting jumps.
  • Updating very large arrays each frame without decimation.

Summary

  • Keep references to artists and update their data in place.
  • Use FuncAnimation for clean and reusable animation code.
  • Stabilize axis limits for readable real-time charts.
  • Optimize frame work when data volume is high.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.