4

I have much the same problem as this guy: Dynamically updating plot in matplotlib. I want to update a graph with data from a serial port and I have been trying to implement this answer, but I can't get a MWE to work. The graph simply doesn't appear, but everything else seems to work. I have read about problems with the installation of Matplotlib causing similar symptoms.

Here is my Minimum Not Working Example (MNWE):

import numpy as np
import matplotlib.pyplot as plt

fig1 = plt.figure() #Create figure

l, = plt.plot([], [], 'r-') #What is the comma for? Is l some kind of struct/class?
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')

k = 5
xdata=[0.5 for i in range(k+1)]     # Generate a list to hold data
ydata=[j for j in range(k+1)]

while True:
    y = float(raw_input("y val :"))
    xdata.append(y)     # Append new data to list
    k = k + 1       # inc x value
    ydata.append(k)
    l.set_data(xdata,ydata) # update data
    print xdata     # Print for debug perposes
    print ydata
    plt.draw        # These seem to do nothing
    plt.show        # !?

Could someone please point me in the right direction / provide a link / tell me what to google? I'm lost. Thanks

Community
  • 1
  • 1
Aaron
  • 7,015
  • 2
  • 13
  • 22
  • 2
    Maybe a stupid question, but have you tried `plt.draw()` and `plt.show()`, including parentheses? Without parentheses you don't call the function. – fhdrsdg Dec 21 '14 at 14:15

1 Answers1

3

As suggested by user @fhdrsdg I was missing brackets. Getting the rescale to work requires code from: set_data and autoscale_view matplotlib

A working MWE is provided below:

import numpy as np
import matplotlib.pyplot as plt

plt.ion()       # Enable interactive mode
fig = plt.figure()  # Create figure
axes = fig.add_subplot(111) # Add subplot (dont worry only one plot appears)

axes.set_autoscale_on(True) # enable autoscale
axes.autoscale_view(True,True,True)

l, = plt.plot([], [], 'r-') # Plot blank data
plt.xlabel('x')         # Set up axes
plt.title('test')

k = 5
xdata=[0.5 for i in range(k+1)]     # Generate a list to hold data
ydata=[j for j in range(k+1)]

while True:
    y = float(raw_input("y val :")) #Get new data
    xdata.append(y)     # Append new data to list
    k = k + 1       # inc x value
    ydata.append(k)
    l.set_data(ydata,xdata) # update data
    print xdata     # Print for debug perposes
    print ydata
    axes.relim()        # Recalculate limits
    axes.autoscale_view(True,True,True) #Autoscale
    plt.draw()      # Redraw
Community
  • 1
  • 1
Aaron
  • 7,015
  • 2
  • 13
  • 22
  • This worked for me. Thank you very much for sharing this script. Just for the record, when setting the blank plot data, you really need a comma there. For example this `l = plt.plot([], [], 'r-')` does not work but this `l, = plt.plot([], [], 'r-')` does. – muammar Apr 08 '19 at 22:21