如何根据 python 中一张图中不同绘图的一个变量获得不同的线条颜色?

how to get different line colors depending on one variable for different plots in one single figure in python?

假设我有一个图,其中有一定数量的图,类似于这个:

其中单幅图的颜色由 matplotlib 自动决定。获取这个的代码很简单:

for i in range(len(some_list)):
    x, y = some_function(dataset, some_list[i])
    plt.plot(x, y) 

现在假设所有这些行都依赖于第三个变量 z。我想包含此信息,用一种颜色绘制给定的线,该颜色提供有关 z 大小的信息,可能使用图右侧的颜色图和颜色条。你会建议我做什么?我排除使用图例,因为在我的图中我有更多的线条,而不是我展示的线条。我能找到的所有信息都是关于如何用不同颜色绘制一条线,但这不是我要找的。我先谢谢你了!

这是一些代码,在我看来,您可以轻松地适应您的问题

import numpy as np
import matplotlib.pyplot as plt
from random import randint

# generate some data
N, vmin, vmax = 12, 0, 20
rd = lambda: randint(vmin, vmax)
segments_z = [((rd(),rd()),(rd(),rd()),rd()) for _ in range(N)]

# prepare for the colorization of the lines,
# first the normalization function and the colomap we want to use
norm = plt.Normalize(vmin, vmax)
cm = plt.cm.rainbow
# most important, plt.plot doesn't prepare the ScalarMappable
# that's required to draw the colorbar, so we'll do it instead
sm = plt.cm.ScalarMappable(cmap=cm, norm=norm)

# plot the segments, the segment color depends on z
for p1, p2, z in segments_z:
    x, y = zip(p1,p2)
    plt.plot(x, y, color=cm(norm(z)))

# draw the colorbar, note that we pass explicitly the ScalarMappable
plt.colorbar(sm)

# I'm done, I'll show the results,
# you probably want to add labels to the axes and the colorbar.
plt.show()