在更短的时间内绘制许多图 - python

Yas*_*ine 3 python plot matplotlib

我想在同一张图中绘制大约 50 000 列。这是我使用的代码:

# "Xaxis" is a list containing the x-axis, and "data" a list of the 50 000 data series I want to plot.
for elt in data:
    plt.plot(Xaxis,elt)
Run Code Online (Sandbox Code Playgroud)

这有点耗时(我需要等待大约15分钟)。有什么优化流程/减少时间的建议吗?

谢谢!

Imp*_*est 5

一句话回答:使用LineCollection.


有多种选项可以绘制多条线。

A、循环

人们可以循环遍历数据并plot为每行创建一个。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection


def loop(N, show=False):
    x = np.random.rand(N,3)
    y = np.random.rand(N,3)
    
    fig, ax = plt.subplots()
    for i in range(N):
        ax.plot(x[i], y[i])
        
    if show:
        plt.show()
    else:
        fig.canvas.draw()
    plt.close(fig)
Run Code Online (Sandbox Code Playgroud)

B. 绘制矩阵

您可以提供一个矩阵,其中每一列包含一行的值,而不是plot多次调用。plot然而,这仍然会创建Line2D与矩阵中的列一样多的对象。

def matrix(N, show=False):
    x = np.random.rand(N,3)
    y = np.random.rand(N,3)
    
    fig, ax = plt.subplots()

    ax.plot(x.T, y.T)
        
    if show:
        plt.show()
    else:
        fig.canvas.draw()
    plt.close(fig)
Run Code Online (Sandbox Code Playgroud)

C.ALineCollection

集合允许创建单个艺术家,该艺术家仅渲染一次。这是最快的选择。

from matplotlib.collections import LineCollection
    
def linecoll(N, show=False):
    x = np.random.rand(N,3)
    y = np.random.rand(N,3)
    
    data = np.stack((x,y), axis=2)
    fig, ax = plt.subplots()

    ax.add_collection(LineCollection(data))
        
    if show:
        plt.show()
    else:
        fig.canvas.draw()
    plt.close(fig)
Run Code Online (Sandbox Code Playgroud)

D. 带有 nan 的单图。

nan将在数据中值的位置截取一条线。这允许绘制单个Line2D,但nan在构成单独线条的每个数据块的末尾带有 s 。

def fillednan(N, show=False):
    x = np.random.rand(N,3)
    y = np.random.rand(N,3)
    
    X = np.concatenate((x, np.ones_like(x)*np.nan)).flatten()
    Y = np.concatenate((y, np.ones_like(x)*np.nan)).flatten()
    
    fig, ax = plt.subplots()

    ax.plot(X,Y)
        
    if show:
        plt.show()
    else:
        fig.canvas.draw()
    plt.close(fig)
Run Code Online (Sandbox Code Playgroud)

结果。

N针对不同的through值运行这些函数,%timeit结果如下图所示。

在此输入图像描述

我们看到它LineCollection花费的时间最少。对于大公司来说,N差异是显着的。循环效率最低,其次是矩阵。这是因为两者都会创建N需要绘制的单独线条。带有 nan 的单行和 LineCollection 效率更高,仍然LineCollection优于plot.