Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to increase the font size of the legend in my Seaborn plot using Matplotlib?
When creating Seaborn plots, you might need to increase the legend font size for better readability. Seaborn uses Matplotlib under the hood, so we can use plt.legend() with the fontsize parameter to control legend text size.
Basic Example
Let's create a DataFrame and plot a bar chart with custom legend font size ?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Set figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create sample data
df = pd.DataFrame({
'number': [2, 5, 1, 6, 3],
'count': [56, 21, 34, 36, 12],
'select': [29, 13, 17, 21, 8]
})
# Create bar plots
bar_plot1 = sns.barplot(x='number', y='count', data=df, label="count", color="red")
bar_plot2 = sns.barplot(x='number', y='select', data=df, label="select", color="green")
# Set legend with custom font size
fontsize = 20
plt.legend(loc="upper right", frameon=True, fontsize=fontsize)
plt.show()
Different Font Size Options
You can use numeric values or string keywords for font sizes ?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Sample data
data = pd.DataFrame({
'category': ['A', 'B', 'C', 'D'],
'value1': [23, 45, 56, 78],
'value2': [12, 25, 33, 41]
})
# Create plot
sns.lineplot(x='category', y='value1', data=data, label='Series 1', marker='o')
sns.lineplot(x='category', y='value2', data=data, label='Series 2', marker='s')
# Using string keywords
plt.legend(fontsize='large') # Options: 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'
plt.title('Legend with Large Font Size')
plt.show()
Alternative Methods
You can also set legend properties using prop parameter ?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Sample data
df = pd.DataFrame({
'x': [1, 2, 3, 4, 5],
'y1': [10, 15, 13, 18, 16],
'y2': [8, 12, 11, 14, 13]
})
# Create scatter plot
sns.scatterplot(x='x', y='y1', data=df, label='Dataset 1', s=100)
sns.scatterplot(x='x', y='y2', data=df, label='Dataset 2', s=100)
# Using prop parameter with font dictionary
plt.legend(prop={'size': 16, 'weight': 'bold'})
plt.title('Legend with Bold Font')
plt.show()
Font Size Comparison
| Method | Syntax | Use Case |
|---|---|---|
| Numeric Value | fontsize=20 |
Precise control |
| String Keywords | fontsize='large' |
Relative sizing |
| Prop Dictionary | prop={'size': 16} |
Multiple font properties |
Conclusion
Use plt.legend(fontsize=value) to control legend font size in Seaborn plots. Choose numeric values for precise control or string keywords for relative sizing based on your visualization needs.
Advertisements
