Python使用matplotlib画动态图

机器学习需要使用python实现相应的算法,因此学习了Matplotlib中的画图。
更多内容访问omegaxyz.com

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

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

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

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

代码:

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)

这里写图片描述

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

代码:

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)

效果:
这里写图片描述
更多内容访问omegaxyz.com
网站所有代码采用Apache 2.0授权
网站文章采用知识共享许可协议BY-NC-SA4.0授权
© 2018 • OmegaXYZ-版权所有 转载请注明出处

猜你喜欢

转载自blog.csdn.net/xyisv/article/details/80651334