为什么使用 plot() 绘制线条时 matplotlib 会变慢? [英] Why matplotlib get slow when use plot() to draw lines?

查看:80
本文介绍了为什么使用 plot() 绘制线条时 matplotlib 会变慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道为什么用matplotlib画线会很慢?如何解决?

I want to know why it will be very slow when I use matplotlib to draw lines? How to fix it?

以下是演示代码.它使用 plot() 在两个随机生成的点之间画一条线.

Belows are the demo code. It used plot() to draw a line between two randomly generated points.

在我的计算机上,END=100/200/500"结果为FPS=36.9/28.6/20".我需要无休止地画线,而且暂时会变得更糟.如何解决?谢谢!

On my computer, 'END=100/200/500' results 'FPS=36.9/28.6/20'. I need to endless draw lines and it will get worse while time being. How to solve it? Thanks!

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

def draw_demo():
    x = 100
    plt.axis([0, x, 0, 1])
    plt.ion()

    last = 50
    TIME = 5
    END = 1000
    time_start = time.time()

    for i in range(0, END):
        random_num = np.random.random()

        if i > 70:
            plt.axis([x - 100, x + 1, 0, 1])
            x += 1

        plt.plot([i, i + 1], [last, random_num])
        last = random_num

        plt.pause(0.0001)

    print ('FPS:', END/(time.time()-time_start))
    raw_input()

if __name__ == '__main__':
    draw_demo()

推荐答案

尝试类似:

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

def draw_demo2(ax):
    x = 100
    ax.set_xlim([x-100, x + 250])
    ax.set_ylim([0, 1])

    END = 250
    time_start = time.time()

    ln, = ax.plot([], [])
    x_data = []
    y_data = []
    for i in range(0, END):
        random_num = np.random.random()

        if i%100 == 99:
            cur_xlim = ax.get_xlim()
            ax.set_xlim(np.array(cur_xlim) + 100)
        x += 1
        x_data.append(x)
        y_data.append(random_num)
        ln.set_data(x_data, y_data)
        ax.figure.canvas.draw_idle()
        ax.figure.canvas.flush_events()

    print ('FPS:', END/(time.time()-time_start))


if __name__ == '__main__':
    draw_demo()

将 x 和 y 数据缓冲区截断到视图范围可能是值得的(因为每次绘制屏幕时列表都会转换为数组.

It might be worth truncating the x and y data buffers to the view range (as the lists are converted to arrays every time the screen is drawn.

如果您需要非常快速地查看 blitting,但这与更改限制的交互效果不佳,则重绘文本是绘制图形中最慢的部分之一.

If you need to go really fast look into blitting, however that does not interact well with changing the limits, redrawing the text is one of the slowest parts of drawing the figure.

还尝试使用 qt 而不是 tk,我看到该更改使速度提高了 4 倍.

Also try qt instead of tk, I saw a 4x speed up from that change.

这篇关于为什么使用 plot() 绘制线条时 matplotlib 会变慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆