matplotlib 加速循环中的绘图线

matplotlib Speeding up plotting lines in loop

我有几个使用 matplotlib 创建的子图。绘制数据后,我需要返回并在 for 循环中的数据点之间画线。我的数据文件很大,这需要 python 很长时间...

有没有办法加快速度?这是我的代码:

def generateHistogram(x, y, ax):
    x = np.log10(x)
    xerror = []

    numData = len(x)

    plt.rcParams['lines.solid_capstyle'] = 'butt'

    for dataIndex in range(0, numData-1):
        xerror.append(np.divide(np.subtract(x[dataIndex+1], x[dataIndex]), 2.0))

    for errorIndex in range(0, len(x)):
        if (errorIndex == 0):
            ax.semilogx((np.power(10, (x[errorIndex]-xerror[errorIndex])), np.power(10, x[errorIndex])),
                        (y[errorIndex], y[errorIndex]), linewidth=2, color='k')

        if (errorIndex == len(xerror)):
            ax.semilogx((np.power(10, x[errorIndex]), np.power(10, (x[errorIndex]+xerror[errorIndex-1]))),
                        (y[errorIndex], y[errorIndex]), linewidth=2, color='k')

        if (errorIndex < len(xerror)):
            ax.semilogx((np.power(10, x[errorIndex]), np.power(10, (x[errorIndex]+xerror[errorIndex]))),
                         (y[errorIndex], y[errorIndex]), linewidth=2, color='k')
            ax.semilogx((np.power(10, (x[errorIndex+1]-xerror[errorIndex])), np.power(10, x[errorIndex+1])),
                        (y[errorIndex+1], y[errorIndex+1]), linewidth=2, color='k')

            verticleLineXPos = np.power(10, (x[errorIndex]+xerror[errorIndex]))
            ax.semilogx((verticleLineXPos, verticleLineXPos), (y[errorIndex], y[errorIndex+1]),
                        linewidth=2, color='k')


    return xerror;

这基本上是在我需要的位置上的每个子图(x 轴是半对数刻度)上画线。您对提高性能有什么建议吗?

我在这里找到了这个参考资料,它提供了一个巧妙的优化方法:http://exnumerus.blogspot.com/2011/02/how-to-quickly-plot-multiple-line.html

它提供了 99% speed-up 的性能。它对我来说效果很好。

当您需要将不同的 kwargs 传递给不同的行时

非常适用于不需要将任何额外的 kwargs 传递给单独行的情况。

但是,如果您这样做(就像我所做的那样),那么您就不能使用他 link 中概述的 one-call 方法。

在检查了 plot 花费的时间之后,特别是当使用循环在同一轴上绘制多条线时,结果发现 自动缩放 浪费了很多时间添加每个内部 Line2D 对象后的视图。

为了解决这个问题,我们可以重用 plot 函数 (see here on the github repo) 的内部结构,但在完成后只调用一次 autoscale_view 函数。

这提供了 ~x2 的加速,虽然远不及 通过一次传递所有绘图参数来提高速度,对于需要传递不同 kwargs(例如特定线条颜色)的情况仍然有用。

示例代码如下。

import numpy as np
import matplotlib.pyplot as plt

Nlines = 1000
Npoints = 100

fig = plt.figure()
ax = fig.add_subplot(111)
xdata = (np.random.rand(Npoints) for N in range(Nlines))
ydata = (np.random.rand(Npoints) for N in range(Nlines))
colorvals = (np.random.rand() for N in range(Nlines))

for x, y, col in zip(xdata, ydata, colorvals):
    ax.add_line(
        plt.Line2D(
            x,y,
            color=plt.cm.jet(col)
        )
    )
ax.autoscale_view()