How to switch axes in Matplotlib?

To switch axes in matplotlib, we can create a figure with two subplots to demonstrate how the X and Y axes are swapped. This technique is useful for comparing data from different perspectives or when you need to visualize the inverse relationship between variables.

Steps

  • Create x and y data points using numpy

  • Create a figure and add a set of two subplots

  • Set the title of the plot on both the axes

  • Plot x and y data points using plot() method

  • Extract the x and y data points using get_xdata() and get_ydata()

  • To switch the axes of the plot, set x_data and y_data of the axis 1 curve to axis 2 curve

  • Adjust the padding between and around the subplots

  • To display the figure, use show() method

Example

Here's how to create two plots where the second plot has switched X and Y axes ?

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-2, 2, 50)
y = np.sin(x)

f, axes = plt.subplots(2)

axes[0].set_title("Original plot")
curve, = axes[0].plot(x, y, c='r')

# Extract x and y data from the first plot
newx = curve.get_xdata()
newy = curve.get_ydata()

# Create second plot with switched axes
axes[1].set_title("Switched axes plot")
curve2, = axes[1].plot(x, y, c='r')

# Switch the axes by setting y data as x and x data as y
curve2.set_xdata(newy)
curve2.set_ydata(newx)

plt.tight_layout()
plt.show()

Alternative Method Using Direct Plotting

You can also switch axes by directly plotting y vs x instead of x vs y ?

import numpy as np
from matplotlib import pyplot as plt

x = np.linspace(-2, 2, 50)
y = np.sin(x)

f, axes = plt.subplots(1, 2, figsize=(10, 4))

# Original plot: x vs y
axes[0].plot(x, y, 'r-')
axes[0].set_title("Original: x vs sin(x)")
axes[0].set_xlabel("x")
axes[0].set_ylabel("sin(x)")

# Switched plot: y vs x
axes[1].plot(y, x, 'b-')
axes[1].set_title("Switched: sin(x) vs x")
axes[1].set_xlabel("sin(x)")
axes[1].set_ylabel("x")

plt.tight_layout()
plt.show()

Key Points

  • get_xdata() and get_ydata() extract data from existing plot lines

  • set_xdata() and set_ydata() modify the data of existing plot lines

  • Direct plotting with plot(y, x) is simpler than using get/set methods

  • tight_layout() automatically adjusts subplot spacing

Output

The first subplot shows the original sine wave, while the second subplot displays the same data with X and Y axes switched, creating a reflection of the original plot.

Original: x vs sin(x) x sin(x) Switched: sin(x) vs x sin(x) x

Conclusion

Switching axes in matplotlib can be accomplished using get_xdata()/get_ydata() methods or by directly plotting y vs x. This technique is useful for data analysis and visualization from different perspectives.

Updated on: 2026-03-25T19:56:38+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements