> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Seaborn: Statistical Data Visualization for Python

> Use Seaborn to create histograms, KDE plots, pair plots, bar plots, violin plots, regression lines, and correlation heatmaps with ease.

Seaborn is a Python visualization library built directly on top of Matplotlib, designed specifically for statistical graphics. Where Matplotlib gives you complete control at the cost of verbosity, Seaborn lets you produce elegant, informative charts in a single function call — and it integrates seamlessly with Pandas DataFrames. You pass your DataFrame and column names directly to Seaborn functions, and it handles the aggregation, styling, and statistical overlays automatically. This makes it the go-to library for exploratory data analysis in data science and machine learning workflows.

## Installation and Import

```bash theme={null}
pip install seaborn
```

```python theme={null}
import seaborn as sns
import matplotlib.pyplot as plt
```

## Styling and Themes

One `sns.set_theme()` call controls the visual style of all subsequent plots.

```python theme={null}
# Apply a modern dark grid style with muted colors
sns.set_theme(style="darkgrid", palette="muted")
```

**Available styles:** `whitegrid`, `darkgrid`, `ticks`, `white`, `dark`

**Available contexts** (scale fonts and element sizes): `paper`, `notebook`, `talk`, `poster`

## Analyzing Numerical Distributions

Distribution plots help you understand how a single continuous variable is spread — its range, center, skewness, and density.

### Histograms with KDE (`sns.histplot`)

Combine a histogram with a **Kernel Density Estimation (KDE)** curve for a smooth probability overlay:

```python theme={null}
tips = sns.load_dataset("tips")

sns.histplot(data=tips, x="total_bill", kde=True, color="teal")
plt.title("Distribution of Total Bills")
plt.show()
```

### Joint Plots (`sns.jointplot`)

A joint plot shows the **bivariate relationship** between two variables (scatter or hex plot) alongside the **univariate distribution** of each variable on the margins:

```python theme={null}
sns.jointplot(data=tips, x="total_bill", y="tip", kind="scatter", color="purple")
plt.show()
```

`kind` options include `"scatter"`, `"hex"`, `"kde"`, and `"reg"`.

### Pair Plots (`sns.pairplot`)

A pair plot creates a grid that compares **every numerical column against every other** — scatter plots off the diagonal, distributions on the diagonal. It is one of the fastest ways to get an overview of a new dataset.

```python theme={null}
# Color-code by a categorical variable using hue
sns.pairplot(data=tips, hue="sex", palette="coolwarm")
plt.show()
```

<Tip>
  Always start exploratory data analysis with `sns.pairplot()`. In a single call you'll spot correlations, clusters, outliers, and skewed distributions that would take many individual plots to uncover.
</Tip>

## Categorical Visualizations

Categorical plots compare a numerical variable across discrete groups.

### Bar Plots (`sns.barplot`)

Seaborn's bar plot automatically aggregates data (mean by default) and draws **confidence interval error bars**:

```python theme={null}
sns.barplot(data=tips, x="day", y="tip", hue="time", palette="Set2")
plt.title("Average Tip by Day and Meal Time")
plt.show()
```

### Count Plots (`sns.countplot`)

A count plot shows the frequency of each category — equivalent to a histogram for categorical data:

```python theme={null}
sns.countplot(data=tips, x="smoker", palette="Blues")
plt.title("Frequency of Customers by Smoking Status")
plt.show()
```

### Box Plots vs. Violin Plots

Both charts compare distributions across categories, but they reveal different aspects of the data:

```python theme={null}
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

# Box plot — quartiles and outliers
sns.boxplot(data=tips, x="day", y="total_bill", ax=axes[0], palette="pastel")
axes[0].set_title("Total Bill Range per Day (Box Plot)")

# Violin plot — distribution density shape
sns.violinplot(data=tips, x="day", y="total_bill", ax=axes[1], palette="muted")
axes[1].set_title("Total Bill Density per Day (Violin Plot)")

plt.tight_layout()
plt.show()
```

| Chart       | Shows                                                 |
| ----------- | ----------------------------------------------------- |
| Box plot    | Median, quartiles (Q1/Q3), whiskers, outliers         |
| Violin plot | All of the above + the full probability density shape |

## Relationship and Regression Plots

### Scatter Plots (`sns.scatterplot`)

Map a third variable to point color (`hue`) and a fourth to point size (`size`) to pack more information into a single chart:

```python theme={null}
sns.scatterplot(
    data=tips,
    x="total_bill",
    y="tip",
    hue="smoker",
    size="size",
    sizes=(20, 200)
)
plt.title("Bill vs. Tip — sized by Table Size")
plt.show()
```

### Regression Plots (`sns.lmplot`)

Draws a scatter plot overlaid with a **fitted linear regression line** and shaded confidence bands:

```python theme={null}
sns.lmplot(data=tips, x="total_bill", y="tip", hue="smoker", height=5)
plt.title("Bill vs. Tip — Linear Regression by Smoking Status")
plt.show()
```

<Note>
  `sns.lmplot` always creates its own figure, so you cannot pass an `ax` parameter. Use `sns.regplot` if you need to embed a regression line inside an existing subplot grid.
</Note>

## Correlation Heatmaps

A heatmap visualizes the correlation matrix of a DataFrame — making it easy to spot which pairs of features are strongly or weakly related.

```python theme={null}
# 1. Select only numerical columns
numerical_df = tips.select_dtypes(include=["number"])

# 2. Compute the Pearson correlation matrix
corr_matrix = numerical_df.corr()

# 3. Draw the heatmap
sns.heatmap(
    corr_matrix,
    annot=True,          # Print correlation values inside cells
    cmap="coolwarm",     # Red = positive, Blue = negative correlation
    vmin=-1,
    vmax=1,
    linewidths=0.5
)
plt.title("Tips Dataset Correlation Matrix")
plt.show()
```

Correlation values range from **-1** (perfect negative correlation) to **+1** (perfect positive correlation). Values close to **0** indicate no linear relationship.

<Warning>
  Correlation measures only **linear** relationships. A near-zero correlation doesn't necessarily mean two variables are unrelated — they may have a non-linear relationship. Always visualize your data before drawing conclusions from correlation alone.
</Warning>

## Seaborn Chart Quick Reference

| Chart                | Function                 | Best For                     |
| -------------------- | ------------------------ | ---------------------------- |
| Distribution + KDE   | `sns.histplot(kde=True)` | Single numerical variable    |
| Scatter + margins    | `sns.jointplot`          | Two numerical variables      |
| All pairs overview   | `sns.pairplot`           | Full dataset EDA             |
| Category means + CI  | `sns.barplot`            | Numerical vs. categorical    |
| Category frequency   | `sns.countplot`          | Categorical counts           |
| Distribution ranges  | `sns.boxplot`            | Outlier-focused comparison   |
| Distribution density | `sns.violinplot`         | Shape-focused comparison     |
| Scatter + regression | `sns.lmplot`             | Trend lines between numerics |
| Feature correlations | `sns.heatmap`            | Correlation matrix           |
