How to invert the x or y axis
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:
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:
Adding padding and adjusting ranges
To add padding around the edges or to set a custom range, you can call upon plt.axis()
:
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:
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:
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:
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.
Was this article helpful?