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
Adjust one subplot's height in absolute way (not relative) in Matplotlib
When creating subplots in Matplotlib, you sometimes need precise control over their positioning and dimensions. The Axes() class allows you to specify absolute positions and sizes instead of using relative grid layouts.
Understanding Axes Parameters
The Axes() class takes parameters [left, bottom, width, height] where all values are in figure coordinates (0 to 1) ?
- left − horizontal position of the left edge
- bottom − vertical position of the bottom edge
- width − width of the subplot
- height − height of the subplot
Example
Here's how to create two subplots with different absolute heights ?
import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 4.50] plt.rcParams["figure.autolayout"] = True figure = plt.figure() # First subplot: positioned at [0.4, 0.6] with size [0.25, 0.25] axes1 = plt.Axes(figure, [0.4, 0.6, 0.25, 0.25]) figure.add_axes(axes1) plt.plot([1, 2, 3, 4], [1, 2, 3, 4]) # Second subplot: positioned at [0.4, 0.1] with size [0.25, 0.25] axes2 = plt.Axes(figure, [0.4, 0.1, 0.25, 0.25]) figure.add_axes(axes2) plt.plot([1, 2, 3, 4], [1, 2, 3, 4]) plt.show()
Creating Subplots with Different Heights
To demonstrate absolute height control, let's create subplots with different heights ?
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 6))
# Tall subplot on the left
tall_axes = plt.Axes(fig, [0.1, 0.1, 0.3, 0.8]) # height = 0.8
fig.add_axes(tall_axes)
tall_axes.plot([1, 2, 3], [1, 4, 2], 'b-', linewidth=2)
tall_axes.set_title('Tall Subplot')
# Short subplot on the right
short_axes = plt.Axes(fig, [0.6, 0.3, 0.3, 0.4]) # height = 0.4
fig.add_axes(short_axes)
short_axes.plot([1, 2, 3], [3, 1, 4], 'r-', linewidth=2)
short_axes.set_title('Short Subplot')
plt.show()
Comparison with subplot()
| Method | Control Type | Best For |
|---|---|---|
subplot() |
Grid−based | Regular layouts |
Axes() |
Absolute positioning | Custom layouts |
subplot2grid() |
Flexible grid | Complex grids |
Conclusion
Use plt.Axes() with [left, bottom, width, height] parameters for absolute control over subplot positioning and dimensions. This method provides precise layout control when standard grid layouts aren't sufficient.
