1

I need to make a plot and update it many times (100's or 1000's) so I need Python to update it very quickly. I found a wonderful solution but I am not allowed to add a comment.

Here is the code of the referred answer:

import time
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
line, = ax.plot(np.random.randn(100))

fig.canvas.draw()
plt.show(block=False)


tstart = time.time()
num_plots = 0
while time.time()-tstart < 5:
    line.set_ydata(np.random.randn(100))
    ax.draw_artist(ax.patch)
    ax.draw_artist(line)
    fig.canvas.blit(ax.bbox)
    fig.canvas.flush_events()
    num_plots += 1
print(num_plots/5)

To have my perfect solution I need to also update the title of the plot besides the lines. For example I would like to print the iteration number (or some counter for the loop) in the title of the figure.

How to do this?

I tried updating the title of the figure inside the while loop, but the title prints the first value of num_plots and then the last one, nothing in between. More specifically, I added

ax.set_title('num_plots = ' + str(num_plots))

as the last line inside the while loop, and it results in this behavior where you can see the title is only updated at the end of the loop (even when the instruction is inside it): click here to see the animated gif

terauser
  • 53
  • 5

1 Answers1

0

You can set the string in the text object returned by title, just like you set the ydata in the line object returned by plot:

titl = ax.set_title('')
while time.time()-tstart < 5:
   ...
   titl.set_text(f'num_plots = {num_plots}')
Jody Klymak
  • 4,979
  • 2
  • 15
  • 31