How to reverse the colormap of an image to scalar values in Matplotib?

To reverse the colormap of an image in Matplotlib, you can use the .reversed() method on any colormap object. This creates a new colormap with inverted colors, which is useful for changing the visual emphasis or meeting specific design requirements.

Steps to Reverse a Colormap

  • Set the figure size and adjust the padding between and around the subplots
  • Create data points using numpy arrays
  • Get the desired colormap using plt.cm.get_cmap() method
  • Create subplots to compare original and reversed colormaps
  • Plot data points using scatter() method with original colormap
  • Plot the same data with reversed colormap using .reversed() method
  • Add colorbars and titles for comparison
  • Display the figure using show() method

Example

Here's a complete example showing how to reverse a colormap ?

import matplotlib.pyplot as plt
import numpy as np

# Set figure size and layout
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create sample data
x = np.linspace(-2, 2, 10)
y = np.linspace(-2, 2, 10)

# Get the Blues colormap
color_map = plt.cm.get_cmap('Blues')

# Create first subplot with original colormap
plt.subplot(1, 2, 1)
sc = plt.scatter(x, y, c=x, cmap=color_map)
plt.colorbar(sc)
plt.title("Original Colormap")

# Create second subplot with reversed colormap
plt.subplot(1, 2, 2)
sc = plt.scatter(x, y, c=x, cmap=color_map.reversed())
plt.colorbar(sc)
plt.title("Reversed Colormap")

plt.show()

Output

The output shows two scatter plots side by side. The left plot uses the original 'Blues' colormap (light to dark blue), while the right plot uses the reversed colormap (dark to light blue).

Original Colormap Reversed Colormap

Alternative Methods

You can also reverse colormaps using the suffix '_r' ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
data = np.random.rand(10, 10)

# Method 1: Using .reversed()
plt.subplot(1, 2, 1)
plt.imshow(data, cmap=plt.cm.viridis.reversed())
plt.title("Using .reversed()")
plt.colorbar()

# Method 2: Using '_r' suffix
plt.subplot(1, 2, 2)
plt.imshow(data, cmap='viridis_r')
plt.title("Using '_r' suffix")
plt.colorbar()

plt.tight_layout()
plt.show()

Key Points

  • Use .reversed() method on any colormap object to create its inverse
  • Alternatively, add '_r' suffix to colormap names (e.g., 'Blues_r')
  • Reversed colormaps are useful for changing visual emphasis in plots
  • Both methods produce identical results

Conclusion

Reversing colormaps in Matplotlib is straightforward using either the .reversed() method or the '_r' suffix. This technique helps create better visual contrast and emphasis in your data visualizations.

Updated on: 2026-03-25T22:41:02+05:30

667 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements