WikiGalaxy

Personalize

Integrating Matplotlib with Seaborn

Matplotlib and Seaborn are both powerful libraries for data visualization in Python. While Matplotlib provides a solid foundation for creating static, interactive, and animated visualizations, Seaborn builds on top of Matplotlib to provide a high-level interface for drawing attractive and informative statistical graphics. Integrating these two libraries allows you to leverage the flexibility of Matplotlib while benefiting from Seaborn's aesthetic and statistical capabilities.

Basic Integration

To integrate Matplotlib with Seaborn, you typically start by setting a Seaborn style and then using Matplotlib's plotting functions alongside Seaborn's functions. This combination allows you to customize your plots extensively while maintaining a polished look.


import matplotlib.pyplot as plt
import seaborn as sns

# Set a Seaborn style
sns.set(style="whitegrid")

# Create a basic line plot using Matplotlib
plt.plot([0, 1, 2, 3], [10, 20, 25, 30], label='Line 1')

# Add a title and labels
plt.title('Basic Integration')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Display the plot
plt.show()
    

In this example, we set a Seaborn style using `sns.set()` before creating a basic line plot with Matplotlib's `plt.plot()`. This ensures that the plot has the aesthetic features provided by Seaborn, such as a grid background and improved color schemes.

Combining Seaborn and Matplotlib Plots

You can also combine Seaborn plots with Matplotlib plots in the same figure. This is particularly useful when you want to add more complex statistical plots from Seaborn to a Matplotlib figure.


import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

# Generate random data
data = np.random.normal(size=100)

# Create a figure and axis
fig, ax = plt.subplots()

# Plot a histogram using Seaborn
sns.histplot(data, kde=True, ax=ax, color='teal')

# Add a vertical line using Matplotlib
ax.axvline(x=0, color='red', linestyle='--')

# Display the plot
plt.show()
    

In this example, a histogram is plotted using Seaborn's `sns.histplot()`, which includes a kernel density estimate (KDE). We then use Matplotlib's `ax.axvline()` to add a vertical line at a specific x-value, demonstrating how to overlay Matplotlib elements on a Seaborn plot.

Customizing Seaborn Plots with Matplotlib

Seaborn plots can be customized further using Matplotlib functions. This allows for additional customization beyond what Seaborn offers by default.


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

# Load a dataset
tips = sns.load_dataset('tips')

# Create a boxplot using Seaborn
sns.boxplot(x='day', y='total_bill', data=tips)

# Customize the plot using Matplotlib
plt.title('Boxplot of Total Bill by Day')
plt.xlabel('Day of the Week')
plt.ylabel('Total Bill ($)')
plt.xticks(rotation=45)

# Display the plot
plt.show()
    

Here, a boxplot is created using Seaborn's `sns.boxplot()`, which is then customized with Matplotlib functions such as `plt.title()`, `plt.xlabel()`, `plt.ylabel()`, and `plt.xticks()` to adjust the plot's title and axis labels.

Adding Annotations to Seaborn Plots

Annotations can be added to Seaborn plots using Matplotlib's annotation functions. This is useful for highlighting specific data points or adding text to a plot.


import matplotlib.pyplot as plt
import seaborn as sns

# Load a dataset
tips = sns.load_dataset('tips')

# Create a scatter plot using Seaborn
sns.scatterplot(x='total_bill', y='tip', data=tips)

# Annotate a specific point using Matplotlib
plt.annotate('High Tip', xy=(50, 10), xytext=(30, 12),
             arrowprops=dict(facecolor='black', shrink=0.05))

# Display the plot
plt.show()
    

In this example, a scatter plot is created using Seaborn's `sns.scatterplot()`. We then use Matplotlib's `plt.annotate()` to add an annotation with an arrow pointing to a specific data point, making it easy to highlight key observations.

Faceting with Seaborn and Customization with Matplotlib

Seaborn's faceting capabilities allow you to create multiple plots based on subsets of your data. These facets can be customized further using Matplotlib.


import matplotlib.pyplot as plt
import seaborn as sns

# Load a dataset
tips = sns.load_dataset('tips')

# Create a FacetGrid using Seaborn
g = sns.FacetGrid(tips, col="sex", height=5, aspect=1)

# Map a scatter plot onto the FacetGrid
g.map(plt.scatter, "total_bill", "tip")

# Customize the FacetGrid using Matplotlib
g.set_axis_labels("Total Bill ($)", "Tip ($)")
g.add_legend()

# Display the plot
plt.show()
    

This example demonstrates the use of Seaborn's `FacetGrid` to create multiple scatter plots based on the `sex` variable in the `tips` dataset. Matplotlib functions are then used to set axis labels and add a legend, providing additional customization options.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025