如何使多条线的颜色随渐变色对应的值变化?

How to make multiple lines' color changing with values corresponding to gradient color?

我有几千行,每行的值都在 0 到 1 之间,与一个特征相关。我要做的是画出这些线条,同时用颜色显示它们的特征。也就是说,如果线条值为 0.5,那么我希望这条线具有颜色条的中间颜色。我如何构建此代码?下面是一个例子。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(111)

x = np.linspace(0, 1, 100)
b_range=np.linspace(0, 1, 5)

for j in range(len(b_range)):
    b=b_range[j]
t=b+(1-b)*(1-x)/(1-0)   
ax.plot(x, t,color="red")


plt.show()

你可以自己改,用一个Color变量控制下一个颜色

这是一个例子

import numpy as np
import matplotlib.pyplot as plt


def format_axes(ax):
    ax.margins(0.2)
    ax.set_axis_off()

points = np.ones(5)  # Draw 5 points for each line
text_style = dict(horizontalalignment='right', verticalalignment='center',
                  fontsize=12, fontdict={'family': 'monospace'})
COLOR = (0, 0, 0.1)

def color_conv(color_range):
    return (COLOR[0] + color_range, COLOR[1], COLOR[2]) 

# Plot all line styles.
fig, ax = plt.subplots()

for color_ite in range(10):   
    ax.text(-0.1, color_ite, '-', **text_style)
    ax.plot(color_ite * points, color=color_conv(color_ite/10), linewidth=3)
    format_axes(ax)
    ax.set_title('line styles')

plt.show()

输出:

使用cmap中的色图:

import numpy as np

from matplotlib import pyplot as plt
from matplotlib import colors

fig, ax = plt.subplots(figsize=(6, 6))

cdict = {'red':   ((0.0,  0.22, 0.0),
                   (0.5,  1.0, 1.0),
                   (1.0,  0.89, 1.0)),

         'green': ((0.0,  0.49, 0.0),
                   (0.5,  1.0, 1.0),
                   (1.0,  0.12, 1.0)),

         'blue':  ((0.0,  0.72, 0.0),
                   (0.5,  0.0, 0.0),
                   (1.0,  0.11, 1.0))}

cmap = colors.LinearSegmentedColormap('custom', cdict)

for i in np.linspace(0, 1):
    # Plot 50 lines, from y = 0 to y = 1, taking a corresponding value from the cmap
    ax.plot([-1, 1], [i, i], c=cmap(i))

完整的彩色地图列表可用 here