Python 根据colormap设置线条颜色

Python 根据colormap设置线条颜色,python,matplotlib,Python,Matplotlib,我在列表中存储了一系列行,如下所示: line_list = [line_1, line_2, line_3, ..., line_M] 其中每个行_i是由两个子列表组成的子列表,一个子列表用于x坐标,另一个子列表用于y坐标: line_i = [[x_1i, x2_i, .., x_Ni], [y_1i, y_2i, .., y_Ni]] 我还有一个与line\u list长度相同的列表,由浮点数组成: floats_list = [0.23, 4.5, 1.6, ..., float_M

我在列表中存储了一系列行,如下所示:

line_list = [line_1, line_2, line_3, ..., line_M]
其中每个
行_i
是由两个子列表组成的子列表,一个子列表用于x坐标,另一个子列表用于y坐标:

line_i = [[x_1i, x2_i, .., x_Ni], [y_1i, y_2i, .., y_Ni]]
我还有一个与
line\u list
长度相同的列表,由浮点数组成:

floats_list = [0.23, 4.5, 1.6, ..., float_M]
我想绘制每条线,给它一个颜色,该颜色取自一个颜色图,并与它在
floats\u列表中的索引位置相关。因此,
line_j
的颜色将由编号
floats_list[j]
确定。我还需要一个色条显示在一边

代码希望类似这样,但它应该可以工作:)


使用
LineCollection
最简单。事实上,它希望这些行的格式与您已有的类似。要使用第三个变量为行着色,只需指定
array=floats\u list
。例如:

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()

与重复调用
plot
相比,这种方法有两个主要优点

  • 渲染速度<代码>收藏
  • 渲染速度比大量类似艺术家快得多
  • 根据colormap(和/或稍后更新colormap),通过另一个变量为数据着色更容易

  • Joe,如果我正确理解了你代码中的
    Z
    相当于我的
    浮动列表
    ,但是我不确定
    x
    y
    数组与我的
    行列表
    列表的关系。它们只是生成你
    行列表中已有内容的数据。示例中的
    变量的格式与您的
    行列表
    的格式完全相同。哎哟,我稍微误读了您的格式!等一下。。。(
    LineCollection
    要求的格式与您已有的格式非常相似。)exclent,但我们可以为这些行添加图例吗?Joe我已经提出了一个与您的答案相关的后续问题(这就是@void问这个问题的原因),如果您有时间,请访问:
    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()