How to Add a Second x-axis in Python Matplotlib?

Problem Formulation

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()

How to Add a Second x-axis in Python Matplotlib?

To plot two x-axes at the top and the bottom of a given plot, apply the following five steps:

  1. Define the X and Y data.
  2. Create a figure object with plt.figure().
  3. 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 set_xlabel() and set_xticks() methods.
  4. 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 set_xlabel() and set_xticks() methods.
  5. Plot and show everything using plt.show().
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. πŸ˜‰