Draw now and Matplotlib

瘦欲@ 提交于 2021-01-28 00:27:07

问题


I am currently working on a project that involves taking analog readings, and mapping them real time on a graph. So to complete this I am running a photo resister through an Arduino Analog port and am reading that data via python 3.4.3. On the python side I have maplotlib, and drawnow installed. The code as it is shown below will plot the first data marker that the resistor will read, but will not update it real time. However if I change the resistance and then restart the program it will then plot the new value continually. What I want it to do is change the value on the graph as I change the value of the photo resistor.

import serial # import from pySerial
import numpy # import library from Numerical python
import matplotlib.pyplot as plt # import Library from matplotlib
from drawnow import drawnow # import lib from drawnow

ConF = [] # create an empty array for graphing
ArduinoData = serial.Serial('com3',9600) # set up serial connection with    arduino
plt.ion() # tell matplotlib you want interactive mode to plot data
cnt = 0

def makeFig(): # creat a function to make plot
    plt.plot(ConF, 'go-')

while True: # loop that lasts forever
    while (ArduinoData.inWaiting()==0): # wait till there is data to plot
         pass # do nothing

    arduinoString = ArduinoData.readline()
    dataArray = arduinoString 
    Con = float(arduinoString) # turn string into numbers
    ConF.append(Con) # addinf to the array.

    drawnow(makeFig)  # call draw now to update 
    plt.pause(.000001)
    cnt=cnt+1 
    if(cnt>50):
         ConF.pop(0)

I am not sure where my mistake is, there is no error message... it just plots the same data point over and over. Any help would be most welcome.


回答1:


Something like:

fig, ax = plt.subplots()
ln, = ax.plot([], [], 'go-')
while True:
    x, y = get_new_data()
    X, Y = ln.get_xdata(), ln.get_ydata()
    ln.set_data(np.r_[X, x], np.r_[Y, y])
    fig.canvas.draw()
    fig.canvas.flush_events()

should do the trick.



来源:https://stackoverflow.com/questions/30972289/draw-now-and-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!