Low FPS in MatPlotlib

南笙酒味 提交于 2021-01-28 05:22:46

问题


Faced with the fact that MatPlotlib when using self.frame.canvas.draw() I got only 12 FPS on a simple chart. I found a good article about acceleration speed MatPlotlib: https://bastibe.de/2013-05-30-speeding-up-matplotlib.html But part of the examples is working code, but the example with the fastest code (500 FPS) is not working. Attempts to read the documentation MatPlotlib have not yet led to success in understanding where the error is in the code: «AttributeError: draw_artist can only be used after an initial draw which caches the renderer». Where is the error in the code?

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

fig, ax = plt.subplots()
line, = ax.plot(np.random.randn(100))
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.update()
    fig.canvas.flush_events()
    num_plots += 1
print(num_plots/5)

回答1:


If using the Qt5Agg backend, you can indeed just do what the error suggest, namely draw the canvas once before starting the loop.

import time
import numpy as np
import matplotlib
matplotlib.use("Qt5Agg")
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.update()
    fig.canvas.flush_events()
    num_plots += 1
print(num_plots/5)

However, I would actually use blit instead of PyQt's update, such that it would work with any backend,

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)


来源:https://stackoverflow.com/questions/59702177/low-fps-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!