By default, Matplotlib does a reasonable job of setting the axis ranges to encompass your data. However, there are many situations where you'll want to manually control these limits. You might want to:
Matplotlib provides simple functions to adjust the limits of the x-axis and y-axis.
xlim
and ylim
The primary way to set axis limits depends on whether you are using the pyplot
interface directly or the object-oriented approach with Axes
objects.
1. The pyplot
Interface
If you are creating simple plots using functions directly from matplotlib.pyplot
(often imported as plt
), you can use plt.xlim()
and plt.ylim()
.
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave - Default Limits")
plt.xlabel("X value")
plt.ylabel("sin(X)")
plt.show() # Display the plot with default limits
# Now, set specific limits
plt.plot(x, y)
plt.title("Sine Wave - Custom Limits")
plt.xlabel("X value")
plt.ylabel("sin(X)")
# Set x-axis limits from 2 to 8
plt.xlim(2, 8)
# Set y-axis limits from -0.5 to 0.5
plt.ylim(-0.5, 0.5)
plt.show() # Display the plot with custom limits
The plt.xlim()
and plt.ylim()
functions each take two arguments: the minimum and maximum desired limits for the respective axis.
2. The Object-Oriented Interface
As discussed in the "Anatomy of a Matplotlib Plot" section, using the object-oriented approach gives you more control, especially with multiple subplots. When you have an Axes
object (commonly named ax
), you use its methods: ax.set_xlim()
and ax.set_ylim()
.
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y = np.cos(x) # Using cosine this time
# Create figure and axes objects
fig, ax = plt.subplots()
# Plot data on the axes
ax.plot(x, y)
ax.set_title("Cosine Wave - Custom Limits (OO)")
ax.set_xlabel("X value")
ax.set_ylabel("cos(X)")
# Set x-axis limits from 0 to 5
ax.set_xlim(0, 5)
# Set y-axis limits from -1 to 0
ax.set_ylim(-1, 0)
plt.show()
This approach is generally recommended as it's more explicit and scales better to more complex visualizations. The arguments work the same way as the pyplot
versions.
Sometimes, you might only want to adjust the minimum or maximum limit, letting Matplotlib determine the other automatically. You can achieve this by passing None
for the limit you want to keep automatic, or by using keyword arguments.
Using None
:
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(50) * 10
y = np.random.rand(50) * 5
fig, ax = plt.subplots()
ax.scatter(x, y)
ax.set_title("Scatter Plot - Adjusted Lower Limits")
ax.set_xlabel("Random X")
ax.set_ylabel("Random Y")
# Set only the lower bound for x-axis (minimum x is 0)
ax.set_xlim(0, None) # Or ax.set_xlim(left=0)
# Set only the lower bound for y-axis (minimum y is 1)
ax.set_ylim(bottom=1) # Or ax.set_ylim(1, None)
plt.show()
Using keyword arguments (left
, right
, bottom
, top
):
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(50) * 10
y = np.random.rand(50) * 5
fig, ax = plt.subplots()
ax.scatter(x, y)
ax.set_title("Scatter Plot - Adjusted Upper Limits")
ax.set_xlabel("Random X")
ax.set_ylabel("Random Y")
# Set only the upper bound for x-axis (maximum x is 8)
ax.set_xlim(right=8)
# Set only the upper bound for y-axis (maximum y is 4)
ax.set_ylim(top=4)
plt.show()
Let's visualize how setting axis limits can help focus on a specific part of the data. We'll plot some data that has a concentration in one area and use set_xlim
and set_ylim
to zoom in.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd # Using pandas for easier data handling
# Generate some data with a denser cluster
np.random.seed(42) # for reproducibility
data = pd.DataFrame({
'x': np.random.normal(loc=5, scale=2, size=200),
'y': np.random.normal(loc=3, scale=1, size=200)
})
# Add some sparse points further out
data = pd.concat([data, pd.DataFrame({
'x': np.random.uniform(-5, 15, 20),
'y': np.random.uniform(-2, 8, 20)
})], ignore_index=True)
# --- Plot 1: Default Limits ---
fig1, ax1 = plt.subplots(figsize=(6, 4))
ax1.scatter(data['x'], data['y'], alpha=0.6, color='#228be6') # Blue color
ax1.set_title("Data with Default Axis Limits")
ax1.set_xlabel("Feature X")
ax1.set_ylabel("Feature Y")
ax1.grid(True, linestyle='--', alpha=0.5)
plt.show()
# --- Plot 2: Custom Limits ---
fig2, ax2 = plt.subplots(figsize=(6, 4))
ax2.scatter(data['x'], data['y'], alpha=0.6, color='#228be6') # Blue color
ax2.set_title("Data Focused with Custom Limits")
ax2.set_xlabel("Feature X")
ax2.set_ylabel("Feature Y")
# Set limits to focus on the main cluster around x=5, y=3
ax2.set_xlim(0, 10)
ax2.set_ylim(0, 6)
ax2.grid(True, linestyle='--', alpha=0.5)
plt.show()
# --- Interactive Plotly Version ---
# (Shows the effect dynamically, though not directly executable here)
# This JSON represents the second plot (focused)
```plotly
{"layout": {"title": "Data Focused with Custom Limits (Plotly)", "xaxis": {"title": "Feature X", "range": [0, 10], "gridcolor": "#dee2e6"}, "yaxis": {"title": "Feature Y", "range": [0, 6], "gridcolor": "#dee2e6"}, "width": 600, "height": 400, "plot_bgcolor": "#e9ecef"}, "data": [{"type": "scatter", "mode": "markers", "x": [5.99342831, 4.7234714, 5.29537708, 7.04605971, 3.53169325, 5.53178596, 5.88193508, 4.73106404, 4.67904912, 3.1129166, 5.15443918, 3.73796791, 4.41137694, 3.89192033, 5.30875361, 6.07371768, 2.9903949, 6.15729178, 5.18807565, 5.19967068, 3.47603678, 5.17939696, 2.86186388, 3.37494904, 6.31116861, 3.08974181, 4.96868498, 6.44724269, 4.40152448, 3.33313626, 4.06413627, 6.2114819, 3.40800185, 5.76103768, 6.23129146, 5.46007955, 5.44128025, 6.32969017, 3.57759154, 3.07656328, 5.02333502, 7.00475885, 6.21870665, 4.02990718, 5.19598151, 4.93057701, 2.56752764, 3.80027069, 4.62414199, 5.45919274, 2.94948242, 7.71158868, 3.42573621, 7.9322453, 6.1987419, 2.53543463, 3.82278924, 4.23064537, 6.33126328, 5.6833387, 5.36415735, 5.30629247, 3.03136103, 3.80044622, 4.54288611, 6.24660957, 6.14677797, 6.38478059, 3.31508899, 5.26495647, 5.41605859, 5.18461864, 4.22907593, 5.3172371, 5.83898644, 5.51669339, 4.39317192, 4.6116638, 5.75667008, 4.50781731, 2.20375605, 4.36759876, 4.88962333, 5.30392731, 4.92317364, 4.74515108, 7.02684599, 5.28114768, 4.8219325, 5.7048188, 6.11509506, 2.95546685, 4.24919914, 2.85729161, 3.91515227, 4.80378575, 5.05445153, 6.37316539, 5.88448027, 6.65884813, 4.81836102, 3.84347076, 4.61057746, 4.01604999, 3.83041876, 2.21704911, 5.94883436, 7.38314519, 5.08625671, 6.33463028, 4.5134659, 5.45920396, 4.59389813, 4.15854653, 5.61721678, 3.38644216, 5.26777027, 4.23377341, 7.85446908, 6.02220342, 4.26903219, 4.65607024, 2.48462532, 3.1543206, 5.29584324, 6.05542407, 6.99834276, 4.35921964, 4.74826596, 4.08606821, 3.0065799, 4.96583696, 4.9427689, 7.68897174, 5.86605737, 6.34930996, 2.00103307, 5.9749268, 3.83767966, 5.01875477, 5.3218687, 7.40712306, 4.41588695, 3.3965872, 5.05865075, 4.14241682, 5.03946585, 4.89912807, 3.38922787, 3.79301851, 2.21521497, 4.74672081, 5.30029186, 4.4403457, 5.18014435, 3.98927397, 7.31719726, 4.52615615, 5.43588608, 5.18706783, 5.54913716, 3.91256357, 4.58784245, 7.33256269, 4.87834265, 3.11069516, 5.95309955, 5.36223027, 3.20420008, 5.52994169, 2.86200514, 5.87450577, 4.08791362, 5.65019723, 7.75618655, 5.12622647, 3.76590953, 6.96342985, 4.94736567, 3.01605378, 7.12971742, 4.11322524, 5.13187434, 4.60168775, 7.01912021, 2.76351486, 2.13726149, 3.37387813, 3.89389036, 4.34267421, 3.51175597, 6.76778929, 3.51450354, 4.81894493, 7.17438023, 8.1211046, -4.64509123, -1.89343733, 13.3285109, 7.01487776, 8.4577438, 13.12138685, 13.06002212, 7.60516572, -3.89582248, 12.98003844, 1.23556089, 13.14776349, 11.83862029, -3.1083832, -3.5846578, 7.8735861, 14.43067622, 13.45166577, -4.3077043], "y": [2.99671423, 2.8617357, 3.64768854, 4.52302986, 2.76584663, 3.8858043, 3.83182732, 3.71632721, 3.33902766, 1.7327034, 3.07921276, 2.82486138, 3.36139582, 2.60932368, 3.69998546, 4.14882551, 2.19471129, 3.61828103, 3.2620926, 3.06446313, 2.82471867, 3.61649116, 2.46604413, 2.61673671, 3.75677219, 2.02641135, 3.1940303, 3.85089451, 2.70285945, 2.35639622, 2.77648717, 4.30018695, 2.35700329, 3.38594174, 3.9439049, 3.42763149, 3.55456096, 3.6331307, 2.70219197, 2.39762741, 3.24279199, 4.49806555, 4.06833808, 2.85658619, 3.28028166, 3.13209186, 1.90994304, 2.81007358, 3.06512335, 3.60034199, 2.16988391, 4.82522215, 2.6220075, 5.03542948, 3.81791827, 2.16172491, 2.89028059, 3.02728516, 4.03037102, 3.74345408, 3.66013937, 3.62846034, 2.29300413, 2.85566789, 3.25314452, 4.08217935, 4.02998815, 4.14555791, 2.5374788, 3.5873595, 3.72074093, 3.46576947, 2.98973041, 3.63804066, 3.90599091, 3.68475353, 2.95507178, 3.04707562, 3.86759482, 3.12115692, 1.65142368, 3.04046566, 3.37506503, 3.61136504, 3.32270932, 3.21006127, 4.55240113, 3.57480866, 3.25674793, 3.75171872, 3.95847457, 2.21485664, 3.01261749, 2.43455117, 2.86263509, 3.28022253, 3.40040893, 4.11062082, 3.90781253, 4.33703431, 3.27558396, 2.80243469, 3.16414065, 2.88689791, 2.80922924, 1.72453091, 3.96958335, 4.69670742, 3.41615714, 4.11164715, 3.07209557, 3.6536325, 3.08956666, 2.93304939, 3.70019193, 2.43021578, 3.5846021, 2.98488734, 4.96339057, 3.93970104, 2.99243413, 3.16969176, 1.91077529, 2.35292758, 3.58560264, 4.01249744, 4.49810307, 3.0259879, 3.21735184, 2.92537723, 2.24020143, 3.35297525, 3.33406348, 4.85335569, 3.89555497, 4.08801402, 1.60277109, 3.97963167, 2.79208358, 3.38110453, 3.60180289, 4.69698797, 3.03441102, 2.45036875, 3.39908167, 2.93891534, 3.39146328, 3.33406865, 2.4807182, 2.82710693, 1.77081884, 3.21011504, 3.60199328, 3.02757869, 3.48460469, 2.88213526, 4.64249243, 3.10075328, 3.68603027, 3.49782787, 3.7223756, 2.84576392, 3.13718257, 4.6563391, 3.34337932, 2.33054697, 3.96572785, 3.64602858, 2.37908052, 3.7062429, 2.43939233, 3.90639413, 2.92001477, 3.73980622, 4.8743766, 3.4607109, 2.78294593, 4.47400114, 3.34642603, 2.26461219, 4.55102355, 2.91660423, 3.45958134, 3.12379175, 4.49726814, 2.0485717, 1.72467339, 2.46815372, 2.84832245, 3.04930952, 2.63595258, 4.32918818, 2.63831377, 3.28429744, 4.57652829, -0.95023271, 2.70335848, -1.01469935, 3.73287184, -0.11605978, 7.82433383, 3.65875152, 6.44532446, -0.72200027, 4.11801331, 2.75295421, -0.11895329, 7.16958735, 0.7027769, 1.1314149, 5.50408347, 3.75467174, 5.8933783, 1.47469572], "marker": {"color": "#228be6", "opacity": 0.6}}]}
Scatter plot showing the data distribution. The plot on the right uses
set_xlim(0, 10)
andset_ylim(0, 6)
to zoom in on the denser region compared to the default view on the left (represented by the code generatingfig1
).
Setting axis limits is a fundamental technique for refining your plots, making them clearer, more focused, and better suited for comparison or presentation. You'll find yourself using set_xlim
and set_ylim
frequently as you create more sophisticated visualizations.
© 2025 ApX Machine Learning