3

The application I'm coding for requires a real time plot of incoming data that is being stored long term in an excel spreadsheet. So the real time graph displays the 25 most recent data points.

The problem comes when the plot has to shift in the newest data point and shift out the oldest point. When I do this, the graph "smears" as shown here: here

I then began to use plt.cla(), but this causes me to lose all formatting in my plots, such as the title, axes, etc. Is there any way for me to update my graph, but keep my graph formatting?

Here's an example after plt.cla():

after plt.cla().

And here's basically how I'm updating my graphs within a larger loop:

if data_point_index < max_data_points:
    y_data[data_point_index] = measurement
    plt.plot(x_data[:data_point_index + 1], y_data[:data_point_index + 1], 'or--')
else:
    plt.cla()
    y_data[0:max_data_points - 1] = y_data[1:max_data_points]
    y_data[max_data_points - 1] = measurement
    plt.plot(x_data, y_data, 'or--')
plt.pause(0.00001)

I know I can just re-add axis labels and such, but I feel like there should be a more eloquent way to do so and it is somewhat of a hassle as there can be multiple sub-plots and reformatting the figure takes a non-trivial amount of time.

1 Answer 1

1

Rather than plt.cla(), which as you have found out clears everything on the axes, you could just remove the last line plotted, which will leave you labels and formatting intact.

The Axes instance has an attribute lines, which stores all the lines currently plotted on the axes. To remove the last line plotted, we can access the current axes using plt.gca(), and then pop() from the list of lines on the axes.

else:
    plt.gca().lines.pop()
    y_data[0:max_data_points - 1] = y_data[1:max_data_points]
    y_data[max_data_points - 1] = measurement
    plt.plot(x_data, y_data, 'or--')
Sign up to request clarification or add additional context in comments.

1 Comment

Worked for the most part. Had to change from popping to clearing the list completely by plt.gca().lines[:] = [] because popping only removed the most recent data point, where I need to shift everything down and add a new data point. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.