7

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

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

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

line_i = [[x_1i, x2_i, .., x_Ni], [y_1i, y_2i, .., y_Ni]]

我还有一个与line_list浮点数相同长度的列表,:

floats_list = [0.23, 4.5, 1.6, ..., float_M]

我想绘制每条线,给它一种从颜色图中获取的颜色,并与其索引在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()
4

1 回答 1

14

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).
于 2013-11-08T21:20:20.817 回答