Search code examples
pythonmatplotlibcolorbar

How to apply normalized colorbar to a figure with iterative line plots


I have normalized the color bar according to my data

import matplotlib as mpl
fig,ax=plt.subplots(figsize=(6,1))
fig.subplots_adjust(bottom=0.5)
cmap=mpl.cm.jet
norm=mpl.colors.Normalize(vmin=np.min(epi_dist),vmax=np.max(epi_dist))
cb1=mpl.colorbar.ColorbarBase(ax,cmap=cmap,norm=norm,orientation='horizontal')
fig.show()

enter image description here

Now I need to plot multiple line plots through a for loop in a single figure with a variable representing the color according to this newly normalized colormap eg:

plt.plot(x,y,color=200,cmap='cmap')

here color represents the variable from data which represent the color according to the normalized cmap

Final figure will be like this with normalized colorbar if iterate the above code for multiple line plots enter image description here

Looking forward to your valuable suggestions


Solution

  • You can use color=cmap(norm(value)) to extract the desired color from the colormap corresponding to a value on the scale shown in the colorbar.

    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import numpy as np
    
    epi_dist = np.linspace(0, 420, 20)
    
    fig, (ax, cbar_ax) = plt.subplots(nrows=2, figsize=(10, 6), gridspec_kw={'height_ratios': [5, 1]})
    cmap = plt.cm.jet
    norm = plt.Normalize(vmin=np.min(epi_dist), vmax=np.max(epi_dist))
    cb1 = mpl.colorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norm, orientation='horizontal')
    
    x = np.linspace(0, 2 * np.pi, 200)
    for epi in epi_dist:
        ax.plot(x, epi + 100 * np.sin(x), color=cmap(norm(epi)))
    
    fig.show()
    

    example plot