2

I'd like to update a plot by redrawing a new curve (with 100 points) in real-time.

This works:

import time, matplotlib.pyplot as plt, numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
t0 = time.time()
for i in range(10000000):
    x = np.random.random(100)
    ax.clear()
    ax.plot(x, color='b')
    fig.show()
    plt.pause(0.01)
    print(i, i/(time.time()-t0))

but there is only ~10 FPS, which seems slow.

What is the standard way to do this in Matplotlib?

I have already read How to update a plot in matplotlib and How do I plot in real-time in a while loop using matplotlib? but these cases are different because they add a new point to an existing plot. In my use case, I need to redraw everything and keep 100 points.

Basj
  • 41,386
  • 99
  • 383
  • 673

1 Answers1

3

I do not know any technique to gain an order of magnitude. Nevertheless you can slightly increase the FPS with

  1. update the line data instead of creating a new plot with set_ydata (and/or set_xdata)
  2. use Figure.canvas.draw_idle() instead of Figure.canvas.draw() (cf. this question).

Thus I would recommand you to try the following:

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

fig = plt.figure()
ax = fig.add_subplot(111)
t0 = time.time()

x = np.random.random(100)
l, *_ = ax.plot(x, color='b')
fig.show()
fig.canvas.flush_events()
ax.set_autoscale_on(False)
for i in range(10000000):
    x = np.random.random(100)
    l.set_ydata(x)
    fig.canvas.draw_idle()
    fig.canvas.flush_events()
    print(i, i/(time.time()-t0))

Note that, as mentioned by @Bhargav in the comments, changing matplotlib backend can also help (e.g. matplotlib.use('QtAgg')).

I hope this help.

Remi Cuingnet
  • 943
  • 10
  • 14
  • 3
    I've tried your code .It Jumped all away from 20 to 50 FPS...Try backends along with your edits...I got arround 70 FPS after uisng [backends](https://stackoverflow.com/questions/4930524/how-can-i-set-the-backend-in-matplotlib-in-python) – Bhargav - Retarded Skills Feb 13 '23 at 11:31