11.1 C
London
Sunday, July 7, 2024
HomePythonMatplotlib in PythonHow to Reverse Axes in Matplotlib (With Examples)

How to Reverse Axes in Matplotlib (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to reverse the x-axis and y-axis in Matplotlib:

plt.gca().invert_xaxis()
plt.gca().invert_yaxis()

The following example shows how to use this syntax in practice.

Example: Reverse Axes in Matplotlib

The following code shows how to create a basic scatterplot in Matplotlib:

import matplotlib.pyplot as plt

#define x and y
x = [1, 4, 8, 11, 13, 14]
y = [5, 11, 18, 26, 25, 23]

#create scatterplot of x and y
plt.scatter(x, y)

We can use the following code to reverse the y-axis:

import matplotlib.pyplot as plt

#define x and y
x = [1, 4, 8, 11, 13, 14]
y = [5, 11, 18, 26, 25, 23]

#create scatterplot of x and y
plt.scatter(x, y)

#reverse y-axis
plt.gca().invert_yaxis()

Notice that the y-axis now ranges from 25 to 5 instead of 5 to 25.

Alternatively, we could use the following code to reverse the x-axis:

import matplotlib.pyplot as plt

#define x and y
x = [1, 4, 8, 11, 13, 14]
y = [5, 11, 18, 26, 25, 23]

#create scatterplot of x and y
plt.scatter(x, y)

#reverse x-axis
plt.gca().invert_xaxis()

Notice that the x-axis now ranges from 14 to 0 instead of 0 to 14.

Lastly, we could use the following code to reverse both axes:

import matplotlib.pyplot as plt

#define x and y
x = [1, 4, 8, 11, 13, 14]
y = [5, 11, 18, 26, 25, 23]

#create scatterplot of x and y
plt.scatter(x, y)

#reverse both axes
plt.gca().invert_xaxis()
plt.gca().invert_yaxis()

Notice that both axes values are reversed.

Additional Resources

The following tutorials explain how to perform other common operations in Matplotlib:

How to Set Axis Ranges in Matplotlib
How to Set Axis Ticks in Matplotlib
How to Adjust Axis Label Position in Matplotlib

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories