In this Python Matplotlib tutorial, we’ll discuss the Matplotlib legend font size. Here we’ll cover different examples related to legend font size using matplotlib in Python. And we’ll also cover the following topics:
- Matplotlib legend font size
- Matplotlib bar chart legend font size
- Matplotlib default legend font size
- Matplotlib legend title font size
Matplotlib legend font size
Matplotlib is a Python package that allows you to create interactive visualizations. Matplotlib’s legend() method describes the plot’s elements. We will learn to change the legend font size in Matplotlib in this article.
The following syntax is used to add a legend to a plot:
matplotlib.pyplot.legend(*args, **kwa)
In the following ways we can change the font size of the legend:
- The font size will be used as a parameter.
- To modify the font size in the legend, use the prop keyword.
- To make use of the rcParams method.
Integer or float values can be used for the font size option. But we can also use ‘xx-small’, ‘x-small’,’small’,’medium’, ‘large’, ‘x-large’, ‘xx-large’ string values as font size.
Font size as Parameter
Here we’ll learn to change the font size of the legend by using the font size parameter.
The syntax is as below:
matplotlib.pyplot.legend([labels], fontsize)
Let’s see examples related to this:
Example #1
In this example, we’ll see the default size of the legend.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.linspace(0, 8, 100)
y = np.exp(x/2)
# Plot
plt.plot(x, y, color='green', label='Exp(x)')
# Add legend
plt.legend()
# Add title
plt.title("Default Legend Size")
# Add labels
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# Display
plt.show()
- For data visualisation, import the matplotlib.pyplot library as a plt.
- For data creation, import the numpy library as np.
- We use the linspace() and exp() functions to define data coordinates.
- The plot() function is used to create a line chart.
- The legend() method is used to add a legend to the plot.
- The title() function is used to add a title to the plot.
- We use xlabel() and ylabel() to add labels to the x- and y-axes, respectively.
- The show() function is used to display the figure.
In this above output, we’ll see the legend with the default font size.
Example #2
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.linspace(0, 8, 100)
y = np.exp(x/2)
# Plot
plt.plot(x, y, color='green', label='Exp(x)')
# Add legend
plt.legend(fontsize=18)
# Add title
plt.title("Fontsize Parameter To change Legend Size")
# Add labels
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# Display
plt.show()
- Here we set the legend to the plot, by passing label argument to the plot() function.
- To show the legend to the plot, we use legend() function.
- To change the legend size, we pass fontsize argument to legend method and set its size to 18.
Change font size using prop keyword
In matplotlib, we can change the font-size property of legend by using the prop argument.
The syntax is as below:
matplotlib.pyplot.legend([labels], prop={'size':10})
Let’s see examples related to this:
Example #1
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.linspace(0, 10, 100)
y1 = np.sin(x/2)
y2 = np.cos(x/2)
# Plot
plt.plot(x, y1, label='Sin')
plt.plot(x, y2, label='Cos')
# Add legend
plt.legend(prop={'size':15})
# Add title
plt.title("Prop Parameter To change Legend Size")
# Add labels
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# Display
plt.show()
- Firstly, we import necessary libraries such as matplotlib.pyplot and numpy.
- To define data coordinates, we use linspace(), sin(), and cos() functions.
- To plot a line chart, we use plot() function.
- To add a legend to the plot, we use legend() function.
- To modify the size of legend label text, we pass prop argument to legend method. We pass size as a key and 15 as value to prop dict.
- To add a title, we use title() function.
- To add labels at axes, we use xlabel() and ylabel() function.
- To visualize the graph on user’s screen, we use show() function.
Example #2
# Import Libraries
import matplotlib.pyplot as plt
from numpy.random import random
# Define color data
colors = ['maroon', 'teal', 'yellow']
# Plot
data1 = plt.scatter(random(30), random(30), marker='d',
color=colors[0],label='Label 1')
data2 = plt.scatter(random(50), random(50), marker='d',
color=colors[1],label='Label 2')
data3 = plt.scatter(random(25), random(25), marker='d',
color=colors[1],label='Label 3')
data4 = plt.scatter(random(20), random(20), marker='d',
color=colors[2],label='Label 4')
data5 = plt.scatter(random(10), random(10), marker='d',
color=colors[0],label='Label 5')
# Add legend
plt.legend(loc='upper center', prop={'size':13.89},
bbox_to_anchor=(0.5, -0.08), ncol=2)
# Display
plt.show()
- Import matplotlib.pyplot library for data visualization.
- Import random from numpy.
- Next, we define colors list.
- Then, we use scatter() function for plotting.
- To enchane the plot, we pass marker, color, and label parameter.
- To show legend at the plot, we use legend() function.
- To glorify the legend, we pass loc, bbox_to_anchor, and ncol as parameter.
- To change the size of the legend text, we pass prop dict with size key as a argument to the legend function.
rcParams method
The matplotlib.rcparams variable is a dictionary-like variable that contains all of the settings for modifying default parameters. Using keyword arguments, the matplotlib.rc() function can be used to adjust various settings.
The syntax is as below:
matplotlib.pyplot.rc(group, **kwargs)
Let’s see an example:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x = [2, 3, 4, 5, 6, 7, 8, 9]
y1 = [4, 9, 16, 25, 36, 49, 64, 81]
y2 = [8, 27, 64, 125, 216, 343, 512, 729]
# Plot
plt.plot(x, y1, label='Square')
plt.plot(x, y2, label='Cube')
# Size
plt.rc('legend', fontsize=21)
# Add legend
plt.legend()
# Add title
plt.title("rcParams To change Legend Size")
# Add labels
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
# Display
plt.show()
- Import matplotlib.pyplot library as plt.
- Next, we define data coordinates.
- To plot a graph between coordinates, we use plot() function.
- To add a legend to a graph, we use legend() function and the labels of legend are defined in plot function.
- To change the default size of legend text, we use rc() method and pass a keyword argument fontsize.
- To add a title to the plot, we use title() function.
- To add label at x-axis, we use xlabel() function.
- To add label at y-axis, we use ylabel() function.
Read: Matplotlib scatter plot legend
Matplotlib bar chart legend font size
Here, we’ll learn to change the legend font size of the bar plot using matplotlib.
Let’s see examples related to this:
Example #1
In this example, we specify the font size by using a number.
# Import Library
import numpy as np
import matplotlib.pyplot as plt
# Set figure size
plt.figure(figsize=(7.5,4))
# Define Data
team = ['Team 1','Team 2','Team 3','Team 4','Team 5']
won = [15, 10, 30, 20, 25]
lose = [5, 20, 15, 16, 13]
x_axis = np.arange(len(team))
# Multi bar Chart
plt.bar(x_axis -0.2, won, width=0.4, label = 'Match_Won')
plt.bar(x_axis +0.2, lose, width=0.4, label = 'Match_Lose')
# Xticks
plt.xticks(x_axis, team)
# Add labels
plt.xlabel("Team", fontsize=12, fontweight='bold')
plt.ylabel("Matches", fontsize=12, fontweight='bold')
# Add legend
plt.legend(fontsize=18)
# Display
plt.show()
- Import numpy library for data creation.
- Import matplotlib.pyplot for data visualization.
- To set the figure size, we pass figsize parameter to the figure() method.
- After this, we define data for plotting.
- To generate a range of values, use the np.arange() method.
- The plt.bar() function is then used to create multiple bar charts.
- To avoid overlapping, we move the bars -0.2 and 0.2 units farther from the x-axis.
- The width of the bars was then fixed to 0.4.
- To specify the ticks at x-axis, we use xticks() function.
- To add labels at axes, we use xlabel() and ylabel() function.
- To add legend to a plot, we use legend() function.
- To change the font size of the text in the legend we specify font size by using a number.
Example #2
In this example, we specify the font size by using a string.
# Import Library
import matplotlib.pyplot as plt
# Define Data
Class = ["First", "Second", "Third", "Fourth", "Fifth"]
Males = [15, 20, 16, 18, 25]
Females = [10, 12, 5, 9, 15]
# Define height of stacked chart
h = 0.6
# Plot stacked bar chart
plt.barh(Class, Males, h, label='Males')
plt.barh(Class, Females, h, left=Boys, label='Females')
# Set fontsize of legend
plt.legend(fontsize='x-small')
# Display
plt.show()
- We import the matplotlib.pyplot package in the example above.
- The data and height of the bars are then defined.
- Then, using the plt.barh() method, we create bar chart and then we pass left as a parameter to convert this simple bar into stacked.
- To add a legend to a plot, we use legend() function.
- To change the font size of the text in the legend we specify font size by using a string.
Here we set the font size to extra small i.e. x-small.
Also, check: Put legend outside plot matplotlib
Matplotlib default legend font size
Above, we learn to change the default font size of the legend text. So, here, we’ll see more examples related to this.
Example #1
# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
# Create subplot
fig, ax = plt.subplots()
# Define Data
x = np.linspace(0, 5, 250)
y1 = np.cos(x)
y2 = np.sin(x)
# Plot
ax.plot(x, y1, '--b', label ='Cos')
ax.plot(x, y2, c ='r', label ='Sin')
# Set axes
ax.axis('equal')
# Default legend fontsize
plt.rc('legend',fontsize='xx-large')
# Legend
ax.legend();
# Show
plt.show()
- Import numpy and matplotlib.pyplot python libraries.
- To create a subplot, we use subplots() function.
- To define data coordinates, we use linspace(), cos(), and sin() function.
- To plot a line chart, we use plot() function.
- Then, we set axes to equal by using axis() function.
- To set default fontsize of legend, we use rc() method and pass fontsize as a keyword argument.
- To add a legend to the plot, we use legend() function.
Example #2
Here, we’ll use rc.params.update() function to specify the default legend font size.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.linspace(0, 20, 100)
y = np.cos(x)
# Plot graph
plt.plot(x, y, label="cos(x)")
# Default legend fontsize
plt.rcParams.update({'legend.fontsize': 18})
# Legend
plt.legend()
# Display
plt.show()
- Import necessary libraries such as, numpy and matplotlib.
- Then, define the x and y data coordinates.
- To define data coordinates, we use linspace() and cos() function of numpy.
- To plot a graph between data coordinates, we use the plot() function.
- Next, plt.rcParams.update() uses the dictionary params to update the Matplotlib properties and styles.
- The matplotlib legend font size is specified by legend.fontsize parameter.
- To show the legend to the plot, we use the legend() function.
- To display the plot, we use the show() function.
Example #3
Here we update the rcParams dictionary by putting the key in the parentheses [].
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Legend font size
plt.rcParams['legend.fontsize'] = 'xx-large'
# Define Data
x = np.linspace(0, 20, 100)
y = np.tan(x)
# Plot graph
plt.plot(x, y, label="tan(x)")
# Legend
plt.legend()
# Display
plt.show()
- Import matplotlib.pyplot as plt for data visualization.
- Import numpy as np for data creation.
- To set the legend font size, we use rcParams dictionary and putting the key in the parentheses []. Here the key is legend.fontsize.
- To define x and y data coordinates, we use the linspace() and tan() function.
- To plot a chart, we use the plot() function.
- To a legend to the plot, we use the legend() function.
- To visualize the plot on user’s screen, we use the show() function.
Read: Matplotlib increase plot size
Matplotlib legend title font size
We’ll use matplotlib to change the size of the legend’s title font. There is no title by default. We must pass a title argument to the legend function to set a title.
Let’s see examples related to this:
Example #1
In this example, we’ll learn to change the title size of legend globally.
# Import Libraries
import matplotlib.pyplot as plt
import numpy as np
# Legend Font Size
plt.rcParams['legend.title_fontsize'] = 'x-large'
# Define Data
x = np.random.randint(low = 0, high = 60, size = 50)
y = np.random.randint(low = -15, high = 80, size = 50)
# Plot
plt.plot(x, color='slategrey', label='Line 1')
plt.plot(y, color= '#EE1289', linestyle = ':', label='Line 2')
# Legend
plt.legend(fontsize='small',title='Legend Title')
# Display
plt.show()
- Firstly, we import necessary libraries such as numpy and matplotlib.pyplot for data creation and data visualization respectively.
- Then, we change the legend title font size globally by using plt.rcParams dictionary and legend.title_fontsize key in the parentheses.
- After this, we use random.randint() function of numpy for data defining.
- To plot the line chart, we use the plot() function.
- To glorify the plot we pass color , linestyle as parameter to set color and linestyle of lines.
- To set the legend on the plot, we pass legend() function.
- To change the font size of legend text, we pass fontsize as parameter.
- To add title to the legend, we pass title as parameter.
- To display the plot on user’s screen, we use show() function.
Example #2
In this example, we’ll use the title_fontsize argument to change the size of the legend’s title.
# Import Library
import matplotlib.pyplot as plt
# Set figure size
plt.figure(figsize=(6,5))
# Define Data Coordinates
popularity = [45, 14, 13, 7, 21]
emojis = ['Happy Face', 'Sad Face', 'Hearts', 'Hand Gestures',
'Others']
# Plot
plt.pie(popularity)
# Legend
plt.legend(labels=emojis,bbox_to_anchor=(0.16,0.96),
ncol=2, title='EMOJIS', title_fontsize=18)
# Display
plt.show()
- Import matplotlib.pyplot library for data visualization.
- To set the size of figure, we use figure() method with figsize argument.
- After this, we define data values to be plotted.
- Then, we define list of sequence of strings which sets the label of each wedge.
- To plot a pie chart, we use the pie() function.
- To add a legend to the plot, we use legend() function and pass label parameter to it.
- We also pass the bbox_to_anchor and ncol parameters to the function to set the location of the legend with define columns in legend box.
- To set the legend’s title, we pass title parameter to the function.
- To modify the size of legend’s title, we pass the title_fontsize parameter and set it to 18.
- To display the figure, use show() function.
Example #3
In this example, we’ll change the font size of the legend’s title by using the set_fontsize argument.
# Import Library
import matplotlib.pyplot as plt
# Set axes
fig = plt.figure()
ax = fig.add_subplot(111)
# Define Data Coordinates
popularity = [20, 16, 35, 9]
# Define Label
books = ['Story Books','Comic Books', 'Puzzel Books',
'Poem Books']
# Color
colors=['rosybrown', 'moccasin', 'lightyellow', 'darkseagreen']
# Plot with different edgecolor
plt.pie(popularity, wedgeprops={'edgecolor':'maroon'},
colors=colors)
# Set title font
lg = ax.legend(labels=books,title='BOOKS',
bbox_to_anchor=(0.45,-0.1),ncol=2,
loc='center')
title = lg.get_title()
title.set_fontsize('x-large')
# Add title
plt.title('Favourite Books',fontweight='bold')
# Display
plt.show()
- Firstly, we import matplotlib library for data visualization.
- Then, as part of a subplot layout, the figure module of the matplotlib package is used to add an Axes to the figure.
- After this, we define data values to be plotted.
- Then, we define list of sequence of strings which sets the label of each wedge.
- We also define the list of colors.
- To plot a pie chart, use pie() method.
- We also define edgecolor and colors of the wedges in the pie chart.
- To set a legend with title, we use legend() method with labels and title arguments.
- Then we get the legend title, by using the get_title() function.
- To change the font size of legend’s title, we use set_fontsize() method and set it to x-large.
- To add a title to the plot, we use title() method.
- To display the figure, use show() method.
You may also like to read the following tutorials on Matplotlib.
- Matplotlib 2d surface plot
- Matplotlib time series plot
- Matplotlib not showing plot
- Matplotlib set y axis range
- Matplotlib multiple plots
- Matplotlib Pie Chart Tutorial
So, in this Python tutorial, we have discussed the “Matplotlib legend font-size” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.
- Matplotlib legend font size
- Matplotlib bar chart legend font size
- Matplotlib default legend font size
- Matplotlib legend title font size
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.