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
Selected Reading
How to plot contourf and log color scale in Matplotlib?
In Matplotlib, you can create contour plots with logarithmic color scaling using contourf() combined with LogLocator(). This is particularly useful when your data spans several orders of magnitude.
Basic Setup
First, let's understand the key components needed for logarithmic contour plots ?
- Use
contourf()method for filled contour plots - Apply
ticker.LogLocator()for logarithmic color scale - Handle negative or zero values with masked arrays
- Add a colorbar to visualize the scale
Example
Here's how to create a contour plot with logarithmic color scaling ?
import matplotlib.pyplot as plt import numpy as np from numpy import ma from matplotlib import ticker, cm # Set figure properties plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create sample data N = 100 x = np.linspace(-3.0, 3.0, N) y = np.linspace(-2.0, 2.0, N) X, Y = np.meshgrid(x, y) # Generate exponential data with different scales Z1 = np.exp(-X**2 - Y**2) Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2) # Combine data with large range z = Z1 + 50 * Z2 # Mask negative/zero values for log scale z[:5, :5] = -1 z = ma.masked_where(z <= 0, z) # Create contour plot with log scale fig, ax = plt.subplots() cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.PuBu_r) cbar = fig.colorbar(cs) plt.show()
Key Components
Understanding the important parameters ?
| Parameter | Purpose | Example |
|---|---|---|
locator |
Sets tick positions | ticker.LogLocator() |
cmap |
Color mapping | cm.PuBu_r |
ma.masked_where |
Handle invalid values | z |
How It Works
The logarithmic scaling works by ?
- LogLocator() automatically determines appropriate logarithmic intervals
- Masked arrays exclude negative or zero values that can't be log-scaled
- Colorbar displays the logarithmic scale for easy interpretation
- Color mapping distributes colors evenly across log intervals
Conclusion
Use contourf() with ticker.LogLocator() to create contour plots with logarithmic color scaling. Always mask negative or zero values when using log scales, and include a colorbar for proper interpretation.
Advertisements
