Simple and efficient dynamic visualization of Python arrays

Simple and efficient Python array visualization


main content

  • Introduction
  • Method to realize
  • Overall code

Introduction

  • When encountering some algorithms that involve arrays (such as sorting or statistics), the visualization of arrays can provide us with a more intuitive perspective to find bugs in our own programs (or learn the implementation principles of certain algorithms) .
  • Here is an array visualization class that I wrote for beginners. In order to reduce the difficulty and reduce the cost, I castrated a lot of secondary content.
  • In this code, I provide the corresponding interface, which allows other programmers to directly import my code file and expand it.

Method to realize

1 goal

  • Visualize the array

2 Implementation principle

  • Use Matplotlib to set the index of the array as xxx axis, the corresponding value isyyThe y- axis is then plotted as a histogram.
    NjCSMV.png

3 concrete realization

  • The library used is
    import matplotlib.pyplot as plt
    
3.1 Initialization
  • Here, use the plt.subplots() method to initialize a canvas, and store the returned fig and ax variables in the class for encapsulation, which is convenient for subsequent expansion.
    class VisualArray():
    """动态可视化数组"""
    
        def __init__(self):
            """初始化"""
            self.fig,self.ax = plt.subplots()
    
3.2 Drawing an image
  • The method of drawing a chart is to erase the image of the previous frame, and then draw the image of the next frame.
  • The bar method is used here to draw, and some basic display parameters are drawn to facilitate programmers to adjust the effect.
    def draw(self,arrays=[],rwidth=0.8,color='black',time=0.0001):
        """
        生成一帧图像
        arrays: 需要显示的数组
        rwidth: 直方图中的条宽
        color: 直方图的颜色
        time: 延迟,默认为0.1ms
        axis: 是否显示坐标轴
        """
    
        self.ax.cla()   # 清除上一帧图像
        self.ax.bar(range(0,len(arrays)), height=arrays, width=rwidth,color=color)
            
        plt.pause(time)  #暂停,防止速度太快无法
    
3.3 Stop painting
  • By default, the animation will disappear after drawing, so if you want to keep the last frame of image or end the animation early, you can use plt.show() . For convenience, this function is also specially encapsulated as a method.
    def stop(self):
        """结束绘画,使图片保留在最后一帧"""
        plt.show()
    
3.4 Analysis
  • This is a memoryless abstract data type, that is, each frame in this visualization class will not be affected by the previous display content (although you seem to be affected). Therefore, the space cost is a constant level.
  • Except for the ax.bar() method which is greatly affected by the array, the rest of the statements can be completed in constant time , so the method is analyzed separately, in the case of a fixed array size:
    NjpTAJ.png
    it can be seen that in addition to the equal frequency Except for the sharp point, the time cost at other times is constant.
  • Analyzing the dynamically changing array, there are:
    Nj9bVg.png
    after eliminating the interference of abnormal points, the time cost in the case of the dynamic array is linear.

Complete code

  • You can store this code separately in a .py and then call it. Just write this on the file that calls the code.
    import 代码名称
    
    Note that the two code files must be placed in the same file!
  •  #ArrayVisual.py
     import matplotlib.pyplot as plt
    
     class VisualArray():
         """动态可视化数组"""
    
         def __init__(self):
             """初始化"""
             self.fig,self.ax = plt.subplots()
    
         def draw(self,arrays=[],rwidth=0.8,color='black',time=0.0001):
             """
             生成一帧图像
             arrays: 需要显示的数组
             rwidth: 直方图中的条宽
             color: 直方图的颜色
             time: 延迟,默认为0.1ms
             axis: 是否显示坐标轴
             """
         
             self.ax.cla()   # 清除键
             self.ax.bar(range(0,len(arrays)), height=arrays, width=rwidth,color=color)
             plt.pause(time)
    
         def stop(self):
             """结束绘画,使图片保留在最后一帧"""
             plt.show()
    
    

By the way, give a thumbs up and support it TT
Author: Elwin
Feel free to reprint, remember to indicate the author

Guess you like

Origin blog.csdn.net/NikkiElwin/article/details/107111527
Recommended