Customizing annotation with Seaborn's FacetGrid

Seaborn's FacetGrid allows you to create multiple subplots based on categorical variables and customize annotations for each subplot. You can set custom titles, labels, and other annotations to make your visualizations more informative.

Basic FacetGrid Setup

First, let's create a basic FacetGrid with custom annotations ?

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

# Set figure parameters
plt.rcParams["figure.figsize"] = [10, 4]
plt.rcParams["figure.autolayout"] = True

# Create sample data
df = pd.DataFrame({
    'values': [3, 7, 8, 1, 5, 9, 2, 6],
    'category': ["A", "B", "C", "D", "A", "B", "C", "D"],
    'group': ["X", "X", "X", "X", "Y", "Y", "Y", "Y"]
})

# Create FacetGrid
g = sns.FacetGrid(data=df, col='category', height=3)
g.map(plt.hist, 'values', color='skyblue', alpha=0.7)
g.set_titles('Category: {col_name}')

plt.show()

Advanced Title Customization

You can customize titles with more complex formatting and add statistical information ?

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

# Create sample data
df = pd.DataFrame({
    'values': [3, 7, 8, 1, 5, 9, 2, 6, 4, 7, 3, 8],
    'category': ["A", "B", "C", "D"] * 3,
    'group': ["X"] * 4 + ["Y"] * 4 + ["Z"] * 4
})

# Create FacetGrid with custom annotations
g = sns.FacetGrid(data=df, col='category', height=3.5, aspect=0.8)
g.map(plt.hist, 'values', color='coral', bins=5, alpha=0.7)

# Custom title with statistics
for ax, title in zip(g.axes.flat, df['category'].unique()):
    subset = df[df['category'] == title]
    mean_val = subset['values'].mean()
    ax.set_title(f'Category {title}\nMean: {mean_val:.1f}', fontsize=12, pad=15)
    ax.set_xlabel('Values', fontsize=10)
    ax.set_ylabel('Count', fontsize=10)

plt.tight_layout()
plt.show()

Adding Annotations to Individual Plots

You can add text annotations directly on each subplot to highlight specific information ?

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

# Create sample data
df = pd.DataFrame({
    'x': [1, 2, 3, 4, 1, 2, 3, 4],
    'y': [2, 5, 3, 8, 1, 4, 6, 7],
    'category': ["Group A", "Group A", "Group A", "Group A", 
                "Group B", "Group B", "Group B", "Group B"]
})

# Create FacetGrid with scatter plot
g = sns.FacetGrid(data=df, col='category', height=4, aspect=1)
g.map(plt.scatter, 'x', 'y', color='green', s=50, alpha=0.7)

# Add custom annotations
for ax, category in zip(g.axes.flat, df['category'].unique()):
    subset = df[df['category'] == category]
    max_y_idx = subset['y'].idxmax()
    max_point = subset.loc[max_y_idx]
    
    ax.annotate(f'Max: ({max_point["x"]}, {max_point["y"]})', 
                xy=(max_point['x'], max_point['y']), 
                xytext=(10, 10), textcoords='offset points',
                bbox=dict(boxstyle='round,pad=0.3', facecolor='yellow', alpha=0.7),
                arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
    
    ax.set_title(f'{category}', fontsize=14, fontweight='bold')

plt.tight_layout()
plt.show()

Key Customization Options

Method Purpose Example
set_titles() Set subplot titles g.set_titles('{col_name}')
set_axis_labels() Set x and y labels g.set_axis_labels('X', 'Y')
annotate() Add text annotations ax.annotate('text', xy=(x,y))
tight_layout() Adjust spacing plt.tight_layout()

Conclusion

FacetGrid customization allows you to create informative multi-panel visualizations with custom titles, labels, and annotations. Use set_titles() for basic titles and direct axis manipulation for advanced annotations.

---
Updated on: 2026-03-25T21:39:34+05:30

531 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements