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 unset 'sharex' or 'sharey' from two axes in Matplotlib?
When creating multiple subplots in Matplotlib, you might want each subplot to have independent X and Y axes instead of sharing them. You can unset sharex and sharey by setting them to 'none' or False.
Basic Syntax
To create subplots without shared axes ?
fig, axes = plt.subplots(rows, cols, sharex='none', sharey='none') # or fig, axes = plt.subplots(rows, cols, sharex=False, sharey=False)
Example with Independent Axes
Let's create a 2x4 grid of subplots where each has independent X and Y axes ?
import matplotlib.pyplot as plt
import numpy as np
# Set figure size
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
# Define grid dimensions
rows = 2
cols = 4
# Create subplots with no shared axes
fig, axes = plt.subplots(rows, cols, sharex='none', sharey='none', squeeze=False)
# Plot different data on each subplot
for row in range(rows):
for col in range(cols):
# Generate different random data for each subplot
x_data = np.random.rand(10) * (col + 1)
y_data = np.random.rand(10) * (row + 1)
axes[row][col].plot(x_data, y_data, marker='o')
axes[row][col].set_title(f'Subplot ({row},{col})')
plt.tight_layout()
plt.show()
Comparison of Sharing Options
| Parameter Value | Behavior | Use Case |
|---|---|---|
'none' or False
|
Each subplot has independent axes | Different data ranges per subplot |
'all' or True
|
All subplots share the same axis | Comparing data with same scale |
'row' |
Subplots in same row share axis | Comparing across columns |
'col' |
Subplots in same column share axis | Comparing across rows |
Practical Example with Different Data Ranges
Here's why independent axes are useful when plotting data with different scales ?
import matplotlib.pyplot as plt
import numpy as np
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), sharex=False, sharey=False)
# First subplot: small values
x1 = np.linspace(0, 1, 100)
y1 = np.sin(2 * np.pi * x1)
ax1.plot(x1, y1)
ax1.set_title('Small Scale Data')
ax1.set_xlabel('X (0-1)')
ax1.set_ylabel('Y (-1 to 1)')
# Second subplot: large values
x2 = np.linspace(0, 1000, 100)
y2 = x2**2
ax2.plot(x2, y2)
ax2.set_title('Large Scale Data')
ax2.set_xlabel('X (0-1000)')
ax2.set_ylabel('Y (0-1M)')
plt.tight_layout()
plt.show()
Conclusion
Use sharex='none' and sharey='none' when each subplot needs independent axis scaling. This is essential when plotting data with different ranges or units across subplots.
Advertisements
