根据colormap设置线条颜色

Gab*_*iel 5 python matplotlib

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

line_list = [line_1, line_2, line_3, ..., line_M]
Run Code Online (Sandbox Code Playgroud)

其中每个line_i是由两个子子列表组成的子列表,一个用于x坐标,另一个用于y坐标:

line_i = [[x_1i, x2_i, .., x_Ni], [y_1i, y_2i, .., y_Ni]]
Run Code Online (Sandbox Code Playgroud)

我也有一个line_list与花车相同长度的列表,:

floats_list = [0.23, 4.5, 1.6, ..., float_M]
Run Code Online (Sandbox Code Playgroud)

我想绘制每一行,给它一个颜色图中的颜色,并与floats_list列表中索引的位置相关.因此line_j它的颜色将由数字决定floats_list[j].我还需要在侧面显示一个颜色条

代码会喜欢这样的东西,除了它应该工作:)

import matplotlib.pyplot as plt

line1 = [[0.5,3.6,4.5],[1.2,2.0,3.6]]
line2 = [[1.5,0.4,3.1,4.9],[5.1,0.2,7.4,0.3]]
line3 = [[1.5,3.6],[8.4,2.3]]

line_list = [line1,line2,line3]
floats_list = [1.2,0.3,5.6]

# Define colormap.
cm = plt.cm.get_cmap('RdYlBu')

# plot all lines.
for j,lin in enumerate(line_list): 
    plt.plot(lin[0], lin[1], c=floats_list[j])

# Show colorbar.
plt.colorbar()

plt.show()
Run Code Online (Sandbox Code Playgroud)

Joe*_*ton 11

这是最容易使用的LineCollection.事实上,它希望线条的格式与您已有的格式相似.要通过第三个变量为线条着色,只需指定array=floats_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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这反复呼叫有两个主要优点plot.

  1. 渲染速度. Collections渲染速度远远超过大量类似的艺术家.
  2. 根据色图(或/或稍后更新色彩图),通过另一个变量为数据着色更容易.