How to Use the Matplotlib.pyplot.ylabel() Function in Python

09/28/2021

Contents

In this article, you will learn how to use the Matplotlib.pyplot.ylabel() function in Python.

The Matplotlib.pyplot.ylabel() Function

The matplotlib.pyplot.ylabel() function is a method provided by the matplotlib library that allows you to set the label for the y-axis in a plot. The y-axis is the vertical axis of a two-dimensional plot, and it typically represents the dependent variable of the plotted data. This function can be used to provide a name or a label to the y-axis to make the plot more informative and readable.

Here’s an example of how to use matplotlib.pyplot.ylabel() function in Python:

import matplotlib.pyplot as plt

# Create some example data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Plot the data
plt.plot(x, y)

# Add a label to the y-axis
plt.ylabel('Y-axis Label')

# Show the plot
plt.show()

In this example, we first import the matplotlib.pyplot module as plt. Then, we create two lists of data x and y, which represent the x and y coordinates of our data points. We plot these points using the plt.plot() function, which creates a line plot by default.

Next, we use the plt.ylabel() function to add a label to the y-axis. We pass a string ‘Y-axis Label’ as an argument to this function, which is used as the label for the y-axis.

Finally, we call the plt.show() function to display the plot.

The plt.ylabel() function has several parameters that you can use to customize the label, such as fontsize, fontweight, and labelpad. Here’s an example that uses some of these parameters:

import matplotlib.pyplot as plt

# Create some example data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Plot the data
plt.plot(x, y)

# Add a label to the y-axis with custom parameters
plt.ylabel('Y-axis Label', fontsize=14, fontweight='bold', labelpad=10)

# Show the plot
plt.show()

In this example, we use the fontsize parameter to set the font size of the label to 14, the fontweight parameter to set the font weight to bold, and the labelpad parameter to add a padding of 10 points between the label and the y-axis.