SoFunction
Updated on 2024-10-28

Python using matplotlib to achieve dynamic visualization details

Data visualization in Python refers to the graphical representation of raw data for better visualization, understanding and reasoning.Python provides various libraries containing different features for visualizing data and can support different types of graphs i.e. Matplotlib, Seaborn, Bokeh, Plotly etc.

Dynamic Visualization in Python

Dynamic visualization of any system means a graphical representation of the current system's changing state during a presentation. In terms of data visualization in Python, a dynamic visualization is a moving graphic that either changes over time, as in a video, or changes as the user changes inputs, but in the case of the current demo, it is as if it were alive.

Steps to create a dynamic graph in Python

Step 1. Create a fixed-length queue

A queue is a linear data structure that stores items on a first-in-first-out (FIFO) principle. It can be implemented in Python in various ways. Creating a fixed length queue for dynamic plotting in Python means creating a data structure that stores a fixed number of elements and discards the oldest element when the container is full. It is very useful when we want to plot constantly updated data points. By limiting the size of the container, the performance and clarity of the plot can be improved.

from collections import deque
# Create a deque with a maximum length of 3
data_points = deque(maxlen=3)
# Add new data points to the deque
data_points.append(40)
data_points.append(60)
data_points.append(30)
# display the data points in the deque
print(data_points)  # deque([40, 60, 30], maxlen=3)
# Add more data points to the deque
data_points.append(13)
data_points.append(99)
# The oldest data point is/are automatically 
# removed from front of queue.
# deque([30, 13, 99], maxlen=3)
print(data_points)  

exports

deque([40, 60, 30], maxlen=3)
deque([30, 13, 99], maxlen=3)

Step 2. Generate points and save them to a queue

Here we dynamically generate data points and attach them to the queue data structure instead of performing manual operations as shown in the example above. Here we will use the functions available in Python's random module to generate data points.

from collections import deque
import random
# Create a deque with fixed length 5
data_points = deque(maxlen=5)
# Generate and append data points to the deque
# we iterate 2 extra times to demonstrate how 
# queue removes values from front
for i in range(7):
     # generate random numbers between 0 
    # to 100 (both inclusive)
    new_data_point = (0, 100)
    data_points.append(new_data_point)
    print(data_points)

exports

deque([64], maxlen=5)
deque([64, 57], maxlen=5)
deque([64, 57, 15], maxlen=5)
deque([64, 57, 15, 31], maxlen=5)
deque([64, 57, 15, 31, 35], maxlen=5)
deque([57, 15, 31, 35, 25], maxlen=5)
deque([15, 31, 35, 25, 12], maxlen=5)

Step 3. Delete the first point

In Dynamic Plotting in Python, when we generate a new data point and add it to a fixed-length queue, we need to remove the oldest point from the queue to maintain the fixed length of the queue. Here, we remove elements from the left side following the FIFO principle.

from collections import deque
import random
# Create a deque with fixed length
data_points = deque(maxlen=5)
# Append 5 data points to the deque at once using extend method.
data_points.extend([1, 2, 3, 4, 5])
# Print the deque before removing the first element
print("Deque before removing the first element:", data_points)
# Remove the first element from the deque
data_points.popleft()
# Print the deque after removing the first element
print("Deque after removing the first element:", data_points)

exports

Deque before removing the first element: deque([1, 2, 3, 4, 5], maxlen=5)
Deque after removing the first element: deque([2, 3, 4, 5], maxlen=5)

Step 4. Drawing the queue and pausing the drawing for visualization

We first plot the data points stored in the queue using Matplotlib, and then pause the plot for a certain amount of time so that we can visualize the plot before updating it with the next set of data points. This can be done using the () function in Matplotlib. Here, in our sample code block, we will generate a set of y values with a constant increase in x-axis values from 0, then observe the graph and then pause it.

import  as plt
from collections import deque
import random
# Create a fixed-length deque of size 50 to store the data points
data_points = deque(maxlen=50)
# Create an empty plot
fig, ax = ()
line = ([])
# Set the x-axis and y-axis limits to 100
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
# Iterate through 50 data points and update the plot
for i in range(50):
    # Generate and add data points to the deque
    new_x = i
    # generate a random number between 0 to 100 for y axis
    new_y = (0, 100)
    data_points.append((new_x, new_y))
    # Update the plot with the new data points
    x_values = [x for x, y in data_points]
    y_values = [y for x, y in data_points]
    line.set_data(x_values, y_values)
    # pause the plot for 0.01s before next point is shown
    (0.01)
# Show the plot
()

Step 5. Clearing the drawing

When updating data points in real time, we will clear the plot before plotting the next set of values. This can be done using the line.set_data([], []) function in Matplotlib so that we can display the fixed size of the queue data structure in real time.

import  as plt
from collections import deque
import random
# Create a fixed-length deque to store the data points
data_points = deque(maxlen=50)
# Create an empty plot
fig, ax = ()
line, = ([])
# Set the x-axis and y-axis limits
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
# Iterate through the data points and update the plot
for i in range(100):
	# Generate and add data points to the deque
	new_x = i
	new_y = (0, 100)
	data_points.append((new_x, new_y))
	# Update the plot with the new data points
	x_values = [x for x, y in data_points]
	y_values = [y for x, y in data_points]
	line.set_data(x_values, y_values)
	(0.01)
	# Clear the plot for the next set of values
	line.set_data([], [])
# Show the plot
()

Dynamic Scatterplot

import  as plt
from collections import deque
import random
# Create a fixed-length deque of length 50 to store the data points
data_points = deque(maxlen=50)
# Create an empty plot
fig, ax = ()
# Set the x-axis and y-axis limits to 100
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
# Create a scatter plot to visualize the data points
scatter = ([], [])
# Iterate through the data points and update the scatter plot
for i in range(100):
    # Generate and add data points to the deque
    new_x = i
    new_y = (0, 100)
    data_points.append((new_x, new_y))
    # Update the scatter plot with the new data points
    x_values = [x for x, y in data_points]
    y_values = [y for x, y in data_points]
    scatter.set_offsets(list(zip(x_values, y_values)))
    (0.01)
# Show the plot
()

Dynamic Scatter and Line Charts

import  as plt
from collections import deque
import random
from  import FuncAnimation
# Create a fixed-length deque of length 50 to store the data points
data_points = deque(maxlen=50)
# Create an empty plot
fig, ax = ()
line, = ([])
# Set the x-axis and y-axis limits to 100
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
# Create a scatter plot to visualize the data points
scatter = ([], [])
# Iterate through the data points and update the scatter plot
for i in range(100):
	# Generate and add data points to the deque
	new_x = i
	new_y = (0, 100)
	data_points.append((new_x, new_y))
	# Update the scatter plot with the new data points
	x_values = [x for x, y in data_points]
	y_values = [y for x, y in data_points]
	scatter.set_offsets(list(zip(x_values, y_values)))
	line.set_data(x_values, y_values)
	(0.01)
# Save the animation as an animated GIF
()

Above is Python using matplotlib to achieve dynamic visualization details, more information about matplotlib dynamic visualization please pay attention to my other related articles!