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 add a second X-axis at the bottom of the first one in Matplotlib?
In Matplotlib, you can add a second X-axis at the top of your plot using the twiny() method. This creates a twin axis that shares the same Y-axis but has an independent X-axis positioned at the top.
Steps
- Set the figure size and adjust the padding between and around the subplots
- Get the current axis (ax1) using
gca()method - Create a twin axis (ax2) sharing the Y-axis using
twiny() - Set X-axis ticks and labels for both axes
- Display the figure using
show()method
Example
Here's how to create a plot with two X-axes −
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Get the first axis
ax1 = plt.gca()
# Create a twin axis sharing the Y-axis
ax2 = ax1.twiny()
# Set ticks and labels for both axes
ax2.set_xticks([1, 2, 3, 4, 5])
ax1.set_xlabel("X-axis 1 (bottom)")
ax2.set_xlabel("X-axis 2 (top)")
plt.show()
Complete Example with Data
Here's a more practical example showing how to plot data with different scales on both X-axes −
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
x1 = np.linspace(0, 10, 100)
y = np.sin(x1)
# Create the plot
fig, ax1 = plt.subplots(figsize=(8, 4))
# Plot data on the first axis
ax1.plot(x1, y, 'b-', linewidth=2)
ax1.set_xlabel('Time (seconds)', color='blue')
ax1.set_ylabel('Amplitude')
# Create second X-axis at the top
ax2 = ax1.twiny()
# Set different scale for the top axis
x2 = x1 * 60 # Convert seconds to minutes
ax2.set_xlim(ax1.get_xlim()[0] * 60, ax1.get_xlim()[1] * 60)
ax2.set_xlabel('Time (minutes)', color='red')
plt.title('Plot with Two X-axes')
plt.tight_layout()
plt.show()
Key Points
- Use
twiny()to create a second X-axis that shares the Y-axis - The second axis appears at the top of the plot by default
- Both axes can have independent scales, ticks, and labels
- Use different colors for labels to distinguish between axes
- Apply
tight_layout()to prevent label overlap
Conclusion
The twiny() method provides an easy way to add a second X-axis at the top of your Matplotlib plots. This is useful when you need to display the same data with different units or scales on both axes.
Advertisements
