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 use ax.get_ylim() in matplotlib?
The ax.get_ylim() method in matplotlib returns the current y-axis limits as a tuple containing the minimum and maximum values. This is useful for understanding the current scale of your plot or for programmatically adjusting other plot elements based on the y-axis range.
Syntax
ax.get_ylim()
Return Value
Returns a tuple (ymin, ymax) representing the current y-axis limits.
Basic Example
Here's how to use ax.get_ylim() to retrieve the y-axis limits ?
import numpy as np
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create figure and axis
fig, ax = plt.subplots()
# Create random data points
y = np.random.rand(10)
# Plot the data points
ax.plot(y, 'b-', marker='o')
# Get and print the y-axis limits
ylimits = ax.get_ylim()
print("Y-axis limits:", ylimits)
print(f"Minimum y-value: {ylimits[0]:.3f}")
print(f"Maximum y-value: {ylimits[1]:.3f}")
plt.title('Random Data Plot')
plt.show()
Y-axis limits: (-0.05, 1.05) Minimum y-value: -0.050 Maximum y-value: 1.050
Practical Use Case
You can use get_ylim() to add annotations or elements relative to the current axis limits ?
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
x = np.linspace(0, 10, 50)
y = np.sin(x) * np.exp(-x/10)
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, y, 'b-', linewidth=2)
# Get current y-limits
ymin, ymax = ax.get_ylim()
# Add a horizontal line at 80% of the y-range
threshold = ymin + 0.8 * (ymax - ymin)
ax.axhline(y=threshold, color='red', linestyle='--', alpha=0.7)
# Add text annotation using the limits
ax.text(5, threshold + 0.05, f'80% threshold: {threshold:.2f}',
ha='center', va='bottom', color='red')
print(f"Current y-limits: {ymin:.3f} to {ymax:.3f}")
print(f"Y-range span: {ymax - ymin:.3f}")
plt.title('Using get_ylim() for Annotations')
plt.grid(True, alpha=0.3)
plt.show()
Current y-limits: -0.105 to 1.050 Y-range span: 1.155
Comparison with set_ylim()
| Method | Purpose | Returns |
|---|---|---|
get_ylim() |
Retrieve current y-axis limits | Tuple (ymin, ymax) |
set_ylim() |
Set new y-axis limits | Tuple of new limits |
Conclusion
The ax.get_ylim() method is essential for retrieving current y-axis limits in matplotlib. Use it to understand your plot's scale or to programmatically position elements relative to the current axis range.
Advertisements
