Given some data. How to plot the data in the same 2D plot but using two x-axes instead of only one?
- You want to have on top axis and one bottom axis.
- You want to be able to customize the ticks and labels of both the top and bottom axis.
We use Matplotlib for this challenge. You can check out our full Matplotlib Mastery Course on the Finxter Academy.
Solution: Matplotlib Axis.twiny()
To plot two x-axes at the top and the bottom of a given plot, apply the following five steps:
- Define the
- Create a figure object with
- Configure the first x-axis using
fig.add_subplot(111)and plot the data using
ax1.plot(X, Y). You can customize the labels and ticks of the axis object with its
- Configure the second x-axis using
ax1.twiny()that creates a copy of the first x-axis that shares the same y-axis. Customize the labels and ticks of the second axis object with its
- Plot and show everything using
import matplotlib.pyplot as plt # 1. Define data X = [0, 1, 2, 3] Y = [x**2 for x in X] # 2. Define figure fig = plt.figure() # 3. Configure first x-axis and plot ax1 = fig.add_subplot(111) ax1.plot(X, Y) ax1.set_xlabel("Original x-axis") ax1.set_xticks((0, 1, 2, 3)) # 4. Configure second x-axis ax2 = ax1.twiny() ax2.set_xticks((0.5, 1.5, 2.5)) ax2.set_xlabel("Modified x-axis") # 5. Make the plot visible plt.show()
The output is the following beauty with two axis instead of only one:
For example, if you want to change the number of ticks and the label of the second x axis, you can do so here:
# ... # 4. Configure second x-axis ax2 = ax1.twiny() ax2.set_xticks([0.2 * x for x in range(20)]) ax2.set_xlabel("FINXTER LEARN PYTHON!") # 5. Make the plot visible plt.show()
Now, have a look at the output—what has changed?
Yes, Python also plots the yellow sun around the second axis. I swear. Not. 😉
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.