Python 显示数据图表

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python 显示数据图表

又是花落时   2022-09-29 我要评论

前言:

python利用matplotlib库中的plt.ion()函数实现即时数据动态显示:

1.非定长的时间轴

代码示例:

# -*- coding: utf-8 -*-
 
import matplotlib.pyplot as plt
import numpy as np
import time
from math import *
 
plt.ion() #开启interactive mode 成功的关键函数
plt.figure(1)
t = [0]
t_now = 0
m = [sin(t_now)]
 
for i in range(100):
    plt.clf() #清空画布上的所有内容
    t_now = i*0.3
    t.append(t_now)#模拟数据增量流入,保存历史数据
    m.append(sin(t_now))#模拟数据增量流入,保存历史数据
    plt.plot(t,m,'-r')
    plt.draw()#注意此函数需要调用
    plt.pause(0.1)

此时间轴在不断变长。 

2.定长时间轴 实时显示数据

使用队列  deque,保持数据是定长的,就可以显示固定长度时间轴的动态显示图,

代码示例:

import matplotlib.pyplot as plt
from collections import deque
from math import *
plt.ion()#启动实时
pData = deque(maxlen=30)
for i in range(30):
    pData.append(0)
fig = plt.figure()
t = deque(maxlen=30)
for i in range(30):
 
    t.append(0)
plt.title('Real-time Potentiometer reading')
(l1,)= plt.plot(pData)
plt.ylim([0, 1])
for i in range(2000):
        plt.pause(0.1)#暂停的时间
        t.append(i)
        pData.append(sin(i*0.3))
        print(pData)
        plt.plot(t,pData,'-r') 
 
        plt.draw()  

Spyder  运行结果(貌似在pycharm 有问题)

偶然间看到:

import numpy as np
import matplotlib.pyplot as plt
 
from IPython import display
import math
import time

fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.set_xlabel('Time')
ax.set_ylabel('cos(t)')
ax.set_title('')
 
line = None
plt.grid(True) #添加网格
plt.ion()  #interactive mode on
obsX = []
obsY = []
 
t0 = time.time()
while True:
    t = time.time()-t0
    obsX.append(t)
    obsY.append(math.cos(2*math.pi*1*t))
 
    if line is None:
        line = ax.plot(obsX,obsY,'-g',marker='*')[0]
 
    line.set_xdata(obsX)
    line.set_ydata(obsY)
 
    ax.set_xlim([t-10,t+1])
    ax.set_ylim([-1,1])
    plt.pause(0.01)

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们