pyplot:创建热图真的很慢

发布于 2024-09-04 00:45:18 字数 467 浏览 3 评论 0原文

我有一个循环执行主体大约 200 次。在每次循环迭代中,它都会进行复杂的计算,然后作为调试,我希望生成 NxM 矩阵的热图。但是,生成此热图的速度慢得令人难以忍受,并且会显着减慢本来就很慢的算法。

我的代码是这样的:

import numpy
import matplotlib.pyplot as plt
for i in range(200):
    matrix = complex_calculation()
    plt.set_cmap("gray")
    plt.imshow(matrix)
    plt.savefig("frame{0}.png".format(i))

来自 numpy 的矩阵并不大 --- 300 x 600 的双精度数。即使我不保存图形而是更新屏幕上的绘图,速度也会更慢。

当然,我一定是在滥用 pyplot。 (Matlab 可以做到这一点,没问题。)如何加快速度?

I have a loop that executes the body about 200 times. In each loop iteration, it does a sophisticated calculation, and then as debugging, I wish to produce a heatmap of a NxM matrix. But, generating this heatmap is unbearably slow and significantly slow downs an already slow algorithm.

My code is along the lines:

import numpy
import matplotlib.pyplot as plt
for i in range(200):
    matrix = complex_calculation()
    plt.set_cmap("gray")
    plt.imshow(matrix)
    plt.savefig("frame{0}.png".format(i))

The matrix, from numpy, is not huge --- 300 x 600 of doubles. Even if I do not save the figure and instead update an on-screen plot, it's even slower.

Surely I must be abusing pyplot. (Matlab can do this, no problem.) How do I speed this up?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤独岁月 2024-09-11 00:45:18

尝试将 plt.clf() 放入循环中以清除当前图形:

for i in range(200):
    matrix = complex_calculation()
    plt.set_cmap("gray")
    plt.imshow(matrix)
    plt.savefig("frame{0}.png".format(i))
    plt.clf()

如果不这样做,循环会减慢,因为机器会努力为图形分配越来越多的内存。

Try putting plt.clf() in the loop to clear the current figure:

for i in range(200):
    matrix = complex_calculation()
    plt.set_cmap("gray")
    plt.imshow(matrix)
    plt.savefig("frame{0}.png".format(i))
    plt.clf()

If you don't do this, the loop slows down as the machine struggles to allocate more and more memory for the figure.

冧九 2024-09-11 00:45:18

我认为这更快一点:

import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
for i in range(200):
    matrix = complex_calculation()
    ax.imshow(matrix, cmap=cm.gray)
    fig.savefig("frame{0}.png".format(i))

plt.imshow 调用gca,后者调用gcf,检查是否有数字;如果没有,它就会创建一个。通过首先手动实例化图窗,您不需要执行所有这些操作。

I think this is a bit faster:

import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
for i in range(200):
    matrix = complex_calculation()
    ax.imshow(matrix, cmap=cm.gray)
    fig.savefig("frame{0}.png".format(i))

plt.imshow calls gca which calls gcf which checks to see if there is a figure; if not, it creates one. By manually instantiating the figure first, you do not need to do all that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文