0
0
Matplotlibdata~5 mins

Customizing Seaborn plots with Matplotlib

Choose your learning style9 modes available
Introduction

Seaborn makes nice plots easily, but sometimes you want to change colors, labels, or add titles. Matplotlib helps you do that.

You want to add a title or axis labels to a Seaborn plot.
You want to change the size or style of text in your plot.
You want to add grid lines or change their style.
You want to save the plot with a specific size or resolution.
You want to combine Seaborn plots with other Matplotlib features.
Syntax
Matplotlib
import seaborn as sns
import matplotlib.pyplot as plt

sns_plot = sns.some_plot(data)
plt.title('Your Title')
plt.xlabel('X axis label')
plt.ylabel('Y axis label')
plt.show()

You use Matplotlib commands like plt.title() after creating a Seaborn plot.

Seaborn plots return Matplotlib axes objects you can customize further.

Examples
Adds a title to a histogram created by Seaborn.
Matplotlib
import seaborn as sns
import matplotlib.pyplot as plt

sns.histplot(data)
plt.title('Histogram of Data')
plt.show()
Changes axis labels using the axes object returned by Seaborn.
Matplotlib
import seaborn as sns
import matplotlib.pyplot as plt

ax = sns.scatterplot(x='age', y='height', data=data)
ax.set_xlabel('Age in years')
ax.set_ylabel('Height in cm')
plt.show()
Adds dashed grid lines to a boxplot.
Matplotlib
import seaborn as sns
import matplotlib.pyplot as plt

sns.boxplot(x='group', y='score', data=data)
plt.grid(True, linestyle='--')
plt.show()
Sample Program

This code creates a bar plot with Seaborn and then adds a title, axis labels, and dotted grid lines using Matplotlib.

Matplotlib
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# Sample data
 data = pd.DataFrame({
    'category': ['A', 'B', 'A', 'B', 'A', 'B'],
    'value': [5, 7, 8, 5, 6, 9]
})

# Create a bar plot
ax = sns.barplot(x='category', y='value', data=data)

# Customize with Matplotlib
plt.title('Average Value by Category')
ax.set_xlabel('Category')
ax.set_ylabel('Value')
plt.grid(True, linestyle=':')

plt.show()
OutputSuccess
Important Notes

Always call Matplotlib functions like plt.title() after creating the Seaborn plot.

You can get the axes object from Seaborn plots to customize labels and ticks.

Use plt.show() to display the final plot.

Summary

Seaborn plots can be customized using Matplotlib commands.

Use plt.title(), plt.xlabel(), and plt.ylabel() to add titles and labels.

Grid lines and other style changes are easy with Matplotlib after plotting with Seaborn.