8

Python。matplotlib如何有效地将大量线段着色为独立渐变?
已经阅读了这个这个和其他的东西;他们都不是我们的答案!

我们有许多单独的线希望以渐变颜色绘制每条线。

上面第一个链接中提到的解决方案,如果您有多个字符串,则不起作用。换句话说,改变颜色循环会影响绘图中的所有内容,而不是唯一的兴趣线。这根本不符合我们的兴趣。

指向 matplotlib 站点的第二个链接使用将每行分割成许多行。这不是一个好方法,因为对于大量的行,比如 10000 甚至更多;即使您只选择每行 10 段,结果也太大了!即使这样,产生的线条也根本没有平滑着色!如果你将分割的数量作为线段的函数以获得更好的梯度,那么结果将非常巨大!难以显示,难以正确保存为文件。

4

1 回答 1

9

一个(次要)加速将是添加单个行集合而不是 10000 个单独的行集合。

只要所有线条共享相同的颜色图,您就可以将它们组合成一个线条集合,并且每条线条仍然可以具有独立的渐变。

Matplotlib 对于这种事情仍然很慢。它针对质量输出进行了优化,而不是快速绘制时间。但是,您可以稍微加快速度(~3x)。

所以,作为我认为你现在可能(?)这样做的一个例子:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
# Make random number generation consistent between runs
np.random.seed(5)

def main():
    numlines, numpoints = 2, 3
    lines = np.random.random((numlines, numpoints, 2))

    fig, ax = plt.subplots()
    for line in lines:
        # Add "num" additional segments to the line
        segments, color_scalar = interp(line, num=20)
        coll = LineCollection(segments)
        coll.set_array(color_scalar)
        ax.add_collection(coll)
    plt.show()

def interp(data, num=20):
    """Add "num" additional points to "data" at evenly spaced intervals and
    separate into individual segments."""
    x, y = data.T
    dist = np.hypot(np.diff(x - x.min()), np.diff(y - y.min())).cumsum()
    t = np.r_[0, dist] / dist.max()

    ti = np.linspace(0, 1, num, endpoint=True)
    xi = np.interp(ti, t, x)
    yi = np.interp(ti, t, y)

    # Insert the original vertices
    indices = np.searchsorted(ti, t)
    xi = np.insert(xi, indices, x)
    yi = np.insert(yi, indices, y)

    return reshuffle(xi, yi), ti

def reshuffle(x, y):
    """Reshape the line represented by "x" and "y" into an array of individual
    segments."""
    points = np.vstack([x, y]).T.reshape(-1,1,2)
    points = np.concatenate([points[:-1], points[1:]], axis=1)
    return points

if __name__ == '__main__':
    main()

相反,我建议按照这些思路做一些事情(唯一的区别在于main函数):

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
# Make random number generation consistent between runs
np.random.seed(5)

def main():
    numlines, numpoints = 2, 3
    points = np.random.random((numlines, numpoints, 2))

    # Add "num" additional segments to each line
    segments, color_scalar = zip(*[interp(item, num=20) for item in points])

    segments = np.vstack(segments)
    color_scalar = np.hstack(color_scalar)

    fig, ax = plt.subplots()
    coll = LineCollection(segments)
    coll.set_array(color_scalar)
    ax.add_collection(coll)

    plt.show()

def interp(data, num=20):
    """Add "num" additional points to "data" at evenly spaced intervals and
    separate into individual segments."""
    x, y = data.T
    dist = np.hypot(np.diff(x - x.min()), np.diff(y - y.min())).cumsum()
    t = np.r_[0, dist] / dist.max()

    ti = np.linspace(0, 1, num, endpoint=True)
    xi = np.interp(ti, t, x)
    yi = np.interp(ti, t, y)

    # Insert the original vertices
    indices = np.searchsorted(ti, t)
    xi = np.insert(xi, indices, x)
    yi = np.insert(yi, indices, y)

    return reshuffle(xi, yi), ti

def reshuffle(x, y):
    """Reshape the line represented by "x" and "y" into an array of individual
    segments."""
    points = np.vstack([x, y]).T.reshape(-1,1,2)
    points = np.concatenate([points[:-1], points[1:]], axis=1)
    return points

if __name__ == '__main__':
    main()

两个版本都生成相同的图:

在此处输入图像描述


但是,如果我们将行数增加到 10000 行,我们将开始看到性能上的显着差异。

使用 10000 行,每行 3 个点,另外还有 20 个点用于颜色渐变(每行 23 段),并查看将图形保存到 png 所需的时间:

Took 10.866694212 sec with a single collection
Took 28.594727993 sec with multiple collections

因此,在这种特殊情况下,使用单行集合将提供不到 3 倍的加速。它不是一流的,但总比没有好。

这是时序代码和输出图,无论其价值如何(由于绘图的顺序不同,输出图并不完全相同。如果您需要控制 z 级别,则必须坚持使用单独的线集) :

在此处输入图像描述

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import time
# Make random number generation consistent between runs
np.random.seed(5)

def main():
    numlines, numpoints = 10000, 3
    lines = np.random.random((numlines, numpoints, 2))

    # Overly simplistic timing, but timeit is overkill for this exmaple
    tic = time.time()
    single_collection(lines).savefig('/tmp/test_single.png')
    toc = time.time()
    print 'Took {} sec with a single collection'.format(toc-tic)

    tic = time.time()
    multiple_collections(lines).savefig('/tmp/test_multiple.png')
    toc = time.time()
    print 'Took {} sec with multiple collections'.format(toc-tic)

def single_collection(lines):
    # Add "num" additional segments to each line
    segments, color_scalar = zip(*[interp(item, num=20) for item in lines])
    segments = np.vstack(segments)
    color_scalar = np.hstack(color_scalar)

    fig, ax = plt.subplots()
    coll = LineCollection(segments)
    coll.set_array(color_scalar)
    ax.add_collection(coll)
    return fig

def multiple_collections(lines):
    fig, ax = plt.subplots()
    for line in lines:
        # Add "num" additional segments to the line
        segments, color_scalar = interp(line, num=20)
        coll = LineCollection(segments)
        coll.set_array(color_scalar)
        ax.add_collection(coll)
    return fig

def interp(data, num=20):
    """Add "num" additional points to "data" at evenly spaced intervals and
    separate into individual segments."""
    x, y = data.T
    dist = np.hypot(np.diff(x - x.min()), np.diff(y - y.min())).cumsum()
    t = np.r_[0, dist] / dist.max()

    ti = np.linspace(0, 1, num, endpoint=True)
    xi = np.interp(ti, t, x)
    yi = np.interp(ti, t, y)

    # Insert the original vertices
    indices = np.searchsorted(ti, t)
    xi = np.insert(xi, indices, x)
    yi = np.insert(yi, indices, y)

    return reshuffle(xi, yi), ti

def reshuffle(x, y):
    """Reshape the line represented by "x" and "y" into an array of individual
    segments."""
    points = np.vstack([x, y]).T.reshape(-1,1,2)
    points = np.concatenate([points[:-1], points[1:]], axis=1)
    return points

if __name__ == '__main__':
    main()
于 2012-11-30T17:11:08.497 回答