Search code examples
pythonmatplotlibcolorsline

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


I have thousands of lines, and each of them with a value between 0 and 1 related to a feature. What I want to do is to draw these lines and at the same time to show their feature by color. That is if a lines value is 0.5, then I want this line have the middle color of a colorbar. How can I build this code? The following is an example.

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()

Solution

  • Use the colour maps in 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))
    

    enter image description here

    A full list of colour maps is available here.