Real-Time Updates in Matplotlib
Learn how to create graphs that update continuously as new data becomes available.
Understand live plotting, dynamic data updates, FuncAnimation, streaming data, sensor monitoring, and real-time visualization.
1. Learning Objectives
After completing this lesson, you will understand:
- What real-time plotting means.
- How live data visualization works.
- How to update an existing Matplotlib line.
- How to use FuncAnimation for continuous updates.
- How to update X-axis and Y-axis values.
- How to use collections.deque for streaming data.
- How to simulate live sensor readings.
- How to control graph refresh intervals.
- How to manage continuously changing graph data.
2. What Are Real-Time Updates?
Real-time updates refer to continuously modifying a visualization when new data arrives. Instead of creating a static chart, the application updates the existing graph to display the latest information.
Matplotlib supports dynamic updates through its animation module, interactive plotting features, and canvas redraw methods.
Examples of Real-Time Visualization
- Monitoring temperature readings from sensors.
- Displaying live stock price changes.
- Monitoring CPU and memory usage.
- Visualizing network traffic.
- Monitoring machine performance.
- Displaying changing scientific measurements.
3. How Real-Time Plotting Works
A real-time plotting application receives new data, updates the existing graph, and refreshes the figure.
Basic workflow of a real-time Matplotlib application.
This process repeats whenever new data becomes available. The graph can display the complete data history or only a limited window of recent values.
4. Static Plotting vs Real-Time Plotting
| Static Plotting | Real-Time Plotting |
|---|---|
| Displays a fixed dataset. | Displays continuously changing data. |
| Usually created once. | Updated repeatedly. |
| Does not require continuous data updates. | Requires new data from a source or simulation. |
| Suitable for reports and analysis. | Suitable for monitoring and live dashboards. |
| Usually needs fewer redraw operations. | Requires regular figure refresh operations. |
5. Updating an Existing Line
Matplotlib allows you to modify an existing line instead of creating a completely new graph.
The set_data() method updates both X-axis and
Y-axis data of a line.
Syntax
line.set_data(x_data, y_data)
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
line, = ax.plot(x, y, marker="o")
new_x = [1, 2, 3, 4, 5]
new_y = [15, 25, 35, 45, 55]
line.set_data(new_x, new_y)
ax.relim()
ax.autoscale_view()
plt.title("Updated Line Plot")
plt.show()
print("Line data updated")
Output
Original Y values:
[10, 20, 30, 40, 50]
Updated Y values:
[15, 25, 35, 45, 55]
Line data updated
set_data() when you need to update both X and Y
values of an existing line.
6. Updating Only Y-Axis Values
If the X-axis values remain the same and only the Y-axis values
change, you can use set_ydata().
Syntax
line.set_ydata(new_y_values)
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [5, 10, 15, 20, 25]
line, = ax.plot(x, y, marker="o")
new_y = [10, 20, 15, 30, 40]
line.set_ydata(new_y)
ax.relim()
ax.autoscale_view()
plt.title("Updated Y Values")
plt.show()
print("Y-axis data updated")
Output
Original Y values:
[5, 10, 15, 20, 25]
Updated Y values:
[10, 20, 15, 30, 40]
Y-axis data updated
7. Using FuncAnimation for Real-Time Updates
FuncAnimation is useful for repeatedly updating
a graph. It calls an update function at regular intervals
according to the animation configuration.
In a real-time plotting example, the update function can generate or retrieve new data and modify the existing graph.
Example: Continuously Updating Graph
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
fig, ax = plt.subplots()
x_data = []
y_data = []
line, = ax.plot([], [], "b-")
ax.set_xlim(0, 50)
ax.set_ylim(0, 100)
def update(frame):
x_data.append(frame)
y_data.append(random.randint(10, 90))
line.set_data(x_data, y_data)
return line,
ani = FuncAnimation(
fig,
update,
frames=range(50),
interval=200,
blit=True,
repeat=False
)
plt.title("Live Data Updates")
plt.xlabel("Time")
plt.ylabel("Value")
plt.show()
Output
A graph window is displayed.
New random values are generated for each frame.
The line graph grows as new values are received.
The animation stops after 50 frames.
8. Using deque for Streaming Data
When data arrives continuously, storing every value forever may consume unnecessary memory.
Python provides collections.deque, which can maintain
a limited collection of recent values using its
maxlen parameter.
Import
from collections import deque
Example
from collections import deque
values = deque(maxlen=5)
for value in range(1, 9):
values.append(value)
print(list(values))
Output
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]
[4, 5, 6, 7, 8]
Once the deque reaches its maximum length, adding another item automatically removes the oldest item from the opposite end.
9. Real-Time Sensor Data Simulation
A sensor monitoring application can receive temperature values at regular intervals and display them using a live graph.
The following example simulates temperature readings and displays only the latest 20 values.
Complete Python Example
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from collections import deque
import random
fig, ax = plt.subplots()
temperature = deque(maxlen=20)
time_values = deque(maxlen=20)
line, = ax.plot([], [], "r-o")
ax.set_ylim(0, 50)
ax.set_xlim(0, 19)
ax.set_title("Real-Time Temperature Monitoring")
ax.set_xlabel("Recent Reading")
ax.set_ylabel("Temperature (Celsius)")
def update(frame):
new_temperature = random.uniform(20, 40)
temperature.append(new_temperature)
time_values.append(frame)
line.set_data(
range(len(temperature)),
temperature
)
return line,
ani = FuncAnimation(
fig,
update,
interval=1000,
frames=range(100),
blit=True,
repeat=False
)
plt.show()
Output
A temperature monitoring graph is displayed.
A new simulated temperature reading is generated
approximately every second.
The graph displays the latest 20 readings.
Older readings are automatically removed from
the displayed data window.
10. Creating a Moving Window Graph
A moving window graph displays only a selected range of the latest data points. This is helpful when the dataset grows continuously.
The following example updates the X-axis limits so that the graph displays a moving time window.
Example
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
fig, ax = plt.subplots()
x_data = []
y_data = []
line, = ax.plot([], [], "g-")
def update(frame):
x_data.append(frame)
y_data.append(random.randint(10, 100))
line.set_data(x_data, y_data)
ax.set_xlim(max(0, frame - 20), max(20, frame))
ax.set_ylim(0, 110)
return line,
ani = FuncAnimation(
fig,
update,
frames=range(100),
interval=200,
blit=False,
repeat=False
)
ax.set_title("Moving Window Data Graph")
ax.set_xlabel("Time")
ax.set_ylabel("Value")
plt.show()
Output
The graph continuously updates.
The visible X-axis range moves forward with time.
The graph focuses on the latest 20 time units
instead of displaying the entire history.
11. Creating a Live Monitoring Dashboard
Matplotlib can display multiple live measurements using subplots. For example, a monitoring dashboard can show CPU usage and memory usage in separate graphs.
Example
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
fig, (ax1, ax2) = plt.subplots(2, 1)
cpu_values = []
memory_values = []
time_values = []
cpu_line, = ax1.plot([], [], "b-", label="CPU")
memory_line, = ax2.plot([], [], "r-", label="Memory")
ax1.set_ylim(0, 100)
ax2.set_ylim(0, 100)
ax1.set_title("CPU Usage")
ax2.set_title("Memory Usage")
ax1.set_ylabel("Percentage")
ax2.set_ylabel("Percentage")
ax2.set_xlabel("Time")
def update(frame):
time_values.append(frame)
cpu_values.append(random.randint(10, 90))
memory_values.append(random.randint(20, 95))
cpu_line.set_data(time_values, cpu_values)
memory_line.set_data(time_values, memory_values)
ax1.set_xlim(max(0, frame - 20), max(20, frame))
ax2.set_xlim(max(0, frame - 20), max(20, frame))
return cpu_line, memory_line
ani = FuncAnimation(
fig,
update,
frames=range(100),
interval=500,
blit=False,
repeat=False
)
plt.tight_layout()
plt.show()
Output
A monitoring window contains two graphs.
First graph:
CPU usage values change over time.
Second graph:
Memory usage values change over time.
Both graphs update approximately every 500 milliseconds.
This example uses random values to simulate monitoring data. Actual system metrics can be connected through an appropriate monitoring library or data source.
12. Common Sources of Real-Time Data
| Data Source | Example | Possible Application |
|---|---|---|
| Sensors | Temperature and humidity readings. | IoT monitoring. |
| System Monitoring | CPU and memory usage. | Server monitoring. |
| Web APIs | Live market or weather information. | Data dashboards. |
| Network Streams | Incoming network traffic measurements. | Network analysis. |
| Scientific Instruments | Experimental measurements. | Scientific research. |
| Databases | Frequently updated records. | Business monitoring. |
13. Performance Considerations
Continuously updating graphs can consume CPU, memory, and rendering resources. Efficient update strategies are important when displaying large datasets.
Important Performance Practices
- Update existing line objects instead of creating new plots.
- Limit the number of displayed data points when appropriate.
- Use deque with maxlen for a fixed-size data window.
- Choose a suitable animation interval.
- Use blitting when supported and beneficial.
- Avoid expensive calculations inside every animation frame.
- Keep the GUI event loop responsive.
- Use efficient data collection and processing methods.
14. Common Mistakes and Solutions
| Problem | Solution |
|---|---|
| Creating a new figure for every incoming data point. | Create one figure and update existing artists. |
| Graph does not display updated values. | Check the update function and artist data. |
| Graph limits do not include new values. | Use relim() and autoscale_view() when appropriate. |
| Memory usage increases continuously. | Use a limited data window or deque. |
| Animation runs too slowly. | Reduce unnecessary work and adjust the interval. |
| Animation stops unexpectedly. | Keep a reference to the animation object. |
| GUI window becomes unresponsive. | Allow the GUI event loop to process events and avoid blocking operations. |
15. Best Practices
- Use FuncAnimation for regularly scheduled graphical updates.
- Keep data acquisition separate from graph rendering when possible.
- Reuse existing figure, axes, and line objects.
- Use deque for a fixed-size collection of recent values.
- Choose a refresh interval appropriate for the incoming data.
- Handle missing or invalid incoming data safely.
- Use suitable axis limits for continuously changing values.
- Test performance with realistic data volumes.
- Keep a reference to animation objects throughout their lifetime.
16. Practical Activity
Task: Build a Real-Time Temperature Monitor
Create a graph that displays continuously changing temperature readings.
Requirements:
- Import Matplotlib and FuncAnimation.
- Import deque from collections.
- Create a figure and axes.
- Create a deque with maxlen set to 20.
- Generate a new temperature value in every update.
- Update the existing line.
- Display only the latest 20 readings.
- Set an appropriate animation interval.
- Display the graph with a title and axis labels.
Expected Result:
A live temperature graph should display changing readings. Older readings should disappear when the data window reaches its maximum size.
17. Practice Questions
- What are real-time updates in Matplotlib?
- How can you update an existing line graph?
- What is the difference between set_data() and set_ydata()?
- How does FuncAnimation help in real-time plotting?
- What is the purpose of collections.deque?
- What does the maxlen parameter do?
- How can you display only the latest data points?
- Why is it important to reuse existing plot objects?
- How can you simulate live sensor readings?
- What are the common performance challenges in real-time plotting?
- How can multiple live measurements be displayed in one figure?
- Why should the GUI event loop remain responsive?
Summary
Real-time plotting in Matplotlib allows graphs to update continuously when new data becomes available. It is useful for monitoring applications, scientific experiments, sensor readings, and dynamic data visualization.
Existing graph elements can be modified using methods such as set_data() and set_ydata(). FuncAnimation provides a convenient way to schedule repeated graphical updates.
The collections.deque data structure can maintain a limited collection of recent measurements. This is useful for applications that need to display a moving window of streaming data.
Efficient real-time visualization requires suitable update intervals, reusable plot objects, responsive GUI event handling, and careful memory management. These techniques help build reliable dynamic monitoring applications.