当前位置:网站首页>Case: drawing Matplotlib dynamic graph

Case: drawing Matplotlib dynamic graph

2022-06-26 00:55:00 Algorithm channel

Study zhenguo The teacher's Python Class has been a week , I feel that I have learned a lot , Just yesterday, the teacher sent a message in the receiving group 100 List of dollars , I answered without hesitation , Not only can we test whether we can apply what we have learned , And make money from crawfish (50 element ~).

Development requirements

The requirements of this list , It's using Python Medium matplotlib Library to draw dynamic line graph , The requirements description is simple and easy to understand , But it also needs to be analyzed .

Matplotlib library

This library is Python One of the necessary libraries for data development , Its main function is to draw charts , And the implementation is also very simple , A few lines of code can draw a histogram 、 Broken line diagram 、 Scatter plot 、 Pie charts and other commonly used charts , Some complex data analysis charts, it can also be competent .

Share a website here : www.matplotlib.org.cn/gallery/#lines-bars-and-markers, You can see that Matplotlib Some cases of drawing , As a reference for their own development .

Core issues

Matplotlib Library to draw a static line chart is relatively simple , Given X Axis and Y The axis data set is OK , But I want to draw a dynamic line chart , We must find a way to make the drawn picture move .

In fact, this problem is not difficult to understand ,Matplotlib Drawing is to generate a picture , The principle of making it move is like animation , Constantly generate new pictures , Connect them back and forth , Just play it frame by frame .

The development process

Understand the core issues , You can start to solve the problem .

Load data

Before drawing , First get the data set to , The demand side gave a sheet excel form , You need to extract the required data set from the table .

This process is also relatively simple , Need to use Python Another library for data analysis Pandas .

Just one line of code pandas.read_excel('data.xls'), You can put the excel File loaded into memory .

Then you can operate like dict Get the data set of each column , Such as :cls = pandas.read_excel('data.xls')[' Column header name '], You'll get one <class 'pandas.core.series.Series'> object , You can directly traverse each row of data , You can also convert the format to a list type .

Draw a line

Once you have the data , You can draw , First draw a broken line , Present the existing data , Look at the effect .

import matplotlib.pyplot as plt
import data

fig, ax = plt.subplots(figsize=(16, 9), dpi=80)
ax.set_ylim(0, 35)
ax.set_xticks(range(0, len(xdata), 10))

xdata = data.times
ydata = data.dealnums
ax.plot(xdata, ydata)

fig.autofmt_xdate()
plt.show()

Simple code , The following is the line chart drawn :

c8152e654a0a83235ab387746d6210fd.png

Let the broken line move

What to do next , Is to make the line chart move , Keep showing new data .

To achieve this effect , You need to do two things , First, let the data move , Add new data to the data set , The second is to make the drawing move at a specified time interval .

First action , Here's how I do it , Go straight to the code :

for x, y in zip(xdata_set, ydata_set):
    xdata.append(x)
    ydata.append(y)

That is to split the original data set into a single data , Load into one by one X Axis and Y Axis data set , Realize the effect of dynamic data increase .

Second operation , The first thing I thought of , Every time the data is updated , Empty the entire canvas , Redraw the latest chart .

for x, y in zip(xdata_set, ydata_set):
    xdata.append(x)
    ydata.append(y)
    
    plt.clf()  #  Empty the whole figure
    
    #  Reestablish the coordinate axis and draw a line chart 
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(xdata, ydata)
    
    plt.pause(1) #  Sleep 1 Draw a new picture in seconds 

There is one more point to pay attention to , Is to call at the beginning plt.ion() Method , Start interactive mode .

This method cannot directly save the image as a moving picture , So there's no way to show , The effect is the same as that of the following moving pictures .

New idea of dynamic diagram

After completing the requirements details according to the above ideas , I submitted the code to zhenguo teacher , The teacher not only gave affirmation and encouragement , It also provides a new idea .

That is to use Matplotlib Animation module to draw dynamic graph .

Quickly find the documents of relevant modules and methods to learn , Finally found , Just use one animation.FuncAnimation Class can meet the requirements of this list .

And this class is very convenient to use , Pass... In the build function figure object 、 Functions that update charts 、 Just initialize the function and interval parameters .

import matplotlib.animation
import matplotlib.pyplot as plt
import data

fig = plt.figure(figsize=(16, 9), dpi=70)

def draw_line(fig, x_data, y_data):
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(xdata, ydata)
    return ax

def init_figure():
    #  Draw the initial chart 
    xdata = data.times
    ydata = data.dealnums

    return draw_line(fig, xdata, ydata)
    
def update(n):
    #  Update data set  xdata  and  ydata
    xdata = data.new_times
    ydata = data.new_dealnums
    #  Clear the previous coordinate system 
    plt.clf() 
    #  Draw the latest line chart 
    return draw_line(fit, xdata, ydata)

ani = animation.FuncAnimation(fig, update, init_func=init_figure, interval=1000)

#  Generate  gif  Move and save 
ani.save('test.gif', writer='pillow')

plt.show()

The modified code is also very simple and clear , It can also save the generated dynamic graph .

Finally, improve some requirements and code details , The end result is this :

ced0922167bf7eee1edead48137f9b57.gif

Isn't it cool !

To study the Python after , Found many interesting programming directions , Drawing development is only a small part of the macro blueprint .

Through this list , I made a breakthrough from eye meeting to hand meeting , Not only for Matplotlib Library has a deeper understanding , what's more !

The crayfish is available tonight !

原网站

版权声明
本文为[Algorithm channel]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206252243419010.html