Python Notes
Learn Seaborn for beautiful statistical data visualization. Master distribution plots, categorical plots, regression plots, heatmaps, pair plots, and FacetGrid with practical data science examples.
Seaborn is a Python data visualization library built on Matplotlib that provides a high-level interface for drawing attractive statistical graphics. It comes with beautiful default themes and integrates seamlessly with Pandas DataFrames.
Installation
pip install seaborn matplotlib pandasimport seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
print(sns.__version__)Built-in Datasets
Seaborn includes several practice datasets:
import seaborn as sns
# List available datasets
print(sns.get_dataset_names())
# Load popular datasets
tips = sns.load_dataset('tips') # Restaurant tips data
iris = sns.load_dataset('iris') # Iris flowers
titanic = sns.load_dataset('titanic') # Titanic passengers
penguins = sns.load_dataset('penguins') # Palmer penguins
flights = sns.load_dataset('flights') # Flight passengers
fmri = sns.load_dataset('fmri') # fMRI brain data
print(tips.head())
print(tips.info())
print(tips.describe())Themes and Styles
Distribution Plots
histplot and kdeplot
displot — Figure-Level Distribution Plot
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
# Histogram with facets
g = sns.displot(data=tips, x='total_bill', col='time', row='sex',
kde=True, height=4, aspect=1.2)
g.set_titles('{row_name} | {col_name}')
g.set_axis_labels('Total Bill ($)', 'Count')
plt.suptitle('Bill Distribution by Meal and Gender', y=1.02, fontsize=14)
plt.show()
# Joint plot — 2D distribution
g = sns.jointplot(data=tips, x='total_bill', y='tip',
kind='scatter', hue='sex',
marginal_kws={'fill': True})
g.set_axis_labels('Total Bill ($)', 'Tip ($)')
g.figure.suptitle('Bill vs Tip with Marginal Distributions', y=1.02)
plt.show()Categorical Plots
Box and Violin Plots
Bar and Count Plots
Relational Plots
Scatter and Line Plots
Regression Plots
Heatmaps and Correlation
Pair Plots
FacetGrid — Multi-Panel Plots
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
# FacetGrid with histograms
g = sns.FacetGrid(tips, col='time', row='sex', height=3, aspect=1.3)
g.map(sns.histplot, 'total_bill', bins=20, kde=True, color='steelblue')
g.set_axis_labels('Total Bill ($)', 'Count')
g.set_titles('{row_name} | {col_name}')
g.add_legend()
plt.suptitle('Bill Distribution by Meal and Gender', y=1.02)
plt.show()
# FacetGrid with scatter
g = sns.FacetGrid(tips, col='day', height=4, aspect=0.9, col_wrap=2)
g.map_dataframe(sns.scatterplot, x='total_bill', y='tip', hue='sex', alpha=0.6)
g.set_axis_labels('Total Bill ($)', 'Tip ($)')
g.set_titles('{col_name}')
g.add_legend()
plt.suptitle('Tips by Day', y=1.02)
plt.show()Complete Dashboard Example
Summary
In this lesson, you learned:
- ✅ Setting up Seaborn themes and color palettes
- ✅ Distribution plots (histplot, kdeplot, ecdfplot, displot)
- ✅ Joint plots for bivariate distributions
- ✅ Categorical plots (boxplot, violinplot, stripplot, barplot)
- ✅ Regression plots (regplot, lmplot, residplot)
- ✅ Heatmaps and correlation visualizations
- ✅ Pair plots for multivariate exploration
- ✅ FacetGrid for multi-panel conditional plots
- ✅ Building a complete dashboard with Seaborn + Matplotlib
------ -------------- ----- 0 total_bill 244 non-null float64 1 tip 244 non-null float64 2 sex 244 non-null category 3 smoker 244 non-null category 4 day 244 non-null category 5 time 244 non-null category 6 size 244 non-null int64
total_bill tip size count 244.000000 244.000000 244.000000 mean 19.785943 2.998279 2.569672 std 8.902412 1.383638 0.951100 min 3.070000 1.000000 1.000000 25% 13.347500 2.000000 2.000000 50% 17.795000 2.900000 2.000000 75% 24.127500 3.562500 3.000000 max 50.810000 10.000000 6.000000
[(0.298, 0.447, 0.690), (0.867, 0.517, 0.321), (0.333, 0.659, 0.408), (0.769, 0.306, 0.322), (0.506, 0.447, 0.702), (0.576, 0.471, 0.376)]
📊 [Visualization: A horizontal bar showing 8 evenly spaced colors from the Viridis palette — transitioning from dark purple → blue → green → yellow]
📊 [Visualization: 2x2 grid of distribution plots]
- Top-Left: Histogram of total_bill with KDE curve overlay — right-skewed
distribution peaking around $15-20, smooth blue bars with density curve
- Top-Right: Overlapping step histograms showing Male vs Female bill distributions
— both groups show similar patterns with males having slightly higher bills
- Bottom-Left: Filled KDE curves for Lunch vs Dinner — Dinner curve is broader
and shifted right, Lunch is more concentrated around lower values
- Bottom-Right: ECDF lines for each day — all days show similar cumulative
patterns with Sunday having slightly higher bill amounts
📊 [Visualization: FacetGrid with 4 panels (2 rows × 2 columns)]
- Rows: Male/Female, Columns: Lunch/Dinner
- Each panel shows histogram with KDE of total_bill
- Dinner panels show wider distributions than Lunch panels
📊 [Visualization: Joint plot with scatter center and marginal distributions]
- Center: Scatter of total_bill vs tip, colored by sex (Male=blue, Female=orange)
- Top margin: KDE of total_bill distribution
- Right margin: KDE of tip distribution
- Clear positive correlation visible between bill and tip amounts
📊 [Visualization: 2x2 grid of categorical plots]
- Top-Left: Box plots for each day split by gender — Saturday/Sunday show
higher median bills, outliers visible above $40
- Top-Right: Split violin plots showing full distribution shape — Dinner
violins are wider indicating more variability in bill amounts
- Bottom-Left: Strip plot with individual data points — jittered to avoid
overlap, shows concentration of points between $10-30
- Bottom-Right: Swarm plot with non-overlapping points — reveals density
patterns clearly, wider swarms indicate more data points
📊 [Visualization: 1x3 row of categorical summary plots]
- Left: Grouped bar chart with error bars — Saturday has highest avg bill
(~$20), Males slightly higher than Females across all days
- Center: Count plot — Saturday and Sunday have most diners, gender split
roughly 60/40 Male/Female
- Right: Point plot with connected lines — tip trends across days, Males
and Females show different patterns (Males peak Sunday, Females peak Thursday)
📊 [Visualization: catplot with box plots in 2 panels]
- Left panel: Lunch — smokers and non-smokers have similar bill distributions
- Right panel: Dinner — smokers show slightly higher median bills with more outliers
📊 [Visualization: 1x2 row of relational plots]
- Left: Multi-encoded scatter plot — x=total_bill, y=tip, color=meal time
(Lunch=blue, Dinner=orange), size=party size (larger dots = bigger parties), style=gender (circles vs crosses). Clear positive trend visible.
- Right: Multi-line plot showing passenger counts over years — 12 colored
lines (one per month), clear upward trend with seasonal peaks in summer months
📊 [Visualization: relplot FacetGrid with 2 scatter panels]
- Left: Lunch scatter — fewer points, clustered in lower bill range
- Right: Dinner scatter — more spread out, higher bills and tips
📊 [Visualization: Regression analysis plots]
- Plot 1: Scatter with linear regression line and shaded 95% CI band —
positive slope (~0.105), tips increase ~$1 per $10 increase in bill
- Plot 2: lmplot with separate regression lines for Male/Female — similar
slopes but Males have slightly higher intercept
- Plot 3: Residual plot — points randomly scattered around y=0 horizontal
line, suggesting linear model is appropriate (no systematic pattern)
- Plot 4: Regression with wider CI band — shaded region narrows where
data is more concentrated
📊 [Visualization: 1x2 row of heatmaps]
- Left: 4x4 correlation matrix with RdBu colormap — petal_length and
petal_width highly correlated (0.96), sepal_width negatively correlated with other features (-0.42 with petal_length)
- Right: 4x6 sales heatmap — darker blue = higher sales, annotated with
actual values (range 50-300), clear patterns visible across months and products
📊 [Visualization: 4x4 pair plot matrix — Iris Dataset]
- Diagonal: KDE distributions for each feature by species (3 colored curves)
- Off-diagonal: Scatter plots showing pairwise relationships
- Clear separation between setosa (red) and other species
- Versicolor (blue) and virginica (green) overlap in some dimensions
- Strongest separation: petal_length vs petal_width
📊 [Visualization: Corner pair plot — Penguins Dataset]
- Lower triangle only (corner=True) — cleaner view
- 3 species clearly separable in most dimension pairs
- bill_length vs bill_depth shows interesting species clustering
📊 [Visualization: 2x2 FacetGrid with histograms]
- 4 panels: Male|Lunch, Male|Dinner, Female|Lunch, Female|Dinner
- Dinner panels show wider distributions
- Male|Dinner has the most data points
📊 [Visualization: 2x2 wrapped FacetGrid with scatter plots]
- 4 panels: Thur, Fri, Sat, Sun — each showing bill vs tip scatter
- Weekend days (Sat, Sun) show higher bill ranges
- Color-coded by gender with legend
📊 [Visualization: 2x3 Dashboard — Restaurant Tips Analysis]
- Panel 1: Tip distribution histogram with mean line at $3.00
- Panel 2: Bill vs Tip scatter colored by gender — clear positive trend
- Panel 3: Bar chart of avg tip by day — Sunday highest (~$3.25)
- Panel 4: Box plots of tip by meal time & smoking status
- Panel 5: Count plot of party sizes — size=2 most common
- Panel 6: 3x3 correlation heatmap — total_bill and tip correlated (0.68)
Dashboard saved!
❌ Wrong — Plot नहीं दिखेगा
sns.histplot(data=tips, x='total_bill')
Script ends without showing
✅ Right — हमेशा plt.show() लगाओ
sns.histplot(data=tips, x='total_bill') plt.show()
❌ Wrong — displot figure-level है, ax parameter नहीं लेता
fig, ax = plt.subplots() sns.displot(data=tips, x='total_bill', ax=ax) # TypeError!
✅ Right — Figure-level plots अपना figure बनाते हैं
sns.displot(data=tips, x='total_bill') plt.show()
✅ Or use axes-level equivalent
fig, ax = plt.subplots() sns.histplot(data=tips, x='total_bill', ax=ax) plt.show()
❌ Wrong — NaN values cause warnings/errors
penguins = sns.load_dataset('penguins') sns.pairplot(penguins, hue='species') # Warnings about NaN!
✅ Right — पहले NaN handle करो
penguins = sns.load_dataset('penguins').dropna() sns.pairplot(penguins, hue='species') plt.show()
❌ Wrong — continuous variable hue में = बहुत सारे colors
sns.scatterplot(data=tips, x='total_bill', y='tip', hue='size')
Creates too many legend entries!
✅ Right — categorical बनाओ या palette adjust करो
sns.scatterplot(data=tips, x='total_bill', y='tip', hue='size', palette='viridis') plt.show()
❌ Wrong — Labels overlap हो जाते हैं
sns.barplot(data=tips, x='day', y='total_bill') plt.title('A Very Long Title That Goes On And On And On')
✅ Right — tight_layout() या adjust करो
sns.barplot(data=tips, x='day', y='total_bill') plt.title('Average Bill by Day') plt.tight_layout() plt.show()
❌ Wrong — set_theme सभी plots को affect करता है
sns.set_theme(style='dark') # This changes EVERYTHING after this line
✅ Right — Temporary style change के लिए context manager
with sns.axes_style('dark'): sns.histplot(data=tips, x='total_bill') plt.show()
Outside the block, original style is restored
❌ Wrong — swarmplot 1000+ points पर बहुत slow है
big_data = pd.DataFrame({'x': ['A']*5000, 'y': np.random.randn(5000)}) sns.swarmplot(data=big_data, x='x', y='y') # Very slow!
✅ Right — Large data के लिए violin/box plot use करो
sns.violinplot(data=big_data, x='x', y='y') plt.show()
| ### Q1 | Seaborn और Matplotlib में क्या difference है? 🤔 |
| **Answer | ** Matplotlib low-level library है — हर चीज़ manually configure करनी पड़ती है। Seaborn high-level wrapper है जो Matplotlib के ऊपर बना है। Seaborn automatically beautiful defaults देता है, statistical computations करता है (mean, CI, KDE), और Pandas DataFrames के साथ seamlessly work करता है। Think of it as: Matplotlib = manual car, Seaborn = automatic car 🚗 |
| ### Q2 | Figure-level और Axes-level plots में क्या difference है? 📊 |
| **Answer | ** **Axes-level** (histplot, boxplot, scatterplot) — existing matplotlib axes पर draw करते हैं, `ax=` parameter accept करते हैं, subplot layouts में use कर सकते हो। **Figure-level** (displot, catplot, relplot) — अपना figure + FacetGrid बनाते हैं, `col=` और `row=` parameters से automatic faceting support करते हैं, लेकिन `ax=` parameter नहीं लेते। |
| ### Q3 | Seaborn में color palette कैसे customize करें? 🎨 |
| **Answer | ** Multiple ways हैं: |
| - Named palettes | `'deep'`, `'muted'`, `'bright'`, `'pastel'`, `'dark'`, `'colorblind'` |
| ### Q4 | Large dataset पर Seaborn slow है — क्या करें? ⚡ |
| **Answer | ** कुछ tips: |
| 4. Data sample करो | `data.sample(1000)` |
| ### Q5 | Seaborn plot को save कैसे करें? 💾 |
| **Answer | ** Seaborn Matplotlib पर built है, तो same methods work करते हैं: |
Axes-level plots
sns.histplot(data=tips, x='total_bill') plt.savefig('plot.png', dpi=300, bbox_inches='tight')
Figure-level plots
g = sns.displot(data=tips, x='total_bill') g.savefig('plot.png', dpi=300, bbox_inches='tight')
| Supported formats | PNG, PDF, SVG, JPG। `dpi=300` publication quality के लिए enough है। |
| ### Q6 | Seaborn plots में font size कैसे बदलें? 🔤 |
| **Answer | ** `sns.set_theme(font_scale=1.5)` सबसे easy way है — सभी text elements proportionally बढ़ जाते हैं। Individual elements के लिए: `plt.title('Title', fontsize=16)`, `plt.xlabel('X', fontsize=12)`। या `sns.set_context('talk')` / `sns.set_context('poster')` use करो predefined sizes के लिए। |
| ### Q7 | Seaborn में subplots कैसे बनाएं? 📐 |
| **Answer | ** Two approaches: |
fig, axes = plt.subplots(1, 2, figsize=(12, 5)) sns.histplot(data=tips, x='total_bill', ax=axes[0]) sns.boxplot(data=tips, x='day', y='tip', ax=axes[1])
sns.catplot(data=tips, x='day', y='tip', col='time', kind='box')
| ### Q8 | Seaborn 0.12+ में क्या major changes आए? 🆕 |
| **Answer | ** Key changes: |
| ### Q1 | Seaborn और Matplotlib में fundamental difference explain करो। Production projects में कब कौन use करोगे? |
| **Answer | ** Seaborn Matplotlib के ऊपर built high-level statistical visualization library है। |
| **Key differences | ** |
| - **Abstraction Level | ** Matplotlib low-level है (fine-grained control), Seaborn high-level (fewer lines, better defaults) |
| - **Statistics | ** Seaborn automatically confidence intervals, KDE, regression lines compute करता है |
| - **DataFrames | ** Seaborn Pandas DataFrames natively support करता है — column names directly use कर सकते हो |
| - **Aesthetics | ** Seaborn के defaults publication-ready हैं, Matplotlib manually style करना पड़ता है |
| **When to use | ** |
| - **Seaborn** | EDA, statistical analysis, quick beautiful plots, categorical data |
| - **Matplotlib** | Custom animations, 3D plots, highly customized layouts, non-standard plot types |
| - **Both together** | Seaborn for the plot + Matplotlib for fine-tuning (labels, annotations, layout) |
| ### Q2 | Figure-level और Axes-level functions का architectural difference explain करो। |
| **Answer | ** |
| - **Axes-level** (`histplot`, `boxplot`, `scatterplot`) | ये एक specific matplotlib Axes object पर draw करते हैं। `ax=` parameter accept करते हैं। Return value matplotlib Axes object है। इन्हें `plt.subplots()` layouts में freely use कर सकते हो। |
| - **Figure-level** (`displot`, `catplot`, `relplot`) | ये internally FacetGrid create करते हैं जो अपना figure manage करता है। `col=`, `row=` parameters से automatic faceting support करते हैं। Return value FacetGrid object है। `ax=` parameter accept नहीं करते। |
| **Architecture | ** Figure-level functions internally axes-level functions call करती हैं within a FacetGrid framework — यह Composite design pattern है। |
| ### Q3 | Seaborn में `hue`, `style`, `size` parameters कैसे multi-dimensional encoding enable करते हैं? |
| **Answer | ** ये parameters visual encoding channels हैं: |
| - **`hue`** | Color mapping (categorical: discrete colors, continuous: color gradient) |
| - **`style`** | Marker shape / line dash style |
| - **`size`** | Marker size / line width |
| एक scatter plot में 5 dimensions encode कर सकते हो | `x`, `y`, `hue`, `size`, `style`। यह Cleveland's visual encoding hierarchy follow करता है — position > color > size > shape in terms of human perception accuracy। |
sns.scatterplot(data=tips, x='total_bill', y='tip', hue='day', size='size', style='sex')
| Feature | FacetGrid | Manual Subplots |
|---|---|---|
| Faceting by variable | Automatic (`col=`, `row=`) | Manual loop required |
| Mixed plot types | Same type per grid | Different type per panel |
| Customization | Limited (through map) | Full matplotlib control |
| Axes sharing | Automatic | Manual `sharey=True` |
| Use case | Same plot, different subsets | Dashboard-style layouts |
Step 1: Overview
sns.pairplot(df, hue='target') # Multivariate relationships
Step 2: Distributions
for col in numeric_cols: sns.histplot(df[col], kde=True) # Each feature distribution
Step 3: Correlations
sns.heatmap(df.corr(), annot=True) # Feature correlations
Step 4: Categorical analysis
sns.catplot(data=df, x='category', y='target', kind='box')
Step 5: Relationships
sns.lmplot(data=df, x='feature', y='target', hue='group')
| **Key principles | ** पहले big picture (pairplot), फिर individual features (histplot), फिर relationships (scatter/regression), और finally insights summarize करो। |
| ### Q9 | Seaborn color palettes — sequential, diverging, और qualitative में difference explain करो। कब कौन use करोगे? |
| **Answer | ** |
| - **Sequential** (`viridis`, `Blues`, `YlGnBu`): Low-to-high ordered data — revenue, temperature, counts। Single direction, light | dark transition। |
| - **Diverging** (`RdBu`, `coolwarm`, `RdYlGn`) | Center point से दोनों directions — correlation (-1 to +1), profit/loss, above/below average। |
| - **Qualitative** (`Set1`, `Set2`, `husl`, `tab10`) | Unordered categories — species, countries, product types। Maximum distinctness between colors। |
| **Selection criteria:** Data type | palette type। Ordered numeric = sequential, centered numeric = diverging, categorical = qualitative। Always consider colorblind-friendly options (`'colorblind'` palette)। |
| ### Q10 | Seaborn plot को production-ready बनाने के लिए क्या best practices follow करोगे? |
| **Answer | ** |
| 1. **Resolution | ** `plt.savefig('plot.png', dpi=300, bbox_inches='tight')` — high DPI for print |
| 2. **Font scaling | ** `sns.set_theme(font_scale=1.3)` — readable from distance |
| 3. **Context | ** `sns.set_context('talk')` for presentations, `'paper'` for publications |
| 4. **Accessibility | ** `palette='colorblind'` — 8% male population color-blind है |
| 5. **Labels | ** Always clear axis labels, title, and legend |
| 6. **Consistency | ** Same palette across all plots in a report/dashboard |
| 7. **Size | ** `figsize` appropriate for medium (slide = 16:9, paper = portrait) |
| 8. **Remove clutter | ** `sns.despine()` — unnecessary borders remove करो |
| 9. **Annotations | ** Key insights directly plot पर annotate करो with `plt.annotate()` |
| 10. **Format | ** SVG for web, PDF for papers, PNG for presentations |
| *Next Lesson: [Data Visualization Project | ](./data-visualization-project)* |
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Statistical Visualization with Seaborn.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, data, science, seaborn
Related Python Master Course Topics