Our programmers, designers, according to the needs of the painstaking development of statistical graphics, often not up to the requirements of users, the reason is generally not comprehensive expression, but also too much content and more disorderly, it is difficult to adjust.

In fact, it is the way we express ourselves that is disconnected from the work of the business people. Business people know what it is by looking at a map or several nearby maps. For example, in the indicator diagram of oil production engineering (see “Method and Practice of Using Matplotlib to graphically analyze data and Build training Set”), I can easily identify working conditions at a glance after a little learning.

Similarly, if you take out a single picture of the daily tank level change as shown in the following figure, you can see whether the tank is producing oil or receiving oil. However, when looking at the data, it is often difficult to identify whether it is static, vibration or fluctuations influenced by temperature. We think we’ve done a good job.

What if you put yourself in the other’s shoes and give the graph to the AI for intelligent recognition?This means that when we design and develop, we need to take a step further — how does ai recognize that I didn’t do well last time (seeClassification and Recognition of Working Condition Diagram by TensorFlow CNN Convolutional Neural Network (I)), my training data set was a single graph.

Nowadays, it is better to combine multiple images into a single image and label the current block, or to use a sequential model. This is because when I was analyzing the oil tank level data, I saw the one-day integration chart for a month, and EVEN I, who did not know the business, could see the operation cycle and efficiency (slope/cosine contrast in and out).

In this way, we can take it to the next level and go back to the user interface. Can we switch to animation for better expression of details? I have converted to animation, how to analyze again to learn.

This article first implements two techniques, one is to draw multiple subgraphs to form a large picture, the other is to draw animated GIF (MP4 can also be used).

1. Draw multiple subgraphs

Subplots of the plt.subplots(nrows=6, nCOLs =5), based on the Matplotlib library, will return a tuple containing figure and axes objects, explained in the code.

"" Created on aug 16 2020 @author: Xiaoyw" "
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator
# Import the MultipleLocator class from Pyplot, which is used to set the scale interval
from matplotlib import animation

def get_DataFromExcel(file_name) :
    
    df = pd.read_excel(file_name)

    return df

def feature_datatime(dat) :
    dat['MearsureTime'] = dat['MearsureTime'].astype('datetime64')
    df_dt = pd.DataFrame(columns=('Year'.'Month'.'Day'.'Hour'.'Minute'))
 
    df_dt['Hour'] = dat['MearsureTime'].dt.hour
    df_dt['Year'] = dat['MearsureTime'].dt.year
    df_dt['Month'] = dat['MearsureTime'].dt.month
    df_dt['Day'] = dat['MearsureTime'].dt.day
    df_dt['Minute'] = dat['MearsureTime'].dt.minute
    
    return df_dt

def draw_OilCanLevel(df) :
    df0 = df[(df['OilCanID'] = =2) & (df['Year'] = =2020) & (df['Month'] = =6)].reset_index(drop=True)
    df0 = df0.sort_values(by = ['Day'.'Hour'.'Minute'])
    count = df0.shape[0]
   
    y = []
    x = []
    for i in range(1.31):
        df_tmp = df0[df0['Day']==i]
        if df_tmp.shape[0] >0:
            x0 = ((df_tmp['Hour'] *60+df_tmp['Minute') /10).tolist()
            y0 = df_tmp['LiquidLevel'].values/100
            x.append(x0)
            y.append(y0)
    
    fig1, ax1 = plt.subplots(nrows=6, ncols=5)
    for i in range(6) :for j in range(5):           
            ax1[i, j].plot(x[i*5+j],y[i*5+j])
            ax1[i, j].set_xlim(0.150)
            ax1[i, j].set_ylim(0.13500/100)
            
            x_major_locator=MultipleLocator(20)
            # Set the x scale interval to 10 and store it in the variable
            y_major_locator=MultipleLocator(2000/100)
            Set the y scale interval to 20 and store it in the variable
            
            ax1[i, j].xaxis.set_major_locator(x_major_locator)
            Set the primary scale on the X-axis to a multiple of 1
            ax1[i, j].yaxis.set_major_locator(y_major_locator)
            Set the primary scale on the Y-axis to a multiple of 10
            ax1[i, j].set_ylabel('Level')
            ax1[i, j].set_xlabel('Time')
                        
    plt.show()

df0 = get_DataFromExcel('e:/drawCandata.xlsx') #('e:/drawCandata.xlsx') #('e:/CandataClean.xlsx')

df0 = pd.concat([df0,feature_datatime(df0)],axis=1)
draw_OilCanLevel(df0)
animation_gif(df0)
Copy the code

2. Animate giFs

If you want to animate matplotlib, you’ll need to introduce the animation module.

Draw curves at 10-minute intervals every day
def animation_gif(df) :
    df0 = df[(df['OilCanID'] = =2) & (df['Year'] = =2020) & (df['Month'] = =6)].reset_index(drop=True)
    df0 = df0.sort_values(by = ['Day'.'Hour'.'Minute'])
    count = df0.shape[0]
    
    y = []
    x = []

    for i in range(1.31):
        df_tmp = df0[df0['Day']==i]
        Take the data length of one day
        row = df_tmp.shape[0]
        if row > 0:
            for j in range(1.int(row/10) +1):
                k = j * 10
                if k > row: # 24*6 collection times per day
                    k = row + 1
                df_tmp0 = df_tmp[0:k]
                print('Row is {0}'.format(df_tmp0.shape[0]))
                x0 = ((df_tmp0['Hour'] *60+df_tmp0['Minute') /10).tolist()
                y0 = df_tmp0['LiquidLevel'].values/100
                x.append(x0)
                y.append(y0)
    # show the number of rows of data, i.e. the number of frames of the animation
    frame = len(x)

    fig, ax = plt.subplots()
    ax.set_xlim(0.150)
    ax.set_ylim(0.13500/100)
    x_major_locator=MultipleLocator(20)
    # Set the x scale interval to 10 and store it in the variable
    y_major_locator=MultipleLocator(2000/100)
    Set the y scale interval to 20 and store it in the variable
    
    ax.xaxis.set_major_locator(x_major_locator)
    Set the primary scale on the X-axis to a multiple of 1
    ax.yaxis.set_major_locator(y_major_locator)    
    
    ax.set_ylabel('Level')
    ax.set_xlabel('Time')    
    
    ln, = ax.plot([], [], 'r-', animated=False)  The third parameter indicates the color and line of the curve to draw

    def update(i) :
        label = 'timestep {0}'.format(i)
        print(label)
        #ax.cla() 
        # Update the line and axis labels
        ln.set_data(x[i],y[i])
        
        # return the object to be redrawn
        return ln, 
    #frames indicates the number of animation frames
    ani = animation.FuncAnimation(fig, update, frames=frame,interval=1000, blit=True)
    ani.save('e:/animation.gif', fps=10, dpi=80, writer='imagemagick')    
    plt.show()
Copy the code

Note that to save GIF images, this requires the developer to have ImageMagicK installed on their computer.

Reference:

[1] the matplotlib. Pyplot. Subplots.”

[2] How to Animate and save GIF images in Matplotlib? CSDN Blog, Frank909, 2018.12

[3] “CNN Algorithm Construction using Python Scientific Computing Package (1)” CSDN blog, Xiao Yongwei, 2018.05