Seaborn
Seaborn
Statistical data visualization. Built on Matplotlib, high-level API.
Seaborn
Statistical data visualization. Built on Matplotlib, high-level API.
Seaborn is a Python statistical visualization library developed by Michael Waskom in 2012. Built on top of Matplotlib, it makes statistical data exploration easy with a more concise API and attractive default styles. It integrates tightly with Pandas DataFrames.
It specializes in statistical visualization. It generates distribution visualizations (histplot, kdeplot, boxplot, violinplot), categorical data plots (catplot, barplot, countplot), regression analysis (regplot, lmplot), and correlations (heatmap, pairplot) with a single line of code.
It performs multivariate analysis with FacetGrid and PairGrid. It splits data into rows/columns to generate multiple subplots, and encodes additional variables as colors with the hue parameter. It composes complex visualizations simply with Figure-level functions such as relplot, catplot, and displot.
It sets the visualization style all at once with themes (set_theme), color palettes (color_palette), and contexts (set_context). The default style is clean enough to be at the level of academic papers, so it can be used for presentations without separate customization.
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# ν
λ§ μ€μ
sns.set_theme(style="whitegrid", palette="husl", font_scale=1.1)
# μν λ°μ΄ν°
tips = sns.load_dataset("tips")
iris = sns.load_dataset("iris")
# 1. λΆν¬ μκ°ν
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# νμ€ν κ·Έλ¨ + KDE
sns.histplot(tips['total_bill'], kde=True, ax=axes[0, 0], color='steelblue')
axes[0, 0].set_title('Total Bill Distribution')
# λ°μ€νλ‘―
sns.boxplot(x='day', y='total_bill', hue='sex', data=tips, ax=axes[0, 1])
axes[0, 1].set_title('Total Bill by Day and Sex')
# λ°μ΄μ¬λ¦° νλ‘―
sns.violinplot(x='day', y='tip', data=tips, ax=axes[1, 0], inner='box')
axes[1, 0].set_title('Tip Distribution by Day')
# KDE νλ‘― (2D)
sns.kdeplot(x=tips['total_bill'], y=tips['tip'], ax=axes[1, 1], fill=True)
axes[1, 1].set_title('2D Density Plot')
plt.tight_layout()
plt.show()
# 2. νκ· λΆμ μκ°ν
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# νκ·μ μ΄ ν¬ν¨λ μ°μ λ
sns.regplot(x='total_bill', y='tip', data=tips, ax=axes[0],
scatter_kws={'alpha': 0.5}, line_kws={'color': 'red'})
axes[0].set_title('Tip vs Total Bill with Regression Line')
# μΉ΄ν
κ³ λ¦¬λ³ νκ·μ (lmplot - Figure-level)
# sns.lmplot(x='total_bill', y='tip', hue='smoker', col='time', data=tips)
# μμ°¨ νλ‘―
sns.residplot(x='total_bill', y='tip', data=tips, ax=axes[1])
axes[1].set_title('Residual Plot')
plt.tight_layout()
plt.show()
# 3. μκ΄κ΄κ³ ννΈλ§΅
plt.figure(figsize=(10, 8))
corr = iris.drop('species', axis=1).corr()
mask = np.triu(np.ones_like(corr, dtype=bool)) # μμΌκ° λ§μ€νΉ
sns.heatmap(corr, mask=mask, annot=True, fmt='.2f', cmap='coolwarm',
center=0, square=True, linewidths=.5)
plt.title('Feature Correlation Heatmap')
plt.show()
# 4. Pair Plot (λ€λ³λ κ΄κ³)
sns.pairplot(iris, hue='species', diag_kind='kde',
plot_kws={'alpha': 0.6}, height=2.5)
plt.suptitle('Iris Dataset Pair Plot', y=1.02)
plt.show()
# 5. FacetGrid (μ‘°κ±΄λΆ μκ°ν)
g = sns.FacetGrid(tips, col='time', row='smoker', hue='sex', height=4)
g.map_dataframe(sns.scatterplot, x='total_bill', y='tip')
g.add_legend()
g.fig.suptitle('Tips by Time, Smoker, and Sex', y=1.02)
plt.show()
# 6. μΉ΄ν
κ³ λ¦¬λ³ μ§κ³
plt.figure(figsize=(10, 6))
sns.barplot(x='day', y='total_bill', hue='sex', data=tips, errorbar='ci')
plt.title('Average Total Bill by Day and Sex')
plt.show()
# μ΄λ―Έμ§ μ μ₯
# plt.savefig('seaborn_plot.png', dpi=300, bbox_inches='tight')
Senior: "When doing EDA, run pairplot first. You can see the relationships between variables at a glance."
Junior: "How is it different from Matplotlib?"
Senior: "Seaborn specializes in statistical visualization, and you can use DataFrame column names as they are, so the code is much more concise. The default style is also nice."
Interviewer: "Please tell us about your experience with exploratory data analysis (EDA)."
Candidate: "I built an EDA automation function with Seaborn. It automatically generated distributions of numeric variables with histplot, frequencies of categorical variables with countplot, and correlations with heatmap, and I explored multivariate relationships with pairplot. I visualized outliers with boxplot and set the preprocessing criteria."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
Reviewer: "When you split groups with hue, setting palette lets you use colorblind-friendly colors. I recommend palette='colorblind'."
Developer: "I'll apply it right away, taking accessibility into account."