Explain Codes LogoExplain Codes Logo

How to invert the x or y axis

python
matplotlib
plotting
data-visualization
Anton ShumikhinbyAnton Shumikhin·Oct 9, 2024
TLDR

To quickly invert an axis in matplotlib, apply invert_xaxis() or invert_yaxis() on plt.gca(), which means get current axes. Here's a quick demo:

import matplotlib.pyplot as plt # When plotting feels like a Monday morning... plt.scatter([1, 2, 3], [4, 5, 6]) # Invert the y-axis plt.gca().invert_yaxis() # Display the plot, or the Monday blues plt.show()

For changing the x-axis, simply replace invert_yaxis with invert_xaxis(). Call the inversion method after your plot commands, just before plt.show().

Digging deeper: Advanced usage and potential pitfalls

Setting the limits

In addition to inverting an axis, you might want to define its limits. For this, ax.set_ylim() or ax.set_xlim() is useful. However, ensure to provide the limits in reverse:

# Let's flip the x-axis, because why not? ax = plt.gca() ax.set_xlim(10, 0) # flip x-axis plt.show()

Adding padding and adjusting ranges

To add padding around the edges or to set a custom range, you can call upon plt.axis():

# Padding with some style! plt.plot([1, 2, 3], [4, 5, 6]) plt.gca().invert_yaxis() plt.axis([0, 3, 6 + 1, 4 - 1]) # custom axis ranges plt.show()

Inversion by slicing

If you're working with data lists, numpy arrays or pandas series, you could invert their order applying slicing: [::-1]. This indirectly reverses the axis when you plot the changed data:

import numpy as np # A plot twist with slicing! data = np.array([3, 2, 1]) plt.plot([1, 2, 3], data[::-1]) # y-axis is inverted now plt.show()

Axes object in action

Direct manipulation of the Axes object can offer you more control over the plot. This is how you can invoke invert_yaxis() following the plot creation:

fig, ax = plt.subplots() ax.scatter([1, 2, 3], [4, 5, 6]) ax.invert_yaxis() # invert the y-axis after plotting data plt.show()

Acing the game: Common pitfalls and solutions

Inline plotting with IPython

While using IPython environments in pylab mode, do not forget to call plt.show() after axis inversion to properly render the changes:

# It's not magic, it's just IPython inline plotting %matplotlib inline plt.plot([1, 2, 3], [4, 5, 6]) # Inverting y-axis, because we can plt.gca().invert_yaxis() # Sanitize after inversion, always. plt.show()

Keeping up with matplotlib API updates

As the matplotlib API updates frequently, getting accustomed to matplotlib.scale and the methods in Axes can be beneficial for more advanced inversion tactics, say for instance, logarithmic scaling or invertible transformations.

Error prediction and prevention

Ensure you're accessing the correct Axes instance. Calling invert_yaxis() on a non-existent or incorrect axis will lead to errors. Use plt.gca() or fig, ax = plt.subplots() to verify that you're tweaking the right plot.