当前位置:网站首页>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 :

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 :

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 !
边栏推荐
猜你喜欢

Vscode shortcut

Comprehensive introduction to Simulink solver

Ssl/tls, symmetric and asymmetric encryption, and tlsv1.3

“Method Not Allowed“,405问题分析及解决

Optimized three-dimensional space positioning method and its fast implementation in C language
![Chapter V exercises (124, 678, 15, 19, 22) [microcomputer principles] [exercises]](/img/16/d67f38d32af6904a7d0be9f2e5be70.png)
Chapter V exercises (124, 678, 15, 19, 22) [microcomputer principles] [exercises]
![Chapter VI exercises (678) [microcomputer principles] [exercises]](/img/20/b02bccebfb245d4710f6f48dd0f5e4.png)
Chapter VI exercises (678) [microcomputer principles] [exercises]

【TSP问题】基于Hopfield神经网络求解旅行商问题附Matlab代码

Apache foundation officially announced Apache inlong as a top-level project

ADC acquisition noise and comparison between RMS filter and Kalman filter
随机推荐
[understanding of opportunity -30]: Guiguzi - internal "chapter - empathy, stand on the other side's position and narrow the psychological distance with the other side
1-9network configuration in VMWare
WordPress
Chapter VI exercises (678) [microcomputer principles] [exercises]
Redis的安装及启动
11.1.2 overview of Flink_ Wordcount case
Should group by be used whenever aggregate functions are used in SQL?
Data synchronization
C IO stream (II) extension class_ Packer
Solution to component stele in SMT chip processing
Unified gateway
Ssl/tls, symmetric and asymmetric encryption, and tlsv1.3
debezium
86. (cesium chapter) cesium overlay surface receiving shadow effect (gltf model)
1-10Vmware构建自定义的网络架构
案例:绘制Matplotlib动态图
[机缘参悟-30]:鬼谷子-内揵篇-同理心,站在对方的立场,拉近与对方的心理距离
Binary sort tree
Kylin
ADC acquisition noise and comparison between RMS filter and Kalman filter