Seaborn Basics
Python · Data Visualization
Theory
Seaborn is a statistical charting library built on matplotlib that works directly with DataFrames: you pass data=df and column names, and it groups, aggregates, colours and adds legends for you. sns.histplot(data=df, x='bill', hue='day') draws overlapping histograms per group, sns.boxplot(data=df, x='day', y='bill') draws one box per day, and sns.barplot(data=df, x='day', y='bill') draws the mean bill per day with an error bar for its uncertainty.
sns.scatterplot adds hue= and size= encodings, sns.heatmap(df.corr(), annot=True) colours a matrix and writes the numbers, and sns.pairplot(df) draws a scatter plot for every pair of numeric columns with histograms on the diagonal, a fast first look at a new dataset. Every seaborn call returns or draws on a matplotlib Axes, so ax.set_title() still works. Seaborn is not available in this in-browser runner, so run seaborn code locally after pip install seaborn.
Why we use it
Seaborn turns common statistical charts into one line with sensible defaults: grouping by hue, automatic legends, error bars and attractive styles. That makes exploratory analysis much faster than building the same charts by hand in matplotlib.
When to use it
Use seaborn for exploring DataFrames: distributions, comparisons across groups, relationships and correlation heatmaps. Use plain matplotlib for highly customised figures, and pandas df.plot for the quickest simple charts.
How it works
- Tidy DataFrame: one row per record
- What question are you asking? Yes: Pick histplot / boxplot / barplot / scatterplot / heatmap. No: Start with sns.pairplot(df).
- Map columns: x=, y=, hue=
- Seaborn groups, aggregates and draws via matplotlib
- Polish with ax.set_title / ax.set_xlabel
- Statistical chart in one line
Syntax
import seaborn as sns
sns.histplot(data=df, x='col', hue='group')
sns.boxplot(data=df, x='group', y='value')
sns.barplot(data=df, x='group', y='value')
sns.heatmap(df.corr(numeric_only=True), annot=True)
sns.pairplot(df)Example
import seaborn as sns
sns.barplot(data=tips, x='day', y='bill')
sns.boxplot(data=tips, x='day', y='bill')
sns.pairplot(tips)Key points
- Pass data=df plus column names; seaborn groups for you
- hue= splits any chart by a category, with a legend
- barplot shows the mean (with an error bar), not the sum
- pairplot is a quick scatter matrix of every numeric pair
- Seaborn draws on matplotlib Axes, so ax methods still work