Matplotlib - Setting Limits
Matplotlib - Setting Axis Limits
Section titled “Matplotlib - Setting Axis Limits”By default, Matplotlib automatically determines the range (limits) of the x and y axes to encompass all the data points being plotted. However, you often need to set these limits manually for better control over the visualization, such as focusing on a specific region or ensuring consistency across multiple plots.
Using set_xlim() and set_ylim()
Section titled “Using set_xlim() and set_ylim()”The primary methods for setting axis limits in the object-oriented API are ax.set_xlim() and ax.set_ylim(), called on an Axes object (ax).
ax.set_xlim(left, right): Sets the minimum (left) and maximum (right) values for the x-axis.ax.set_ylim(bottom, top): Sets the minimum (bottom) and maximum (top) values for the y-axis.
You can also pass a tuple or list: ax.set_xlim((left, right)).
To set only one limit, you can use None or omit the argument for the limit you want Matplotlib to autoscale (e.g., ax.set_xlim(left=0) sets the minimum x-limit to 0, letting the maximum be determined automatically).
Example: Autoscaled vs. Manual Limits
Section titled “Example: Autoscaled vs. Manual Limits”Let’s plot an exponential function and see how setting limits changes the view.
import matplotlib.pyplot as pltimport numpy as np
# Datax = np.arange(1, 10)y = np.exp(x)
# --- Plot 1: Autoscaled Limits ---fig1, ax1 = plt.subplots(figsize=(6, 4))ax1.plot(x, y, 'bo-')ax1.set_title('Exponential Plot (Autoscaled Limits)')ax1.set_xlabel('x')ax1.set_ylabel('exp(x)')ax1.grid(True)print(f"Autoscaled X limits: {ax1.get_xlim()}")print(f"Autoscaled Y limits: {ax1.get_ylim()}")
# --- Plot 2: Manually Set Limits ---fig2, ax2 = plt.subplots(figsize=(6, 4))ax2.plot(x, y, 'rs--')ax2.set_title('Exponential Plot (Manual Limits)')ax2.set_xlabel('x')ax2.set_ylabel('exp(x)')
# Set specific limitsax2.set_xlim(0, 12) # Extend x-axis beyond data rangeax2.set_ylim(-1000, 10000) # Set y-axis range, starting below zero
ax2.grid(True)print(f"Manual X limits: {ax2.get_xlim()}")print(f"Manual Y limits: {ax2.get_ylim()}")
plt.show() # Show both figuresRunning this code will produce two plots:
- The first plot (‘Autoscaled Limits’) will have axes tightly fitted around the data points (approximately x from 1 to 9, y from near 0 to over 8000).
- The second plot (‘Manual Limits’) will show the same data, but the x-axis will range from 0 to 12 and the y-axis from -1000 to 10000. This provides more context or focuses the view according to specific requirements.
Using axis()
Section titled “Using axis()”The ax.axis() method provides a convenient way to get or set axis properties, including limits.
ax.axis(): Returns the current limits(xmin, xmax, ymin, ymax).ax.axis([xmin, xmax, ymin, ymax]): Sets all four limits at once.ax.axis('tight'): Sets limits tightly around the data.ax.axis('equal'): Sets aspect ratio to 1:1 and adjusts limits accordingly.ax.axis('scaled'): Sets aspect ratio to 1:1 by changing figure dimensions.ax.axis('off'): Turns off the axis lines and labels.
# Example using axis()fig, ax = plt.subplots()ax.plot(x, y, 'gd:')ax.set_title('Using ax.axis()')
# Set limits using axis()ax.axis([0, 15, 0, 12000])
ax.grid(True)plt.show()Setting axis limits is a fundamental technique for controlling the presentation of your data visualizations in Matplotlib.