Loading...
Loading...
Statistical visualization with pandas integration. Use for quick exploration of distributions, relationships, and categorical comparisons with attractive defaults. Best for box plots, violin plots, pair plots, heatmaps. Built on matplotlib. For interactive plots use plotly; for publication styling use scientific-visualization.
npx skill4agent add k-dense-ai/claude-scientific-skills seabornimport seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Load example dataset
df = sns.load_dataset('tips')
# Create a simple visualization
sns.scatterplot(data=df, x='total_bill', y='tip', hue='day')
plt.show()seaborn.objectsfrom seaborn import objects as so
# Declarative syntax
(
so.Plot(data=df, x='total_bill', y='tip')
.add(so.Dot(), color='day')
.add(so.Line(), so.PolyFit())
)scatterplot()lineplot()relplot()xyhuesizestylecolrow# Scatter with multiple semantic mappings
sns.scatterplot(data=df, x='total_bill', y='tip',
hue='time', size='size', style='sex')
# Line plot with confidence intervals
sns.lineplot(data=timeseries, x='date', y='value', hue='category')
# Faceted relational plot
sns.relplot(data=df, x='total_bill', y='tip',
col='time', row='sex', hue='smoker', kind='scatter')histplot()kdeplot()ecdfplot()rugplot()displot()jointplot()pairplot()xyhuestatbinsbinwidthbw_adjustfillmultiple# Histogram with density normalization
sns.histplot(data=df, x='total_bill', hue='time',
stat='density', multiple='stack')
# Bivariate KDE with contours
sns.kdeplot(data=df, x='total_bill', y='tip',
fill=True, levels=5, thresh=0.1)
# Joint plot with marginals
sns.jointplot(data=df, x='total_bill', y='tip',
kind='scatter', hue='time')
# Pairwise relationships
sns.pairplot(data=df, hue='species', corner=True)stripplot()swarmplot()boxplot()violinplot()boxenplot()barplot()pointplot()countplot()catplot()kindxyhueorderhue_orderdodgeorientkind# Swarm plot showing all points
sns.swarmplot(data=df, x='day', y='total_bill', hue='sex')
# Violin plot with split for comparison
sns.violinplot(data=df, x='day', y='total_bill',
hue='sex', split=True)
# Bar plot with error bars
sns.barplot(data=df, x='day', y='total_bill',
hue='sex', estimator='mean', errorbar='ci')
# Faceted categorical plot
sns.catplot(data=df, x='day', y='total_bill',
col='time', kind='box')regplot()lmplot()residplot()xyorderlogisticrobustciscatter_kwsline_kws# Simple linear regression
sns.regplot(data=df, x='total_bill', y='tip')
# Polynomial regression with faceting
sns.lmplot(data=df, x='total_bill', y='tip',
col='time', order=2, ci=95)
# Check residuals
sns.residplot(data=df, x='total_bill', y='tip')heatmap()clustermap()dataannotfmtcmapcentervminvmaxsquarelinewidths# Correlation heatmap
corr = df.corr()
sns.heatmap(corr, annot=True, fmt='.2f',
cmap='coolwarm', center=0, square=True)
# Clustered heatmap
sns.clustermap(data, cmap='viridis',
standard_scale=1, figsize=(10, 10))relplotdisplotcatplotg = sns.FacetGrid(df, col='time', row='sex', hue='smoker')
g.map(sns.scatterplot, 'total_bill', 'tip')
g.add_legend()g = sns.PairGrid(df, hue='species')
g.map_upper(sns.scatterplot)
g.map_lower(sns.kdeplot)
g.map_diag(sns.histplot)
g.add_legend()g = sns.JointGrid(data=df, x='total_bill', y='tip')
g.plot_joint(sns.scatterplot)
g.plot_marginals(sns.histplot)Axesax=Axesscatterplothistplotboxplotregplotheatmapfig, axes = plt.subplots(2, 2, figsize=(10, 10))
sns.scatterplot(data=df, x='x', y='y', ax=axes[0, 0])
sns.histplot(data=df, x='x', ax=axes[0, 1])
sns.boxplot(data=df, x='cat', y='y', ax=axes[1, 0])
sns.kdeplot(data=df, x='x', y='y', ax=axes[1, 1])colrowFacetGridJointGridPairGridheightaspectrelplotdisplotcatplotlmplotjointplotpairplot# Automatic faceting
sns.relplot(data=df, x='x', y='y', col='category', row='group',
hue='type', height=3, aspect=1.2)# Long-form structure
subject condition measurement
0 1 control 10.5
1 1 treatment 12.3
2 2 control 9.8
3 2 treatment 13.1# Wide-form structure
control treatment
0 10.5 12.3
1 9.8 13.1df_long = df.melt(var_name='condition', value_name='measurement')"deep""muted""pastel""bright""dark""colorblind"sns.set_palette("colorblind")
sns.color_palette("Set2")"rocket""mako""flare""crest""viridis""magma""plasma"sns.heatmap(data, cmap='rocket')
sns.kdeplot(data=df, x='x', y='y', cmap='mako', fill=True)"vlag""icefire""coolwarm""Spectral"sns.heatmap(correlation_matrix, cmap='vlag', center=0)# Create custom palette
custom = sns.color_palette("husl", 8)
# Light to dark gradient
palette = sns.light_palette("seagreen", as_cmap=True)
# Diverging palette from hues
palette = sns.diverging_palette(250, 10, as_cmap=True)set_theme()# Set complete theme
sns.set_theme(style='whitegrid', palette='pastel', font='sans-serif')
# Reset to defaults
sns.set_theme()"darkgrid""whitegrid""dark""white""ticks"sns.set_style("whitegrid")
# Remove spines
sns.despine(left=False, bottom=False, offset=10, trim=True)
# Temporary style
with sns.axes_style("white"):
sns.scatterplot(data=df, x='x', y='y')"paper""notebook""talk""poster"sns.set_context("talk", font_scale=1.2)
# Temporary context
with sns.plotting_context("poster"):
sns.barplot(data=df, x='category', y='value')# Good: Named columns in DataFrame
df = pd.DataFrame({'bill': bills, 'tip': tips, 'day': days})
sns.scatterplot(data=df, x='bill', y='tip', hue='day')
# Avoid: Unnamed arrays
sns.scatterplot(x=x_array, y=y_array) # Loses axis labelsscatterplotlineplotkdeplotregplotviolinplotboxplotstripplotswarmplothistplotkdeplotecdfplotheatmapclustermappairplotjointplot# Instead of manual subplot creation
sns.relplot(data=df, x='x', y='y', col='category', col_wrap=3)
# Not: Creating subplots manually for simple facetinghuesizestylesns.scatterplot(data=df, x='x', y='y',
hue='category', # Color by category
size='importance', # Size by continuous variable
style='type') # Marker style by type# Lineplot computes mean and 95% CI by default
sns.lineplot(data=df, x='time', y='value',
errorbar='sd') # Use standard deviation instead
# Barplot computes mean by default
sns.barplot(data=df, x='category', y='value',
estimator='median', # Use median instead
errorbar=('ci', 95)) # Bootstrapped CIax = sns.scatterplot(data=df, x='x', y='y')
ax.set(xlabel='Custom X Label', ylabel='Custom Y Label',
title='Custom Title')
ax.axhline(y=0, color='r', linestyle='--')
plt.tight_layout()fig = sns.relplot(data=df, x='x', y='y', col='group')
fig.savefig('figure.png', dpi=300, bbox_inches='tight')
fig.savefig('figure.pdf') # Vector format for publications# Quick overview of all relationships
sns.pairplot(data=df, hue='target', corner=True)
# Distribution exploration
sns.displot(data=df, x='variable', hue='group',
kind='kde', fill=True, col='category')
# Correlation analysis
corr = df.corr()
sns.heatmap(corr, annot=True, cmap='coolwarm', center=0)sns.set_theme(style='ticks', context='paper', font_scale=1.1)
g = sns.catplot(data=df, x='treatment', y='response',
col='cell_line', kind='box', height=3, aspect=1.2)
g.set_axis_labels('Treatment Condition', 'Response (μM)')
g.set_titles('{col_name}')
sns.despine(trim=True)
g.savefig('figure.pdf', dpi=300, bbox_inches='tight')# Using matplotlib subplots with seaborn
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
sns.scatterplot(data=df, x='x1', y='y', hue='group', ax=axes[0, 0])
sns.histplot(data=df, x='x1', hue='group', ax=axes[0, 1])
sns.violinplot(data=df, x='group', y='y', ax=axes[1, 0])
sns.heatmap(df.pivot_table(values='y', index='x1', columns='x2'),
ax=axes[1, 1], cmap='viridis')
plt.tight_layout()# Lineplot automatically aggregates and shows CI
sns.lineplot(data=timeseries, x='date', y='measurement',
hue='sensor', style='location', errorbar='sd')
# For more control
g = sns.relplot(data=timeseries, x='date', y='measurement',
col='location', hue='sensor', kind='line',
height=4, aspect=1.5, errorbar=('ci', 95))
g.set_axis_labels('Date', 'Measurement (units)')g = sns.relplot(data=df, x='x', y='y', hue='category')
g._legend.set_bbox_to_anchor((0.9, 0.5)) # Adjust positionplt.xticks(rotation=45, ha='right')
plt.tight_layout()sns.relplot(data=df, x='x', y='y', height=6, aspect=1.5)fig, ax = plt.subplots(figsize=(10, 6))
sns.scatterplot(data=df, x='x', y='y', ax=ax)# Use a different palette
sns.set_palette("bright")
# Or specify number of colors
palette = sns.color_palette("husl", n_colors=len(df['category'].unique()))
sns.scatterplot(data=df, x='x', y='y', hue='category', palette=palette)# Adjust bandwidth
sns.kdeplot(data=df, x='x', bw_adjust=0.5) # Less smooth
sns.kdeplot(data=df, x='x', bw_adjust=2) # More smoothfunction_reference.mdobjects_interface.mdexamples.md