根据颜色图设置线条颜色
我有一系列的行存储在这样的列表中:
I have a series of lines stored in a list like so:
line_list = [line_1, line_2, line_3, ..., line_M]
其中每个line_i
是一个由两个子子列表组成的子列表,一个用于x坐标,另一个用于y坐标:
where each line_i
is a sub-list composed of two sub-sub-lists, one for the x coordinates and the other for the y coordinates:
line_i = [[x_1i, x2_i, .., x_Ni], [y_1i, y_2i, .., y_Ni]]
我还有一个列表,其长度与由浮点数组成的line_list
相同,
I also have a list of the same length as line_list
composed of floats,:
floats_list = [0.23, 4.5, 1.6, ..., float_M]
我想绘制每条线,给它一种颜色,该颜色取自颜色图,并与其索引在floats_list
列表中的位置有关.因此,line_j
的颜色将由数字floats_list[j]
决定.我还需要在侧面显示一个彩条
I want to plot each line giving it a color taken from a color map and related to the position of its index in the floats_list
list. So line_j
will have its color determined by the number floats_list[j]
. I also need a colorbar shown to the side
该代码想要这样的东西,除了它应该可以工作:)
The code would like something like this, except it should work :)
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()
为此最容易使用LineCollection
.实际上,它希望这些行的格式与您已有的格式相似.要用第三个变量为线条着色,只需指定array=floats_list
.例如:
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()
与重复调用plot
相比,此方法有两个主要优点.
There are two main advantages of this over repeatedly calling plot
.
- 渲染速度.
Collections
的渲染速度比许多类似的艺术家快得多. - 根据颜色图通过另一个变量为数据着色更容易(和/或稍后更新颜色图).
- Rendering speed.
Collections
render much faster than a large number of similar artists. - It's easier to color the data by another variable according to a colormap (and/or update the colormap later).