banner



How To Set Axis Values In Matplotlib

In this Python Matplotlib tutorial, we will discuss the Matplotlib prepare y axis range in matplotlib. Here we volition cover unlike examples related to the prepare y-axis range using matplotlib. And nosotros will also cover the post-obit topics:

  • Matplotlib set y axis range
  • Matplotlib set up y axis range telephone call
  • Matplotlib set y centrality max value
  • Matplotlib ready y axis min value
  • Matplotlib set y axis log scale
  • Matplotlib scatter set y axis range
  • Matplotlib fix y centrality range subplot
  • Matplotlib histogram prepare y axis range
  • Matplotlib bar chart fix y axis range
  • Matplotlib boxplot y axis range
  • Matplotlib y axis range setp

Matplotlib set y axis range

In this section, nosotros'll larn how to fix the y-axis range. The ylim() function of the pyplot module of the matplotlib library is used for setting the y-axis range.

The ylim() function is used to set or to become the y-axis limits or we can say y-axis range. By default, matplotlib automatically chooses the range of y-axis limits to plot the data on the graph surface area. Merely if we want to change that range of the current axes then we tin can use the ylim() office.

So starting time, we'll see the syntax of the ylim() function.

          matplotlib.pyplot.ylim(*args, **kargs)        

Here we can use arguments and keyword arguments, so we tin can accept zero or multiple arguments and keyword arguments.

Likewise, check: Matplotlib update plot in loop

Matplotlib set y centrality range call

There we'll learn to phone call the ylim() role of the pyplot module. Usually, we'll call ylim() function in three dissimilar ways:

  • Get current y-axis range
  • Change current y-axis range
  • Change current y-axis range with keyword arguments

Get electric current y-axis range

To become the range of current y-axis range we'll accept to take the two variables say left and right, so we'll get the left value and correct value of the range, and then nosotros'll call this ylim() function.

Syntax:

          left,right = matplotlib.pyplot.ylim()        

Let's see an example:

                      # Import Library                        import numpy as np  import matplotlib.pyplot as plt            # Data Coordinates                        x = np.arange(1, ten)  y = np.array([ii, iv, 6, viii, 9, 10, 12, 14, 16])            # Plot                        plt.plot(10, y)            # Get and impress current axes                        bottom,top = plt.ylim()  impress("Lesser value:",left,"\n","Meridian Value:",right)            # Add Championship                        plt.title("Go Electric current y-centrality range")            # Add together Axes Labels            plt.xlabel("X-centrality")  plt.ylabel("Y-centrality")            # Display            plt.show()                  
  • Firstly, we import matplotlib.pyplot, and numpy library.
  • Next, we ascertain information coordinates for plotting using arange() and array() method of numpy.
  • plt.plot() method is used to plot the graph.
  • Next, take ii variables bottom and meridian, and and then take the ylim() function without whatsoever argument to return the current y-axis range.
  • So we'll get the bottom and top values, and print them using the print() function.
  • To add the title, we use the title() function.
  • To add the x and y axes labels, we utilise the xlabel() and ylabel() functions.
  • To display the graph, we use the testify() method.
matplotlib set y axis range call
plt.ylim()

Modify current y-axis range

If we want to change the limits of the electric current y-axis, then we call the ylim() function with the lesser value and top value of your selection.

Syntax:

          matplotlib.pyplot.ylim(bottom_value,top_value)        

Let's see an instance:

                      # Import Library            import numpy every bit np import matplotlib.pyplot as plt            # Define Data            ten = [one, 2, 3, 4, 5] y = [5, 10, 15, 20, 25]            # Change electric current axes            plt.ylim(x, xxx)            # Plot            plt.plot(x,y,'-o')            # Display            plt.show()        

Here nosotros use the ylim() function to ready the limits of the y-centrality and we pass the minimum and maximum value to the function as an argument.

matplotlib call set yaxis range
plt.ylim(10, 30)

Change current y-axis range with keyword arguments

Here we'll apply the ylim() role to modify the axes range of the y-axis bypassing the bottom and top as keyword arguments instead of taking arguments.

Syntax:

          matplotlib.pyplot.xlim(lesser=value, peak=value)        

Let'south run across an example:

                      # Import Library                        import matplotlib.pyplot as plt import numpy every bit np            # Define data coordinates                        x = np.linspace(20, 10, 100) y = np.tan(x)            # Change axes with keyword arguments                        plt.ylim(bottom=-150, tiptop=150)            # Plot                        plt.plot(x, y)            # Brandish            plt.bear witness()        
  • Here we first importmatplotlib.pyplot andnumpy libraries.
  • Next, nosotros define data coordinates, usinglinespace() andtan() function of numpy.
  • To alter the limit of axes, we use theylim() function with keyword argumentsbottomandelevationand set their values. Here we prepare the bottom value equally -150 and the top value as 150.
  • To plot the line graph, nosotros use the plot() function.
matplotlib set y axis range by calling
plt.ylim(lesser=-150, top=150)

Read: Matplotlib Pie Chart Tutorial

Matplotlib prepare y axis max value

Here we'll learn to set up or get the limit of the maximum value i.east pinnacle value of the y-centrality. Allow's encounter different examples:

Example #1

In this case, we'll get the top limit of the y-axis and for this, we'll take the variable top, and then we telephone call theylim() function without whatsoever argument.

Syntax:

          top=matplotlib.pyplot.ylim()        

Source Lawmaking:

                      # Import Library            import numpy equally np  import matplotlib.pyplot as plt            # Data Coordinates            ten = [3, 6, ix, 12, 15] y = [v.5, eight, x.5, 23, 12]            # Plot            plt.plot(x, y)            # Get and print electric current axes                        lesser,top= plt.ylim()  impress("Top value:",acme)            # Display            plt.show()        

Output:

matplotlib get y axis max value
top=plt.ylim()

Example #2

In this example, we'll set the max limit of the electric current y-axis and for this, we'll take the keyword argument top with the ylim() function.

Syntax:

          matplotlib.pyplot.ylim(top=top_value)        

Source Code:

                      # Import Library            import numpy every bit np  import matplotlib.pyplot as plt            # Data Coordinates            x = np.linspace(0, xxx, 150) y = np.sin(x)            # Plot                        plt.plot(x, y)            # Set tiptop axes            plt.ylim(pinnacle=one.85)            # Display            plt.show()        
matplotlib set y axis max value
plt.ylim(top=ane.85)

Read: Matplotlib besprinkle plot colour

Matplotlib fix y centrality min value

Here we'll learn to set up or get the minimum limits of the y-axis. Let'southward see dissimilar examples:

Instance #ane

In this example, nosotros'll go the minimum i.e. bottom limit of the y-centrality. For this, we'll have the variable bottom, and then we phone call the ylim() function without any statement. And later on this, nosotros impress the lesser value.

Syntax:

          bottom=matplotlib.pyplot.ylim()        

Source Code:

                      import matplotlib.pyplot as plt import numpy as np            # Define data coordinates            x = np.arange(5, 11)  y = np.exp(x)            # Plot            plt.plot(x, y)            # Become and print current axes            bottom,top= plt.ylim()  print("Bottom Value:",bottom)            # Display                        plt.evidence()        
matplotlib set y axis min value
bottom=plt.ylim()

Case #ii

In this instance, nosotros'll set the bottom y-axis, and for this, we'll pass an argument to the ylim() role and it automatically take it equally a bottom value.

Syntax:

          matplotlib.pyplot.ylim(value)        

Source Lawmaking:

                      # Import Libraries                        import matplotlib.pyplot as plt import numpy as np            # Define Information                        x = np.random.randint(depression=1, loftier=20, size=25)            # Plot            plt.plot(x,linewidth=iii, linestyle='dashed')            # y-axis limits            plt.ylim(-1)            # Display            plt.show()        
matplotlib set min value of y-axis
plt.ylim(-one)

Read: Matplotlib set_xticks – Detailed tutorial

Matplotlib set y centrality log scale

Here we'll see an example of a log plot and we also set the limits of the y-centrality.

Instance:

                      # Import Library                        import matplotlib.pyplot as plt            # Define Information            information = [x**i for i in range(6)]            # Convert y-axis                        plt.yscale("log")            # Plot                        plt.plot(data)            # y-axis limit            plt.ylim([1,2**14])            # Display            plt.show()        
  • Here we first importmatplotlib.pyplot library.
  • Next, we ascertain information coordinates.
  • And then we catechumen y-axis scale to log scale, by usingyscale() role.
  • To plot the graph, we utiliseplot() part.
  • To fix the limits of y-centrality, we applyylim() function.
  • To display the graph, we utilizeevidence() function.
matplotlib set y axis range log scale
plt.ylim()

Read: Matplotlib fill_between – Complete Guide

Matplotlib scatter gear up y axis range

Here nosotros'll ready the limit of the y-centrality of the scatter plot. To create a scatter plot, we use the scatter() function of the pyplot module, and to set the range of the y-centrality we use the ylim() function.

Instance:

                      # Import Library                        import matplotlib.pyplot every bit plt import numpy every bit np            # Define Data                        x = [ii, 6, 3, 5, x, 9.5] y = [20, xiii, 15.6, 25, 6, 21]            # Plotting                        plt.scatter(x, y)            # Set axes                        plt.ylim(bottom=5,superlative=twenty)            # Add label                        plt.xlabel('X-Axis') plt.ylabel('Y-Axis')            # Display            plt.evidence()        

Beneath output is with default y-axis limits:

matplotlib scatter set y axis range
plt.besprinkle()

Now permit'south see the output where we alter the y-centrality limits:

matplotlib scatter plot set y axis range
plt.ylim(lesser=5,height=twenty)

Read: Matplotlib set_yticklabels – Helpful Guide

Matplotlib set y axis range subplot

Here nosotros'll discuss how nosotros can alter the y-axis limit of the specific subplot if we draw multiple plots in a figure area.

Instance:

                      # Importing Libraries            import numpy as np import matplotlib.pyplot every bit plt            # Create subplot            fig, ax = plt.subplots(1, 2)            # Define Data                        x1= [0.2, 0.four, 0.6, 0.8, 1] y1= [0.3, 0.vi, 0.8, 0.nine, 1.v]  x2= [2, half dozen, vii, 9, ten] y2= [five, x, xvi, 20, 25]            # Plot graph                        ax[0].plot(x1, y1) ax[1].plot(x2, y2)            # Limit axes                        ax[i].set_ylim(5,16)            # Add space            fig.tight_layout()            # Brandish Graph                        plt.show()        
  • Firstly, we import numpyandmatplotlib.pyplot libraries.
  • After this, we create a subplot usingsubplots() function.
  • Then we create x and y information coordinates for both the plots.
  • To plot a graph, we use theplot() part of the axes module.
  • Here nosotros change the x-axis limit of 1st subplot past using theset_ylim() function. It ranges between 5 to sixteen.
  • To auto-accommodate the space between subplots, we use thetight_layout() function.
  • To display the graph, we use theshow() function.
matplotlib set y axis range subplot
a[ane].set_ylim()

Read: Matplotlib tight_layout – Helpful tutorial

Matplotlib histogram set y axis range

Hither we'll larn to set the limit of the y-axis in the histogram.

Example:

                      # Import Library            import numpy as np import matplotlib.pyplot every bit plt            # Define Data            x = np.random.normal(200, ten, 60)            # Plot Histogram                        plt.hist(x)            # Set limits            plt.ylim(top=15)            # Display            plt.show()        
  • Here we use plt.hist() function, to plot a histogram chart.
  • After this we use plt.ylim() function, to prepare the summit or maximum limit of the y-centrality.
matplotlib histogram set y axis range
# Default axes limit
matplotlib set y axis range of histogram
plt.ylim()

Read: Python Matplotlib tick_params + 29 examples

Matplotlib bar chart fix y centrality range

Here we'll see an example of a bar chart where we set the limit of the y-axis manually.

Instance:

                      # Import Library            import matplotlib.pyplot equally plt            # Ascertain Data                        x = ['Comdey', 'Action', 'Romance', 'Drama'] y = [4, 5.5, seven.6, 3]            # Plot Histogram                        plt.bar(x,y)            # Fix limits            max_ylim = max(y) + ane.5 min_ylim = min(y) - ane plt.ylim(min_ylim, max_ylim)            # Display            plt.show()        
  • Import matplotlib.pyplot library.
  • Next, create a list of data points.
  • To plot a bar nautical chart, use the bar() function.
  • Ascertain ii variables max_ylim and min_ylim for getting the maximum and minimum value of the y-axis.
  • To set the limits of the y-axis, we employ the ylim() function.
  • To display the figure, use the testify() function.
matplotlib bar chart set y axis range
plt.bar()

Read: What is add_axes matplotlib

Matplotlib boxplot y axis range

Here we'll learn to set the y-axis range for boxplot using matplotlib.

Permit's see examples related to this:

Instance #1

In this example, nosotros'll use ylim() method to gear up axis range.

                      # Import libraries                        import matplotlib.pyplot as plt import numpy equally np            # Figure size            fig = plt.effigy(figsize =(eight,6))            # Dataset            np.random.seed(50) data = np.random.normal(100, 20, 200)            # Creating plot                        plt.boxplot(data)            # Prepare y-axis range            plt.ylim(0,200)            # Prove plot            plt.show()        
  • Firstly, we import matplotlib.pyplot and numpy libraries.
  • Next, we gear up the figure size by using effigy() method and figsize argument.
  • So, we utilise seed() method and random.normal() method of numpy for defining data coordinates.
  • To plot the boxplot graph, we employ boxplot() method.
  • To run across the range of y-centrality, we utilize ylim() method.
  • To brandish the figure, we use testify() part.
matplotlib boxplot y axis range
Original Plot
matplotlib boxplot y axis limit
Matplotlib boxplot y-axis limit

Here, we fix the minimum limit to 0 and the maximum limit to 200. We tin can also telephone call the bottom and top limit instead of the min and max limit.

Example #2

In this example, we'll use the axis() method to set the limit.

                      # Import libraries            import pandas as pd import numpy every bit np import matplotlib.pyplot as plt            # Define Information                        df = pd.DataFrame(np.random.rand(30,10),                    columns=['C1', 'C2', 'C3', 'C4','C5',                            'C6','C7', 'C8', 'C9', 'C10' ])            # Plot            df.plot.box(grid='True')            # Set y-axis range            plt.centrality([None, None, -0.75, 1.v])            # Display            plt.bear witness()        
  • Import pandas library as pd for information creation.
  • Also, import numpy library equally np for information creation.
  • Then, import matplotlib.pyplot library equally plt for data visualization.
  • Then, apply DataFrame() part to create information frame.
  • To define the data coordinate, use random.rand() office.
  • To plot the boxplot, use boxplot() function.
  • To set the y-axis limit, we utilize axis() method and we fix xmin and xmax to None and ymin and ymax to -0.75 and ane.5 respectively.
  • To display the plot, use plot() function.
matplotlib set y axis range boxplot
Matplotlib fix y-axis range boxplot

Read: Matplotlib 2d surface plot

Matplotlib y axis range setp

Hither we'll learn how we can employ setp() function for setting y-centrality range using matplotlib.

To prepare the property on an artist object, use the setp() function in the pyplot module of the matplotlib package.

The post-obit is the syntax:

          matplotlib.pyplot.setp(obj, ,\*args, \*\*kwargs)        

The following are the parameter used:

  • obj: The artist object is represented by this statement.
  • **kwargs: At that place are a variety of keyword arguments that can be used.

Let's see examples related to this:

Example #1

In this instance, we utilize setp() function with ylim() function to set y-axis range.

                      # Import Libraries            import matplotlib.pyplot as plt import numpy as np            # Ascertain Information                        10 = np.arange(l) y = np.sin(ten)            # Plot            plt.plot(10, y)            # Set limit            plt.setp(plt.gca(),ylim=(0,1))            # Brandish            plt.testify()        
  • Import matplotlib.pyplot library for data visualization.
  • Import numpy library for data creation.
  • To define x and y data coordinates, utilize arange() and sin() function of numpy.
  • To plot a graph, use plot() function.
  • To set the centrality limit, we use setp() function and to represent the object nosotros utilize gca() role of pyplot module.
  • We likewise pass the ylim() role with minium and maximum value to setp() function to set y-centrality range.
  • To visualize a plot on user's screen, utilize show() function.
matplotlib y axis range setp
Matplotlib y axis range setp

Example #2

                      # Import Libraries            import matplotlib.pyplot equally plt import numpy as np            # Define Data                        name = ['Ava', 'Noah', 'Charlotte', 'Robert', 'Patricia'] weight_kg = [45, 60, fifty, 75, 53]            # Plot            plt.bar(name, weight_kg)            # Prepare y-centrality            plt.setp(plt.gca(), ylim=(0, 100))            # Display            plt.prove()        
  • Import necessary libraries such every bit numpy and matplotlib.pyplot.
  • Adjacent, ascertain the data coordinates to plot the graph.
  • To create a bar chart, use bar() role.
  • To set the axis limit, we use setp() office with ylim() role.
  • To brandish the graph, apply bear witness() role.
matplotlib y axis range using setp
Matplotlib y centrality range using setp

You may as well like to read the following Matplotlib tutorials.

  • Matplotlib scatter plot legend
  • Matplotlib increase plot size
  • Matplotlib multiple bar chart
  • Stacked Bar Chart Matplotlib
  • What is add_axes matplotlib
  • Draw vertical line matplotlib
  • Matplotlib 2d surface plot

So, in this Python tutorial, we accept discussed the"Matplotlib set y axis range" and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib set y centrality range
  • Matplotlib set y axis range call
  • Matplotlib fix y axis max value
  • Matplotlib set y axis min value
  • Matplotlib set y centrality log scale
  • Matplotlib besprinkle gear up y axis range
  • Matplotlib set y axis range subplot
  • Matplotlib histogram set y axis range
  • Matplotlib bar nautical chart prepare y centrality range
  • Matplotlib boxplot y axis range
  • Matplotlib y axis range setp

Source: https://pythonguides.com/matplotlib-set-y-axis-range/

0 Response to "How To Set Axis Values In Matplotlib"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel