失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 用python画动图_Python使用matplotlib画动态图

用python画动图_Python使用matplotlib画动态图

时间:2023-02-02 08:38:57

相关推荐

用python画动图_Python使用matplotlib画动态图

机器学习需要使用python实现相应的算法,因此学习了Matplotlib中的画图。

当然为了能显示机器学习中每次迭代的效果与收敛速度,需要画出动态图形。

下面给出两个例子,分别可以画出动态条形图和动态折线图(使用两种不同的方法)。

注意要使用到plt.pause(time)函数。

动态条形图

基本原理是将数据放入数组,然后每次往数组里面增加一个数,清除之前的图,重新画出图像。

代码:

Python

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

y1 = []

for i in range(50):

y1.append(i) # 每迭代一次,将i放入y1中画出来

ax.cla() # 清除键

ax.bar(y1, label='test', height=y1, width=0.3)

ax.legend()

plt.pause(0.1)

1

2

3

4

5

6

7

8

9

importmatplotlib.pyplotasplt

fig,ax=plt.subplots()

y1=[]

foriinrange(50):

y1.append(i)# 每迭代一次,将i放入y1中画出来

ax.cla()# 清除键

ax.bar(y1,label='test',height=y1,width=0.3)

ax.legend()

plt.pause(0.1)

效果:

动态折线图

基本原理是使用一个长度为2的数组,每次替换数据并在原始图像后追加。

代码:

Python

import numpy as np

import matplotlib.pyplot as plt

plt.axis([0, 100, 0, 1])

plt.ion()

xs = [0, 0]

ys = [1, 1]

for i in range(100):

y = np.random.random()

xs[0] = xs[1]

ys[0] = ys[1]

xs[1] = i

ys[1] = y

plt.plot(xs, ys)

plt.pause(0.1)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

importnumpyasnp

importmatplotlib.pyplotasplt

plt.axis([0,100,0,1])

plt.ion()

xs=[0,0]

ys=[1,1]

foriinrange(100):

y=np.random.random()

xs[0]=xs[1]

ys[0]=ys[1]

xs[1]=i

ys[1]=y

plt.plot(xs,ys)

plt.pause(0.1)

效果:

如果觉得《用python画动图_Python使用matplotlib画动态图》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。