0

I'm reading a sensor signal from the COM-port and would like to show the values live in a plot. I managed to show the graph and it also gets updated but the graph changes its color for every new point. I guess the problem is that not only the point gets updated but the whole graph. My code looks like this:

import pylab as plt

buttonclick():
  plt.figure()
  ln, = plt.plot([])
  plt.ion()
  plt.show()
  plotdata =[]
  while self.Run:
    plotdata.append(getsensordata()) #getsensordata returns a float
    plt.plot(plotdata)
    plt.draw()
    time.sleep(1000)

I also tried another option with ln.set_data. With this option it seems that only the new points are updated but I can't confirm since there I have the problem that the axis doesn't scale automatically. I changed the while loop to:

i=0
while self.Run:
  plotdata.append(getsensordata())
  xdata.append(i)
  ln.set_data(xdata,plotdata)
  plt.autoscale(True,True,True)
  plt.draw()
  i+=1

I saw Can you plot live data in matplotlib? but this solution doesn't work at all in my case, no idea why. Also other solution with blib seem to me a little bit over the top since I seem to be very close to the solution with this easy solutions.

Community
  • 1
  • 1
Daniel
  • 33
  • 3

1 Answers1

1

Found the answer in Python Matplotlib: Dynamically update plot - array length not known a priori

fig = plt.figure()
ax = fig.add_subplot(111)
ln, = plt.plot([])
plt.ion()
axes=plt.axes()
plt.show()
plotdata = []
while self.Run:
  plotdata.append(getsensordata())
  plotdata.append(AH_SHT)
  ln.set_ydata(plotdata)
  ln.set_xdata(range(len(plotdata)))
  ax.relim()
  ax.autoscale_view()
  plt.draw()
Community
  • 1
  • 1
Daniel
  • 33
  • 3