How to reverse a Colormap using Matplotlib in Python?

How to reverse a Colormap using Matplotlib in Python?

Reversing a colormap in Matplotlib is straightforward. To get the reversed version of any colormap, simply append '_r' to its name.

Here's how you can reverse a colormap and demonstrate it using an example:

  • Import Necessary Libraries:
import numpy as np import matplotlib.pyplot as plt 
  • Demonstrate Original and Reversed Colormap:

Let's use the viridis colormap as an example:

# Create sample data data = np.random.random((10, 10)) # Plot using the original 'viridis' colormap plt.subplot(1, 2, 1) plt.imshow(data, cmap='viridis') plt.title('Original viridis') plt.colorbar() # Plot using the reversed 'viridis' colormap plt.subplot(1, 2, 2) plt.imshow(data, cmap='viridis_r') # Notice the '_r' plt.title('Reversed viridis') plt.colorbar() plt.tight_layout() plt.show() 

In the example above, by appending _r to viridis, you can access the reversed version of the viridis colormap. This approach works with other built-in colormaps in Matplotlib as well.


More Tags

virtual-memory asp.net-mvc-5 large-title relationship amazon-redshift watch wsgi vmware-workstation organization azure-redis-cache

More Programming Guides

Other Guides

More Programming Examples