Axis Limits in Matplotlib
Learn how to control the visible range of X and Y axes using Matplotlib. Understand axis limits, set minimum and maximum values, zoom into specific chart regions, and customize the plotting area.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand axis limits in Matplotlib.
- Control the minimum and maximum values of the X-axis.
- Control the minimum and maximum values of the Y-axis.
- Use
xlim()andylim()functions. - Set axis limits using the Object-Oriented API.
- Zoom into a specific region of a chart.
- Understand automatic and manual axis limits.
2. Introduction to Axis Limits
Axis limits define the minimum and maximum values visible on a chart. Every Matplotlib plot has an X-axis and a Y-axis. By default, Matplotlib automatically calculates suitable axis limits based on the supplied data.
Sometimes, the automatically selected range is not suitable for our requirements. We may want to focus on a particular section of the data or display a specific range of values. In such situations, we can manually set axis limits.
What are Axis Limits?
Axis limits determine the visible boundaries of a plotting area. The X-axis limits control the horizontal range, while the Y-axis limits control the vertical range.
The horizontal and vertical boundaries define the visible axis ranges.
3. Setting X-Axis Limits Using xlim()
The plt.xlim() function is used to set the minimum and maximum
values of the X-axis.
It accepts two arguments: the left limit and the right limit. Values outside this range will not be visible in the plotting area.
Syntax
plt.xlim(left, right)
Example: Set X-Axis Limits
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [10, 20, 15, 25, 30, 28, 35, 40, 38, 45]
plt.plot(x, y, marker="o")
plt.xlim(2, 8)
plt.title("X-Axis Limits")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
A line chart is displayed.
The visible X-axis starts at 2 and ends at 8.
Data points outside the selected X-axis range are not visible.
The Y-axis range is selected automatically.
The selected X-axis range is highlighted between 2 and 8.
xlim() when you want to focus on a specific
horizontal range without modifying the original dataset.
4. Setting Y-Axis Limits Using ylim()
The plt.ylim() function is used to control the minimum and maximum
values of the Y-axis.
It accepts two arguments: the bottom limit and the top limit. This allows us to control the visible vertical range of the chart.
Syntax
plt.ylim(bottom, top)
Example: Set Y-Axis Limits
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [10, 20, 15, 30, 25, 40, 35, 50]
plt.plot(x, y, marker="o", color="green")
plt.ylim(10, 40)
plt.title("Y-Axis Limits")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
A line chart is displayed with a green line.
The visible Y-axis starts at 10 and ends at 40.
Values below 10 and above 40 are outside the visible range.
The X-axis range is selected automatically.
The visible vertical range is restricted to the selected Y-axis limits.
5. Setting Both X-Axis and Y-Axis Limits
You can set both horizontal and vertical axis limits in the same chart. This provides complete control over the visible plotting region.
Example: Set Both Axis Limits
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
plt.plot(x, y, marker="o", color="purple")
plt.xlim(2, 8)
plt.ylim(10, 40)
plt.title("Custom X and Y Axis Limits")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
A purple line chart is displayed.
The X-axis range is restricted from 2 to 8.
The Y-axis range is restricted from 10 to 40.
Only the portion of the data inside the selected
plotting region is visible.
6. Setting Axis Limits Using the Object-Oriented API
Matplotlib also provides an Object-Oriented API for controlling axis limits. Instead of using pyplot functions, you can use methods on the Axes object.
The commonly used methods are set_xlim() and set_ylim().
| Pyplot Function | Axes Method | Purpose |
|---|---|---|
plt.xlim() |
ax.set_xlim() |
Set horizontal axis limits. |
plt.ylim() |
ax.set_ylim() |
Set vertical axis limits. |
Example: Using set_xlim() and set_ylim()
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [10, 20, 15, 25, 30, 35, 40, 45]
ax.plot(x, y, marker="o", color="blue")
ax.set_xlim(2, 7)
ax.set_ylim(10, 40)
ax.set_title("Axis Limits Using Axes Methods")
ax.set_xlabel("X Values")
ax.set_ylabel("Y Values")
plt.show()
Expected Output
A blue line chart is displayed.
The X-axis limits are set from 2 to 7.
The Y-axis limits are set from 10 to 40.
The chart is configured using the Axes object.
Additional Method: set()
You can also set both axis limits together using the Axes object's
set() method.
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [10, 20, 15, 30])
ax.set(
xlim=(1, 4),
ylim=(5, 35),
title="Setting Both Limits"
)
plt.show()
7. Getting Current Axis Limits
Sometimes you may need to check the current axis limits of an existing chart.
Matplotlib provides get_xlim() and get_ylim()
methods for this purpose.
Example: Retrieve Axis Limits
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
ax.plot(x, y)
ax.set_xlim(0, 6)
ax.set_ylim(0, 40)
print("X-axis limits:", ax.get_xlim())
print("Y-axis limits:", ax.get_ylim())
plt.show()
Expected Output
X-axis limits: (0.0, 6.0)
Y-axis limits: (0.0, 40.0)
The returned values are tuples containing the lower and upper limits of the corresponding axis.
8. Automatic and Manual Axis Limits
Matplotlib automatically calculates axis limits when you plot data. This is called automatic axis scaling.
When you manually specify axis limits using functions such as
plt.xlim() or ax.set_ylim(), you control
the visible range yourself.
| Automatic Limits | Manual Limits |
|---|---|
| Calculated by Matplotlib. | Specified by the developer. |
| Adjust based on plotted data. | Use the selected minimum and maximum values. |
| Useful for general data visualization. | Useful for focusing on a specific range. |
| Requires less configuration. | Provides more control over the visible region. |
Example: Automatic Limits
import matplotlib.pyplot as plt
x = [10, 20, 30, 40, 50]
y = [100, 200, 150, 300, 250]
plt.plot(x, y)
plt.title("Automatic Axis Limits")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
Matplotlib automatically selects suitable X-axis
and Y-axis ranges based on the plotted data.
The visible chart area includes the data points.
Example: Manual Limits
import matplotlib.pyplot as plt
x = [10, 20, 30, 40, 50]
y = [100, 200, 150, 300, 250]
plt.plot(x, y)
plt.xlim(15, 45)
plt.ylim(120, 280)
plt.title("Manual Axis Limits")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
The chart displays only the selected region.
The X-axis range is 15 to 45.
The Y-axis range is 120 to 280.
Data outside these boundaries is not visible.
9. Reversing Axis Limits
You can reverse the direction of an axis by specifying the maximum value before the minimum value.
For example, plt.xlim(10, 0) reverses the horizontal axis
so that values decrease from left to right.
Example: Reverse X-Axis
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
plt.plot(x, y, marker="o")
plt.xlim(5, 1)
plt.title("Reversed X-Axis")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
A line chart is displayed with a reversed X-axis.
The X-axis begins at 5 on the left and decreases
towards 1 on the right.
Example: Reverse Y-Axis
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
plt.plot(x, y, marker="o")
plt.ylim(40, 0)
plt.title("Reversed Y-Axis")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
The Y-axis is reversed.
Higher values appear towards the bottom,
and lower values appear towards the top.
10. Zooming Into a Specific Chart Region
Axis limits are useful when you want to zoom into a particular region of a chart. You can choose a smaller X-axis and Y-axis range to focus on specific data points.
Example: Zoom Into a Data Region
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [10, 15, 20, 18, 30, 35, 32, 45, 50, 48]
plt.plot(x, y, marker="o")
plt.xlim(3, 7)
plt.ylim(15, 40)
plt.title("Zoomed Chart Region")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Expected Output
A line chart displays a zoomed section of the original data.
Only X values between 3 and 7 are visible.
Only Y values between 15 and 40 are visible.
11. Common Mistakes
| Mistake | Explanation | Correct Approach |
|---|---|---|
| Using incorrect limit order | Passing the maximum before the minimum reverses the axis. | Use minimum first and maximum second for a normal axis. |
| Hiding important data | Manually selected limits may exclude important points. | Check the dataset before selecting limits. |
| Using xlim() for Y-axis | xlim() controls only the horizontal axis. | Use ylim() for the vertical axis. |
| Confusing limits with ticks | Limits define the range, while ticks define positions along the axis. | Use axis-limit methods for ranges and tick methods for tick positions. |
| Assuming data is deleted | Axis limits only control what is displayed. | Remember that the original data remains unchanged. |
12. Practical Activity
Activity: Create a Temperature Chart
Create a line chart showing temperature readings for ten days. Set custom axis limits to focus on a selected range of days and temperatures.
Requirements
- Create a list of ten day values.
- Create a list of ten temperature values.
- Display the values using a line plot.
- Set X-axis limits from 2 to 8.
- Set Y-axis limits from 15 to 35.
- Add a title, axis labels, and markers.
Sample Solution
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
temperature = [
12, 15, 18, 22, 25,
28, 30, 27, 32, 35
]
plt.plot(
days,
temperature,
marker="o",
color="red",
label="Temperature"
)
plt.xlim(2, 8)
plt.ylim(15, 35)
plt.title("Daily Temperature Analysis")
plt.xlabel("Days")
plt.ylabel("Temperature (°C)")
plt.legend()
plt.show()
Expected Output
A red line chart displays daily temperature readings.
The X-axis is restricted from day 2 to day 8.
The Y-axis is restricted from 15°C to 35°C.
Markers identify the temperature readings.
The legend displays the Temperature label.
13. Practice Questions
Basic Questions
- What are axis limits in Matplotlib?
- Which function controls X-axis limits?
- Which function controls Y-axis limits?
- What is the purpose of
plt.xlim()? - What is the purpose of
plt.ylim()?
Intermediate Questions
- How can you set both X-axis and Y-axis limits?
- What is the difference between automatic and manual axis limits?
- How can you retrieve the current axis limits?
- How can you reverse the X-axis?
- What is the difference between
set_xlim()andget_xlim()?
Practical Questions
- Create a line plot and set X-axis limits from 0 to 10.
- Create a chart and set Y-axis limits from 20 to 80.
- Set both axis limits using the Object-Oriented API.
- Display a reversed X-axis.
- Create a chart and zoom into a selected data region.
Summary
Axis limits control the visible range of a Matplotlib chart. The X-axis limits define the horizontal boundaries, while the Y-axis limits define the vertical boundaries of the plotting area.
The pyplot functions xlim() and ylim() allow you to set the minimum and maximum values of the axes. In the Object-Oriented API, set_xlim() and set_ylim() provide the same functionality through an Axes object.
Matplotlib automatically calculates suitable axis limits based on the plotted data. However, manual limits are useful when you want to focus on a specific range, zoom into a chart, or control the visible plotting area.
You can also retrieve existing axis limits using get_xlim() and get_ylim(), or reverse an axis by specifying its limits in descending order. Understanding axis limits helps you create clear and meaningful visualizations.