Matplotlib set y axis range

In this Python Matplotlib tutorial, we will discuss the Matplotlib set y axis range in matplotlib. Here we will cover different examples related to the set y-axis range using matplotlib. And we will also cover the following topics:

  • Matplotlib set y axis range
  • Matplotlib set y axis range call
  • Matplotlib set y axis max value
  • Matplotlib set y axis min value
  • Matplotlib set y axis log scale
  • Matplotlib scatter set y axis range
  • Matplotlib set y axis range subplot
  • Matplotlib histogram set y axis range
  • Matplotlib bar chart set y axis range
  • Matplotlib boxplot y axis range
  • Matplotlib y axis range setp

Matplotlib set y axis range

In this section, we’ll learn how to set 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 get 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 area. But if we want to change that range of the current axes then we can use the ylim() function.

So first, we’ll see the syntax of the ylim() function.

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

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

Also, check: Matplotlib update plot in loop

Matplotlib set y axis range call

There we’ll learn to call the ylim() function of the pyplot module. Usually, we’ll call ylim() function in three different ways:

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

Get current y-axis range

To get the range of current y-axis range we’ll have to take the two variables say left and right, so we’ll get the left value and right value of the range, and then we’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, 10) 
y = np.array([2, 4, 6, 8, 9, 10, 12, 14, 16])

# Plot


plt.plot(x, y) 

# Get and print current axes


bottom,top = plt.ylim()

print("Bottom value:",left,"\n","Top Value:",right)

# Add Title


plt.title("Get Current y-axis range") 

# Add Axes Labels

plt.xlabel("X-axis") 
plt.ylabel("Y-axis") 

# Display

plt.show()
  • Firstly, we import matplotlib.pyplot, and numpy library.
  • Next, we define data coordinates for plotting using arange() and array() method of numpy.
  • plt.plot() method is used to plot the graph.
  • Next, take two variables bottom and top, and then take the ylim() function without any argument to return the current y-axis range.
  • Then 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 use the xlabel() and ylabel() functions.
  • To display the graph, we use the show() method.
matplotlib set y axis range call
plt.ylim()

Change current y-axis range

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

Syntax:

matplotlib.pyplot.ylim(bottom_value,top_value)

Let’s see an example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = [1, 2, 3, 4, 5]
y = [5, 10, 15, 20, 25]

# Change current axes

plt.ylim(10, 30)

# Plot

plt.plot(x,y,'-o')

# Display

plt.show()

Here we use the ylim() function to set the limits of the y-axis 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 use the ylim() function to change the axes range of the y-axis bypassing the bottom and top as keyword arguments instead of taking arguments.

READ:  How to Remove Background From Image in Python

Syntax:

matplotlib.pyplot.ylim(bottom=value, top=value)

Let’s see an example:

# Import Library


import matplotlib.pyplot as plt
import numpy as np

# Define data coordinates


x = np.linspace(20, 10, 100)
y = np.tan(x)

# Change axes with keyword arguments


plt.ylim(bottom=-150, top=150)

# Plot


plt.plot(x, y)

# Display

plt.show()
  • Here we first import matplotlib.pyplot and numpy libraries.
  • Next, we define data coordinates, using linespace() and tan() function of numpy.
  • To change the limit of axes, we use the ylim() function with keyword arguments bottom and top and set their values. Here we set the bottom value as -150 and the top value as 150.
  • To plot the line graph, we use the plot() function.
matplotlib set y axis range by calling
plt.ylim(bottom=-150, top=150)

Read: Matplotlib Pie Chart Tutorial

Matplotlib set y axis max value

Here we’ll learn to set or get the limit of the maximum value i.e top value of the y-axis. Let’s see different examples:

Example #1

In this example, we’ll get the top limit of the y-axis and for this, we’ll take the variable top, and then we call the ylim() function without any argument.

Syntax:

top=matplotlib.pyplot.ylim()

Source Code:

# Import Library

import numpy as np 
import matplotlib.pyplot as plt

# Data Coordinates

x = [3, 6, 9, 12, 15]
y = [5.5, 8, 10.5, 23, 12]

# Plot

plt.plot(x, y) 

# Get and print current axes


bottom,top= plt.ylim()

print("Top value:",top)

# 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 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 as np 
import matplotlib.pyplot as plt

# Data Coordinates

x = np.linspace(0, 30, 150)
y = np.sin(x)

# Plot


plt.plot(x, y) 

# Set top axes

plt.ylim(top=1.85)

# Display

plt.show()
matplotlib set y axis max value
plt.ylim(top=1.85)

Read: Matplotlib scatter plot color

Matplotlib set y axis min value

Here we’ll learn to set or get the minimum limits of the y-axis. Let’s see different examples:

Example #1

In this example, we’ll get the minimum i.e. bottom limit of the y-axis. For this, we’ll take the variable bottom, and then we call the ylim() function without any argument. And after this, we print the bottom 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)

# Get and print current axes

bottom,top= plt.ylim()

print("Bottom Value:",bottom)

# Display


plt.show()
matplotlib set y axis min value
bottom=plt.ylim()

Example #2

In this example, we’ll set the bottom y-axis, and for this, we’ll pass an argument to the ylim() function and it automatically take it as a bottom value.

Syntax:

matplotlib.pyplot.ylim(value)

Source Code:

# Import Libraries


import matplotlib.pyplot as plt
import numpy as np

# Define Data


x = np.random.randint(low=1, high=20, size=25)

# Plot

plt.plot(x,linewidth=3, linestyle='dashed')

# y-axis limits

plt.ylim(-1)

# Display

plt.show()
matplotlib set min value of y-axis
plt.ylim(-1)

Read: Matplotlib set_xticks – Detailed tutorial

Matplotlib set y axis log scale

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

Example:

# Import Library


import matplotlib.pyplot as plt

# Define Data

data = [10**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 import matplotlib.pyplot library.
  • Next, we define data coordinates.
  • Then we convert y-axis scale to log scale, by using yscale() function.
  • To plot the graph, we use plot() function.
  • To set the limits of y-axis, we use ylim() function.
  • To display the graph, we use show() function.
matplotlib set y axis range log scale
plt.ylim()

Read: Matplotlib fill_between – Complete Guide

READ:  Matplotlib is currently using agg a non-gui backend

Matplotlib scatter set y axis range

Here we’ll set the limit of the y-axis 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-axis we use the ylim() function.

Example:

# Import Library


import matplotlib.pyplot as plt
import numpy as np

# Define Data


x = [2, 6, 3, 5, 10, 9.5]
y = [20, 13, 15.6, 25, 6, 21]

# Plotting


plt.scatter(x, y)

# Set axes


plt.ylim(bottom=5,top=20)

# Add label


plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')

# Display

plt.show()

Below output is with default y-axis limits:

matplotlib scatter set y axis range
plt.scatter()

Now let’s see the output where we alter the y-axis limits:

matplotlib scatter plot set y axis range
plt.ylim(bottom=5,top=20)

Read: Matplotlib set_yticklabels – Helpful Guide

Matplotlib set y axis range subplot

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

Example:

# Importing Libraries

import numpy as np
import matplotlib.pyplot as plt

# Create subplot

fig, ax = plt.subplots(1, 2)

# Define Data


x1= [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= [5, 10, 16, 20, 25]

# Plot graph


ax[0].plot(x1, y1)
ax[1].plot(x2, y2)

# Limit axes


ax[1].set_ylim(5,16)

# Add space

fig.tight_layout()

# Display Graph


plt.show()
  • Firstly, we import numpy and matplotlib.pyplot libraries.
  • After this, we create a subplot using subplots() function.
  • Then we create x and y data coordinates for both the plots.
  • To plot a graph, we use the plot() function of the axes module.
  • Here we change the x-axis limit of 1st subplot by using the set_ylim() function. It ranges between 5 to 16.
  • To auto-adjust the space between subplots, we use the tight_layout() function.
  • To display the graph, we use the show() function.
matplotlib set y axis range subplot
a[1].set_ylim()

Read: Matplotlib tight_layout – Helpful tutorial

Matplotlib histogram set y axis range

Here we’ll learn to set the limit of the y-axis in the histogram.

Example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.random.normal(200, 10, 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 set the top or maximum limit of the y-axis.
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 set y axis range

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

Example:

# Import Library

import matplotlib.pyplot as plt

# Define Data


x = ['Comdey', 'Action', 'Romance', 'Drama']
y = [4, 5.5, 7.6, 3]

# Plot Histogram


plt.bar(x,y)

# Set limits

max_ylim = max(y) + 1.5
min_ylim = min(y) - 1
plt.ylim(min_ylim, max_ylim)

# Display

plt.show()
  • Import matplotlib.pyplot library.
  • Next, create a list of data points.
  • To plot a bar chart, use the bar() function.
  • Define two 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 use the ylim() function.
  • To display the figure, use the show() 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.

Let’s see examples related to this:

Example #1

In this example, we’ll use ylim() method to set axis range.

# Import libraries


import matplotlib.pyplot as plt
import numpy as np

# Figure size

fig = plt.figure(figsize =(8,6))
 
# Dataset

np.random.seed(50)
data = np.random.normal(100, 20, 200) 
 
# Creating plot


plt.boxplot(data)

# Set y-axis range

plt.ylim(0,200)
 
# Show plot

plt.show()
  • Firstly, we import matplotlib.pyplot and numpy libraries.
  • Next, we set the figure size by using figure() method and figsize argument.
  • Then, we use seed() method and random.normal() method of numpy for defining data coordinates.
  • To plot the boxplot graph, we use boxplot() method.
  • To see the range of y-axis, we use ylim() method.
  • To display the figure, we use show() function.
matplotlib boxplot y axis range
Original Plot
matplotlib boxplot y axis limit
Matplotlib boxplot y-axis limit

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

READ:  Create PyTorch Empty Tensor

Example #2

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

# Import libraries

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Define Data 

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.axis([None, None, -0.75, 1.5])

# Display

plt.show()
  • Import pandas library as pd for data creation.
  • Also, import numpy library as np for data creation.
  • Then, import matplotlib.pyplot library as plt for data visualization.
  • Then, use DataFrame() function to create data frame.
  • To define the data coordinate, use random.rand() function.
  • To plot the boxplot, use boxplot() function.
  • To set the y-axis limit, we use axis() method and we set xmin and xmax to None and ymin and ymax to -0.75 and 1.5 respectively.
  • To display the plot, use plot() function.
matplotlib set y axis range boxplot
Matplotlib set y-axis range boxplot

Read: Matplotlib 2d surface plot

Matplotlib y axis range setp

Here we’ll learn how we can use setp() function for setting y-axis range using matplotlib.

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

The following is the syntax:

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

The following are the parameter used:

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

Let’s see examples related to this:

Example #1

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

# Import Libraries

import matplotlib.pyplot as plt
import numpy as np

# Define Data 

x = np.arange(50)
y = np.sin(x)

# Plot

plt.plot(x, y)

# Set limit

plt.setp(plt.gca(),ylim=(0,1))

# Display

plt.show()
  • Import matplotlib.pyplot library for data visualization.
  • Import numpy library for data creation.
  • To define x and y data coordinates, use arange() and sin() function of numpy.
  • To plot a graph, use plot() function.
  • To set the axis limit, we use setp() function and to represent the object we use gca() function of pyplot module.
  • We also pass the ylim() function with minium and maximum value to setp() function to set y-axis range.
  • To visualize a plot on user’s screen, use show() function.
matplotlib y axis range setp
Matplotlib y axis range setp

Example #2

# Import Libraries

import matplotlib.pyplot as plt
import numpy as np

# Define Data 

name = ['Ava', 'Noah', 'Charlotte', 'Robert', 'Patricia']
weight_kg = [45, 60, 50, 75, 53]

# Plot

plt.bar(name, weight_kg)

# Set y-axis

plt.setp(plt.gca(), ylim=(0, 100))

# Display

plt.show()
  • Import necessary libraries such as numpy and matplotlib.pyplot.
  • Next, define the data coordinates to plot the graph.
  • To create a bar chart, use bar() function.
  • To set the axis limit, we use setp() function with ylim() function.
  • To display the graph, use show() function.
matplotlib y axis range using setp
Matplotlib y axis range using setp

You may also like to read the following Matplotlib tutorials.

So, in this Python tutorial, we have 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 axis range
  • Matplotlib set y axis range call
  • Matplotlib set y axis max value
  • Matplotlib set y axis min value
  • Matplotlib set y axis log scale
  • Matplotlib scatter set y axis range
  • Matplotlib set y axis range subplot
  • Matplotlib histogram set y axis range
  • Matplotlib bar chart set y axis range
  • Matplotlib boxplot y axis range
  • Matplotlib y axis range setp