To create a heatmap in Python that ranges from green to red, we can take the following steps −
- Set the figure size and adjust the padding between and around the subplots.
- Make a dictionary for different colors.
- Create a colormap from linear mapping segments using LinearSegmentedColormap.
- Create a figure and a set of subplots.
- Create random data with 5☓5 dimension.
- Create a pseudocolor plot with a non-regular rectangular grid.
- Create a colorbar for a ScalarMappable instance, *mappable*.
- To display the figure, use show() method.
Example
import matplotlib.pyplot as plt import matplotlib.colors as colors import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True cdict = {'red': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 0.7)), 'green': ((0.0, 0.7, 0.7), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)) } GnRd = colors.LinearSegmentedColormap('GnRd', cdict) fig, ax = plt.subplots(1) data = np.random.rand(5, 5)*6.-3. p = ax.pcolormesh(data, cmap=GnRd, vmin=-5, vmax=5) fig.colorbar(p, ax=ax) plt.show()