How to change the font size on a matplotlib plot?

Change font size in Matplotlib: In this tutorial, we will learn how to change the font size of the different labels/texts on a Matplotlib plot? By Pranit Sharma Last updated : July 11, 2023

Matplotlib is an important library of Python programming that allows us to analyze and plot the given data samples for better understanding and fine visualization.

Set various text /label in a matplotlib plot

There are different types of text values in a plot like a plot title, axes labels, tick labels, legends, and other descriptive texts. To add these texts with default size, we can use set_title(), set_xlabel(), set_ylabel(), xticks(), yticks(), and legend() respectively.

Example

# Importing matplotlib pyplot as plt
from matplotlib import pyplot as plt

# Preparing some dataset
product = ["S20", "M71", "Yz0", "T65", "TZ2"]
sales = [243000, 20230, 21313, 32343, 424312]

# Creating a line graph with the data set
plt.title("Product and their sales")
plt.xlabel("Product")
plt.ylabel("Sales")
plt.plot(product, sales)

# Display plot
plt.show()

Output:

Output | Set various text /label

Change font size of text in a matplotlib plot

To change the font size of the text in a matplotlib plot, you can use fontsize parameter inside the specified function (whose text's font size you want to change) like set_title(), set_xlabel(), set_ylabel(), etc.

Example

Consider the below example in which we are changing the font size of the plot title text, x label text, and y label text.

# Importing matplotlib pyplot as plt
from matplotlib import pyplot as plt

# Preparing some dataset
product = ["S20", "M71", "Yz0", "T65", "TZ2"]
sales = [243000, 20230, 21313, 32343, 424312]

# Creating a line graph with the data set
plt.title("Product and their sales", fontsize=20)
plt.xlabel("Product", fontsize=16)
plt.ylabel("Sales", fontsize=16)
plt.plot(product, sales)

# Display plot
plt.show()

Output:

Output | Change font size of text in a matplotlib plot


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.