Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create a heat map in Python that ranges from green to red? (Matplotlib)
Creating a heatmap with a green-to-red color scheme is useful for visualizing data where values transition from one extreme to another. Python's Matplotlib provides LinearSegmentedColormap to create custom color gradients.
Understanding LinearSegmentedColormap
The LinearSegmentedColormap creates smooth color transitions by defining RGB values at specific points. Each color channel (red, green, blue) is defined as a tuple containing position and color intensity values.
Creating a Custom Green-to-Red Colormap
Here's how to create a heatmap that transitions from green to red ?
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
# Set figure parameters
plt.rcParams["figure.figsize"] = [8, 4]
plt.rcParams["figure.autolayout"] = True
# Define custom colormap dictionary
cdict = {'red': ((0.0, 0.0, 0.0), # Start: no red (green)
(0.5, 1.0, 1.0), # Middle: full red (yellow)
(1.0, 1.0, 0.7)), # End: mostly red
'green': ((0.0, 0.7, 0.7), # Start: high green
(0.5, 1.0, 1.0), # Middle: full green (yellow)
(1.0, 0.0, 0.0)), # End: no green (red)
'blue': ((0.0, 0.0, 0.0), # Start: no blue
(0.5, 1.0, 1.0), # Middle: some blue
(1.0, 0.0, 0.0)) # End: no blue
}
# Create custom colormap
GnRd = colors.LinearSegmentedColormap('GnRd', cdict)
# Create sample data
data = np.random.rand(6, 6) * 10 - 5 # Random values between -5 and 5
# Create heatmap
fig, ax = plt.subplots()
p = ax.pcolormesh(data, cmap=GnRd, vmin=-5, vmax=5)
# Add colorbar and labels
fig.colorbar(p, ax=ax, label='Value')
ax.set_title('Custom Green-to-Red Heatmap')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
plt.show()
Using Built-in Red-Green Colormap
Matplotlib also provides built-in colormaps for similar effects ?
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
data = np.random.rand(5, 5) * 10 - 5
# Create heatmap with built-in RdYlGn colormap (reversed)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
# Using RdYlGn_r (reversed Red-Yellow-Green)
im1 = ax1.imshow(data, cmap='RdYlGn_r', vmin=-5, vmax=5)
ax1.set_title('Built-in RdYlGn_r Colormap')
plt.colorbar(im1, ax=ax1)
# Using RdGn colormap
im2 = ax2.imshow(data, cmap='RdGn', vmin=-5, vmax=5)
ax2.set_title('Built-in RdGn Colormap')
plt.colorbar(im2, ax=ax2)
plt.tight_layout()
plt.show()
Comparison of Approaches
| Method | Flexibility | Ease of Use | Best For |
|---|---|---|---|
| Custom LinearSegmentedColormap | High | Medium | Precise color control |
| Built-in RdYlGn_r | Low | High | Quick visualization |
| Built-in RdGn | Low | High | Standard red-green transition |
Key Parameters
-
vminandvmax? Define the range of values for color mapping -
cmap? Specifies the colormap to use -
pcolormesh()? Creates pseudocolor plots with irregular grids -
imshow()? Displays data as an image with regular grids
Conclusion
Use LinearSegmentedColormap for custom green-to-red transitions with precise control. For quick visualizations, built-in colormaps like RdYlGn_r provide ready-to-use solutions.
