I'm sure this has been asked, but I've had a very hard time finding a concise answer that works on searches. A few good answers seem to depend on calculating the final size of the array in advance. Seems like this should be very simple, and I'm a bit of a newbie so maybe I'm just searching the wrong terms ...
My Question is: How do I get PyPlot to refresh the data of an existing line sourced from a numpy array of data, when the length of the array is unknown and changing over time?
My current code is as follows
#Initial Setup
changing_dataset = np.array(1) #initialize with a single blank y-value
plt.close('all') #clear all the priors
plt.ion()
f, axarr = plt.subplots(3,2) #setup a 3x2 plot ...only 1 shown below
axarr[0,0].set_title('My Plot')
line1, = axarr[0,0].plot(changing_dataset)
plt.show
... some code which appends new data to changing_dataset is omitted here...
then I simply want to do this:
line1.set_ydata(changing_dataset)
f.canvas.draw()
f.canvas.flush_events()
plt.show()
In order to update the line in my initial plot, to now be based on the new, larger dataset contained in the array "changing_dataset".
But this generates an error like
ValueError: shape mismatch: objects cannot be broadcast to a single shape
How do I get around the requirement that seems to need the array to be of a static size? I would prefer to not need to re-title and build the plot from scratch - as the only thing that needs to change is the line (and possibly auto-rescaling the axes)
A plot necessarily consists of x and y values. When setting line1.set_ydata(new_y_data)
where new_y_data
has a different length than the original y data, you break the correspondance of x and y values resulting in the shape mismatch error observed in the question.
If you want to change the number of y values in the plot, you need to change the number of x values as well.
Either use
line.set_xdata(new_x_values)
line.set_ydata(new_y_values)
or in one row
line.set_data(new_x_values, new_y_values)
In case you are plotting the y values against their index, the new_x_values
would simply be the first n integers with n being the number of y values,
line.set_data(np.arange(len(new_y_values)), new_y_values)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With