Set line colors according to colormap

前端 未结 1 2002
孤街浪徒
孤街浪徒 2020-12-02 00:35

I have a series of lines stored in a list like so:

line_list = [line_1, line_2, line_3, ..., line_M]

where each line_i is a su

相关标签:
1条回答
  • 2020-12-02 01:29

    It's easiest to use a LineCollection for this. In fact, it expects the lines to be in a similar format to what you already have. To color the lines by a third variable, just specify the array=floats_list. As an example:

    import numpy
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    
    # The line format you curently have:
    lines = [[(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)],
             [(0, 1, 2, 3, 4), (0, 1, 2, 3, 4)],
             [(0, 1, 2, 3, 4), (8, 7, 6, 5, 4)],
             [(4, 5, 6, 7, 8), (0, 1, 2, 3, 4)]]
    
    # Reformat it to what `LineCollection` expects:
    lines = [zip(x, y) for x, y in lines]
    
    z = np.array([0.1, 9.4, 3.8, 2.0])
    
    fig, ax = plt.subplots()
    lines = LineCollection(lines, array=z, cmap=plt.cm.rainbow, linewidths=5)
    ax.add_collection(lines)
    fig.colorbar(lines)
    
    # Manually adding artists doesn't rescale the plot, so we need to autoscale
    ax.autoscale()
    
    plt.show()
    

    enter image description here

    There are two main advantages of this over repeatedly calling plot.

    1. Rendering speed. Collections render much faster than a large number of similar artists.
    2. It's easier to color the data by another variable according to a colormap (and/or update the colormap later).
    0 讨论(0)
提交回复
热议问题