Tag Archives: programming

How to apply gradient color to matplotlib graphs with colormap?

Matplotlib in python offers some useful tools for plotting with gradient colors. Below is a script that plot a sine wave with gradient color based on its y-value. It shows the use of matplotlib.cm.get_cmap to obtain a color map and the use of matplotlib.colors.Normalize to convert a value to the gradient index used for cmap.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import Normalize


X = np.linspace(0, 10, 101)
Y = 10*np.sin(x)

cmap = cm.get_cmap('Blues', len(y))
norm = Normalize(vmin=np.min(Y),vmax=np.max(Y))

for i in range(len(X)-1):
    plt.plot(X[i:i+2], Y[i:i+2], color=cmap(norm(Y[i])))

plt.legend()
plt.grid()
plt.xlabel("x")
plt.ylabel("y")

A more comprehensive list of colormaps can be found in the matplotlib site: https://matplotlib.org/3.3.2/tutorials/colors/colormaps.html