将样本点转换为时间值

时间:2014-07-24 04:02:35

标签: python-2.7 matplotlib

import sys
import serial
import numpy as np
import matplotlib.pyplot as plt
from collections import deque

port = "COM11"
baud = 9600
timeout=1

ser = serial.Serial()
ser.port = port
ser.baudrate = baud
ser.timeout = timeout


a1 = deque([0.0]*100)
#ax = plt.axes(xlim=(0, 100), ylim=(0, 1000))



line, = plt.plot(a1)
plt.ion()
plt.ylim([0,1000])

try:
  ser.open()
except:
  sys.stderr.write("Error opening serial port %s\n" % (ser.portstr) )
  sys.exit(1)

#ser.setRtsCts(0)

while 1:
     # Read from serial port, blocking
     data = ser.read(1)

     # If there is more than 1 byte, read the rest
     n = ser.inWaiting()
     data = data + ser.read(n)
     #sys.stdout.write(data)
     print(a1)

     a1.appendleft((data))
     datatoplot = a1.pop()
     line.set_ydata(a1)
     plt.draw()

我在串口值和采样点之间得到了一个图。我想绘制连续绘图值与时间的关系。有没有办法将样本点转换为时间值,比如我们如何使用 freqs = scipy.fftpack.fftfreq(n,d)将样本点转换为频率值 感谢

2 个答案:

答案 0 :(得分:0)

如果您想从程序开始绘制数据与时间,那么:

import time

t0 = time.time()
tlist = deque([np.nan] * 100)

while 1:
    # read the serial data ...
    # when you have read a sample, capture the time difference
    # and put it into a queue (similarly to the data values)
    deltat = time.time() - t0
    dlist.appendleft((deltat))

    # remember to pop the data, as well
    dlist.pop()
    a1.pop()

    # set the x and y data
    line.set_xdata(tlist)
    line.set_ydata(a1)

    # draw it
    plt.draw()

现在你有从X轴上程序开始的秒数。

如果您想显示实时,请使用datetime.datetime个对象:

import datetime

dlist = deque([datetime.datetime.now()] * 100)

while 1:
    # capture the serial data ...

    dilst.appendleft((datetime.datetime.now()))

    # everything else as above

这应该会给你一张X轴实时的情节。

答案 1 :(得分:0)

import sys
import serial
import numpy as np
import matplotlib.pyplot as plt
import time
from collections import deque
from scipy import arange
port = "COM13"
baud = 9600
timeout=1

ser = serial.Serial()
ser.port = port
ser.baudrate = baud
ser.timeout = timeout
t0=time.time()


tlist = deque([np.nan]*10)
a1 = deque([0.0]*10)
#ax = plt.axes(xlim=(0, 100), ylim=(0, 1000))



line, = plt.plot(a1)
plt.ion()
plt.ylim([-100,100])
plt.grid(b=True,which= 'major' , color= 'g' , linestyle= '--')
#plt.grid(b=True,which= 'minor' , color= '-m' , linestyle= '--')

try:
  ser.open()
except:
  sys.stderr.write("Error opening serial port %s\n" % (ser.portstr) )
  sys.exit(1)

#ser.setRtsCts(0)

while 1:
     # Read from serial port, blocking
     data = ser.read(1)

     # If there is more than 1 byte, read the rest
     n = ser.inWaiting()
     data = data + ser.read(n)
     #sys.stdout.write(data)
     #print(a1)
     #data1=int(data)-128

     deltat = time.time() - t0


     tlist.appendleft((deltat1))
     datatoplot = tlist.pop()

     a1.appendleft((data))
     datatoplot = a1.pop()
     line.set_xdata(tlist)
     line.set_ydata(a1)
     plt.hold(False)
     plt.draw()

这是我使用的完整代码,是的,我已经更改了line.pop。但正如我之前在评论中解释的那样,我无法获得x轴中的时间值