Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Refreshing Pyplot Line from a Changing Length Array

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)

like image 448
The Rhyno Avatar asked Sep 20 '25 13:09

The Rhyno


1 Answers

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)
like image 178
ImportanceOfBeingErnest Avatar answered Sep 22 '25 04:09

ImportanceOfBeingErnest