Python uses matplotlib to achieve dynamic visual detail _python_script home

Python uses matplotlib for dynamic visual detailing

Updated: August 28, 2023 14:56:27 Author: python Collector
Data visualization in Python refers to the graphical representation of raw data to better visualize, understand and reason,Python provides a variety of libraries, including different features for visualizing data, let's take a look at how to use matplotlib to achieve dynamic visualization, right

Data visualization in Python refers to the graphical representation of raw data for better visualization, understanding, and reasoning. Python provides a variety of libraries with different features for visualizing data, and can support different types of graphics, namely Matplotlib, Seaborn, Bokeh, Plotly, and so on.

Dynamic visualization in Python

Dynamic visualization of any system means graphically representing changes in the state of the current system during the presentation. In terms of data visualization in Python, dynamic visualization is a dynamic graph that either changes over time, as in a video, or changes as the user changes the input, but in the current presentation it seems to be alive.

Steps for creating a dynamic graph in Python

Step 1. Create a queue of fixed length

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 drawing in Python means creating a data structure that can store a fixed number of elements and discard the oldest elements when the container is full. It is very useful when we want to plot data points that are constantly updated. By limiting the size of the container, you can improve the performance and clarity of the drawing.

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)  

exportation

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

Step 2. Generate the point and save it to the queue

Here, we generate data points dynamically and attach them to the queue data structure, rather than performing manual operations as shown in the example above. Here we will use 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 = random.randint(0, 100)
    data_points.append(new_data_point)
    print(data_points)

exportation

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 keep the queue fixed length. Here, we remove the element from the left in accordance with 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)

exportation

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. Draw the queue and pause the drawing for visualization

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

import matplotlib.pyplot 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 = plt.subplots()
line = ax.plot([])
# 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 = random.randint(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
    plt.pause(0.01)
# Show the plot
plt.show()

Step 5. Clear the drawing

When the data points are updated in real time, we will clear the plot before drawing 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 matplotlib.pyplot 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 = plt.subplots()
line, = ax.plot([])
# 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 = random.randint(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)
	plt.pause(0.01)
	# Clear the plot for the next set of values
	line.set_data([], [])
# Show the plot
plt.show()

Dynamic scatter plot

import matplotlib.pyplot 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 = plt.subplots() # 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 = ax.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 = random.randint(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)) plt.pause(0.01) # Show the plot plt.show()

Dynamic scatter chart and line chart

import matplotlib.pyplot as plt
from collections import deque
import random
from matplotlib.animation 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 = plt.subplots()
line, = ax.plot([])
# 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 = ax.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 = random.randint(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)
	plt.pause(0.01)
# Save the animation as an animated GIF
plt.show()

The above is the detailed content of Python using matplotlib to achieve dynamic visualization, more information about matplotlib dynamic visualization please pay attention to script home other related articles!

Related article

  • Python列表的深复制和浅复制示例详解

    Python list deep copy and shallow copy examples detailed

    This article mainly introduces the relevant information about the deep copy and shallow copy of the Python list, the article introduces the example code in great detail, which has certain reference value for everyone's study or work, and the friends who need to study together with the small series below
    2021-02-02
  • Python动态规划之零钱兑换问题详解

    Python dynamic programming change conversion problem detailed solution

    This article mainly introduces the Python dynamic programming change problem detailed solution, this time we will follow the routine template, and then analyze a classic dynamic change problem, calculate and return can make up the total amount of the minimum number of coins required if there is no combination of coins can form the total amount, return -1, the need of friends can refer to the next
    2023-11-11
  • Django自定义分页与bootstrap分页结合

    Django custom paging is combined with bootstrap paging

    This article mainly introduces the method of using Django custom paging and bootstrap paging in detail, which has certain reference value, interested partners can refer to it
    2017-05-05
  • Python操作PostgreSQL数据库的基本方法(增删改查)

    Python operating PostgreSQL database basic methods (add, delete, modify and check)

    PostgreSQL database is one of the most commonly used relational databases, the most attractive point is that it is an open source database and has scalability, can provide rich applications, this article mainly introduces the basic method of Python operation PostgreSQL database, the article introduces the connection PostgreSQL number According to the database, as well as the addition and deletion of the check, the need of friends can refer to the next
    2023-09-09
  • Pytorch相关知识介绍与应用

    Pytorch related knowledge introduction and application

    Recently, I picked up the relevant technology of machine learning again. I learned and used the Tensorflow 2.x tool during the undergraduate graduation period. At that time, I used it directly without understanding it, but now I have enough time, energy and basic knowledge to re-learn it
    2022-11-11
  • Python编程实现线性回归和批量梯度下降法代码实例

    Python programming to implement linear regression and batch gradient descent code examples

    This article mainly introduces Python programming to achieve linear regression and batch gradient descent method code examples, has a certain reference value, need friends can refer to
    2018-01-01
  • HTTPX入门使用教程

    Getting started with HTTPX

    HTTPX is a Python stack HTTP client library, it provides a higher level than the standard library, more advanced features, such as connection reuse, connection pooling, timeout control, automatic reproduction requests, the following through this article to introduce the introduction of HTTPX knowledge and basic usage, interested friends take a look
    2023-12-12
  • 利用scrapy将爬到的数据保存到mysql(防止重复)

    Save crawled data to mysql using scrapy (prevents duplication)

    This article mainly introduces the relevant information about the use of scrapy to save the crawled data to mysql (to prevent duplication), the article introduces very detailed through the example code, for everyone's study or work has a certain reference learning value, the friends need to take a look at it below.
    2018-03-03
  • 基于Python编写一个DOS命令辅助工具

    Write a DOS command assistant based on Python

    In the daily System management and maintenance work, the execution of DOS (Disk Operating System) commands is an essential task, let's take a look at how to use Python to write a simple DOS command assistant tool to simplify the system administration task
    2024-01-01
  • python实现的一个火车票转让信息采集器

    python implementation of a train ticket transfer information collector

    This article mainly introduces a train ticket transfer information collector implemented by python, the source of information collection is 58 same journey or Ganji network, the need of friends can refer to the next
    2014-07-07

Latest comments