Matplotlib Invert Y Axis - Python Guides (2024)

In thisPython tutorial, we will discussMatplotlib invert y axisin python. Here we will cover different examples related to inverting of the y-axis usingmatplotlib. And we will also cover the following topics:

  • Matplotlib invert y axis
  • Matplotlib invert y axis subplots
  • Matplotlib invert x and y axis
  • Matplotlib barh invert y axis
  • Matplotlib invert secondary y axis
  • Matplotlib 3D invert y axis
  • Matplotlib flip y axis label
  • Matplotlib invert y axis imshow

If you are new to python Matplotlir, check out, How to install matplotlib python.

Table of Contents

Matplotlib invert y axis

In this section, we learn about how to invert the y-axis in matplotlib in Python. Now before starting the topic firstly, we discuss what does invert mean here:

Invert means reverse or flip the order

To understand more clearly let’s take a common example:

Suppose the y-axis starts from 0 to 10 and you want to start it from 10 to 0. So in that cases, we invert or flip the axes of the plot.

In matplotlib, we can invert the y-axis of a graph using different methods. The following are the different methods used for reversing the y-axis are as below.

  • Using invert_yaxis() method
  • Using ylim() method
  • Using axis() method

By using invert_yaxis() method

To invert Y-axis, we can use invert_yaxis() method.

Syntax of the method is as below:

matplotlib.axes.Axes.invert_yaxis(self)

Example: (Without inverting axis)

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0, 15, 0.2)y = np.sin(x)# Plot figureplt.plot(x, y)# Titleplt.title("Sine Function Normal Plot", fontsize= 15, fontweight='bold')# Generate Plotplt.show()
  • In the above example, we import the matplotlib.pyplot and numpy library.
  • After this we define data using np.arrange() and np.sin() method.
  • Next, we use the plt.plot() method to draw the plot.
  • By using plt.title() we define the title of the plot.
  • plt.show() method is used to generate the plot on the user screen.
Matplotlib Invert Y Axis - Python Guides (1)

Look at the y-axis: Here it starts from -1.00 and ends at 1.00

Example: (With inverting axis)

# Import Libraryimport matplotlib.pyplot as pltimport numpy as np# Define Datax = np.arange(0, 15, 0.2)y = np.sin(x)# Plot figureplt.plot(x, y)# Invert y-axisax = plt.gca()ax.invert_yaxis()# Titleplt.title("Sine Function Invert Plot", fontsize= 15, fontweight='bold')# Generate Plotplt.show()
  • In the above example, we include the plt.gca() method to get current axes.
  • After this, we use the ax.invert_yaxis() method to invert or reverse the y-axis of the plot.
Matplotlib Invert Y Axis - Python Guides (2)

Look at the y-axis: Here it starts from 1.00 and ends at -1.00

Conclusion: By using invert_yaxis() method we can reverse the y-axis of the plot.

Read Put legend outside plot matplotlib

By using ylim() method

ylim() method is also used to invert axes of a plot in Matplotlib. Generally, this method is used to set limits for the axes.

But if we set the minimum value as the upper limit and maximum value as the lower limit we can revert the axes.

The syntax of the ylim() method is as below:

matplotlib.pyplot.ylim(bottom,top)

Here bottom and top specify the tuple of the new y-axis limits.

Let’s see an example to understand it more clearly:

# Import Libraryimport numpy as npimport matplotlib.pyplot as plt # Define Datax = np.linspace(5, 15, 35) y = 2*x+5 # Create plotaxes,(p1,p2) = plt.subplots(1, 2) # Normal plotp1.plot(x, y)p1.set_title("Normal Plot") # Invert plotp2.plot(x, y)p2.set_title("Inverted Plot")plt.ylim(max(y), min(y)) # Show axes.tight_layout()plt.show()
  • In the above example, firstly we import numpy and matplotlib.pyplot library.
  • Next, we define the data and by using the plt.subplot() method we create subplots.
  • Now we use the plot() method to draw a simple plot.
  • plt.ylim() method is used to invert the y-axis here we pass max and min as a parameter.
Matplotlib Invert Y Axis - Python Guides (3)

Conclusion: In the normal plot, the y-axis starts from 1 and ends at 5. And In the inverted plot, the y-axis starts from 5 and ends at 1.

Read Matplotlib save as pdf + 13 examples

By using axis() method

The axis() method is also used to revert axes in Matplotlib. Basically, this method is used to set the minimum and maximum values of the axes.

But if we set the minimum value as the upper limit and the maximum value as the lower limit we can get inverted axes.

The syntax of the axis() method is as below:

matplotlib.pyplot.axis()

Let’ see an example:

# Import Libraryimport numpy as npimport matplotlib.pyplot as plt # Define Datax = np.arange(0, 15, 0.2)y = np.tan(x) # Create plotaxes,(p1,p2) = plt.subplots(1, 2) # Normal plotp1.plot(x, y)p1.set_title("Normal Plot") # Invert plotp2.plot(x, y)p2.set_title("Inverted Plot")plt.axis([max(x), min(x), max(y), min(y)]) # Show axes.tight_layout()plt.show()
  • Here we import matplotlib.pyplot and numpy library and define data using np.arrange() and np.tan() method.
  • plt.subplots() method is used for creating subplots.
  • Then we use the plot() method to plot a graph and the set_title() method is used to add a title to the plot.
  • By using the plt.axis() method we revert the axes and here we pass the max and min values of the y and x axes.
Matplotlib Invert Y Axis - Python Guides (4)

Read Matplotlib title font size

Matplotlib invert y axis subplots

Here we will discuss how to invert the y-axis of the specific subplot if we draw multiple plots in a figure area in Python matplotlib.

We use the invert_yaxis() method to flip the y-axis of the subplot.

Let’s understand the concept with the help of an example:

# Import Librariesimport numpy as npimport matplotlib.pyplot as plt# Define Datax1= [0.2, 0.4, 0.6, 0.8, 1]y1= [0.3, 0.6, 0.8, 0.9, 1.5]x2= [2, 6, 7, 9, 10]y2= [3, 4, 6, 9, 12]x3= [5, 8, 12]y3= [3, 6, 9]x4= [5, 8, 12]y4= [3, 6, 9]fig, ax = plt.subplots(2, 2)# Invert y-axis ax[1,0].invert_yaxis()# Plot graphax[0, 0].plot(x1, y1)ax[0, 1].plot(x2, y2)ax[1, 0].plot(x3, y3)ax[1, 1].plot(x4, y4)# Display Graphfig.tight_layout()plt.show()
  • In the above example, we plot multiple plots in a figure area. And we want to invert the y-axis of the specific plot.
  • Here we use the invert_yaixs() method to flip the y-axis of the plot.
  • We use the invert_yaxis() method with the third plot.
Matplotlib Invert Y Axis - Python Guides (5)

Read Matplotlib default figure size

Matplotlib invert x and y axis

Here we are going to learn how to invert the x-axis and y-axis of the plot in Python matplotlib.

By using invert_xaxis() and invert_yaxis() method we can flip the x-axis and y-axis respectively.

The syntax is as given below:

# Invert x-axismatplotlib.axes.Axes.invert_xaxis(self)# Invert y-axismatplotlib.axes.Axes.invert_yaxis(self) 

Let’s see an example related to this concept:

# Import Libraryimport numpy as npimport matplotlib.pyplot as plt # Define Datax=[5, 10, 15, 20, 25,30]y=[0, 1, 2, 3, 4, 5] # Create Subplotaxes,(p1,p2) = plt.subplots(1, 2) # Normal plotp1.plot(x, y)p1.set_title("Normal Plot") # Invert plotp2.plot(x, y)p2.set_title("Inverted Plot")# Invert axesax = plt.gca()ax.invert_yaxis()ax.invert_xaxis() # Show axes.tight_layout()plt.show()
  • In the above example, we import numpy and matplotlib libraries.
  • After this, we define data on x and y coordinates.
  • By using the plt.subplots() method we create subplots in a figure area.
  • Next, we use the plot() method to plot a graph and the set_title() method to set the title of the plot.
  • Then we use plt.gca() method to get current axes of the plot.
  • By using the invert_yaxis() and the invert_xaxis() method we flip the axes of the plot.
  • In last, we use the tight_layout() method to automatically set the plots and the show() method to display the plot on the user’s screen.
Matplotlib Invert Y Axis - Python Guides (6)

Also, read Matplotlib savefig blank image

Matplotlib barh invert y axis

Here we are going to learn how we invert the y-axis of the horizontal bar chart using matplotlib in Python. Firstly, we have to know how to plot a horizontal bar chart.

The syntax to plot the horizontal bar chart is as below:

matplotlib.pyplot.barh(x,y)

Here x represents the x-axis coordinates and y represents the height of the bars.

The syntax to invert the y-axis of the barh chart is as given below:

# Invert y-axismatplotlib.axes.Axes.invert_yaxis(self) 

Example:

# Import Libraryimport numpy as npimport matplotlib.pyplot as plt# Define Datax=[1, 2, 3, 4, 5]y=[20, 15, 12, 6, 5]# Simple Bar Chartplt.figure()plt.barh(x,y)# Inverted Bar chartplt.figure()plt.barh(x,y)plt.gca().invert_yaxis()# Showplt.show()
  • In the above example, we first import the numpy and matplotlib.pyplot library.
  • Next, we define data.
  • By using the plt.barh() method we create a horizontal bar chart.
  • By using the plt.gca() method we get the current axes of the plot.
  • Then we use the invert_yaxis() method to flip the y-axis of the plot.
Matplotlib Invert Y Axis - Python Guides (7)

Read Matplotlib save as png

Matplotlib invert secondary y axis

Here we are going to learn how we can invert the secondary y-axis in matplotlib in Python. Firstly, we have to understand what does secondary y-axis means and when we need it.

Once in a while, we need two x-axes or y-axes to get more insights into the data. At that moment we need to create secondary axes.

In python, matplotlib provides the functionality to create a plot that has two y-axes, and even we can provide different labels to both.

We can create a plot with two different y-axes by using two different axes objects. And to create different axes objects we use the twinx() method.

Let’s see an example where we invert the secondary y-axis:

# Import Libraryimport numpy as npimport matplotlib.pyplot as plt # Define Datax = np.arange(0, 10, 3.5)y1 = x**2y2 = x**4 # Create subplotfig, ax = plt.subplots(figsize = (10, 5))# twinx() for creating axes object for secondary y-axisax2 = ax.twinx()# Plot graphax.plot(x, y1)ax2.plot(x, y2)# Invert secondary y-axisax2.invert_yaxis()# Labels to axesax.set_xlabel('x-axis')ax.set_ylabel('y-axis') # Label secondary y-axis ax2.set_ylabel('Secondary y-axis', color = 'b') # Display layoutplt.tight_layout() # Show plotplt.show()
  • In the above example, we import important libraries such as numpy and matplotlib.pyplot.
  • Next, we create data by using the np.arange() method here we define data between 0 to 10 with the difference of 3.5 at the x-axis.
  • Then by using plt.subplots() methods we create subplots.
  • By using the twinx() we create another axes object for the secondary y-axis.
  • set_xlabel() and set_ylabel() methods are used for adding labels on the axes.
  • By using the tight_layout() and show() method we define the layout and show the plot.
Matplotlib Invert Y Axis - Python Guides (8)
Matplotlib Invert Y Axis - Python Guides (9)

Read Matplotlib bar chart labels

Matplotlib 3D invert y axis

In this section, we are going to study how to invert a 3D plot in Matplotlib in Python.

The syntax to create a 3D plot and invert the y-axis:

# Create 3D plotax.plot3D(x,y,z)# Invert y-axismatplotlib.pyplot.ylim(max(y),min(y))

Here x, y, and z are the coordinates points.

Let’s see an example related to this:

# Import Librariesimport matplotlibfrom mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as plt# Create subplotsfig = plt.figure(figsize=(12,5), dpi=80)ax1 = fig.add_subplot(121, projection='3d')ax2 = fig.add_subplot(122, projection='3d')# Simple plotx=[1,1,10,10]y=[1,10,10,10]z=[1,1,1,10]ax1.plot(x,y ,z , marker="o")# Inverted Plotx1=[1,1,10,10]y1=[1,10,10,10]z1= [1,1,1,10]# Function used for invert y-axisplt.ylim(max(y1),min(y1))ax2.plot(x1,y1 ,z1, marker="o")# Show Plotplt.show()
  • In the above example, we import important libraries such as matplotlib.pyplot, and mplot3D.
  • Next, we use the plot() method to plot a graph in a figure area.
  • By using the ylim() method we invert the y-axis of the plot. In function, we pass the max and min of y1 coordinates.
Matplotlib Invert Y Axis - Python Guides (10)

Read Add text to plot matplotlib in Python

Matplotlib flip y axis label

Here we are going to learn to flip labels at the y-axis in Matplotlib in Python. By using the ylabel() method we can add the label at the y-axis and flip it.

Example:

# Import Libraryfrom matplotlib import pyplot as plt# Define Datax=[0, 1, 2, 3, 4, 5]y=[2, 4, 6, 8, 10, 12]# Plot graphplt.plot(x,y)# Flip Y-axis Labelplt.ylabel('Y-axis',rotation=0)# Showplt.draw()
  • In the above example, we import matplotlib.pyplot library for visualization.
  • Next, we define the data and use the plt.plot() method to draw a plot.
  • By using plt.ylabel() method we set the label at the y-axis and flip it horizontally by passing the rotation argument. Here we set the value of rotation to 0.
Matplotlib Invert Y Axis - Python Guides (11)
Matplotlib Invert Y Axis - Python Guides (12)

Read Matplotlib plot error bars

Matplotlib invert y axis imshow

Here we learn to invert the y-axis in the imshow() method in Python Matplotlib. Firstly, understand what does imshow does:

inshow() method shows an image of a color-mapped or 3D RGB array.

The syntax of the inshow() method is given below:

matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=, filternorm=1, filterrad=4.0, imlim=, resample=None, url=None, data=None, *kwargs)

The parameters used above are described as below:

  • X: specify data of the image.
  • cmap: specifies colormap or registered colormap name.
  • norm: It is a normalized instance used to scale data.
  • aspect: Used to control the aspect ratio of the axes.
  • interpolation: It is an interpolation method used to display images.
  • alpha: specify the intensity of the color.
  • vmin, vmax: specify the range of the color bar.
  • origin: Used to place [0,0] index of the array in the upper left or lower corner of the axes.
  • extent: It is a bounding box in data coordinates.
  • filternorm: Used for the antigrain image resize filter.
  • filterrad: specify the filter radius for filters.
  • url: set the URL of the axes image.

Example:

# Import Librariesimport numpy as npfrom matplotlib import pyplot as plt# Define datax = np.array([[0, 1, 2, 3], [1, 1, 1, 3], [1, 2, 2, 3], [2, 2, 3, 3]])# Create subplotfig, ax = plt.subplots(1,2)# Imshow and Invert Y-axisfor i in range(2): ax[0].imshow(x, cmap = 'summer', vmin = 1, vmax = 3,) ax[1].imshow(x, cmap = 'summer', vmin = 1, vmax = 3, origin='lower')# Showplt.show()
  • Here we define data using the np.array() method and use the imshow() method to plot the image of the colormap.
  • We pass the parameter origin to flip the y-axis and set its value to lower.
Matplotlib Invert Y Axis - Python Guides (13)

You may like the following Python Matplotlib tutorials:

  • Matplotlib remove tick labels
  • modulenotfounderror: no module named ‘matplotlib’
  • Matplotlib plot a line
  • Python plot multiple lines using Matplotlib
  • What is matplotlib inline
  • Python Matplotlib tick_params

In this Python tutorial, we have discussed the“Matplotlib invert y axis”and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib invert y axis
  • Matplotlib invert y axis subplots
  • Matplotlib invert x and y axis
  • Matplotlib barh invert y axis
  • Matplotlib invert secondary y axis
  • Matplotlib 3D invert y axis
  • Matplotlib flip y axis label
  • Matplotlib invert y axis imshow

Matplotlib Invert Y Axis - Python Guides (14)

Bijay Kumar

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Matplotlib Invert Y Axis - Python Guides (2024)
Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated:

Views: 5567

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.