> ## 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.

# Matplotlib: Building Charts and Visualizations in Python

> Create line plots, histograms, scatter plots, bar charts, box plots, and multi-panel subplot grids with Matplotlib's pyplot interface.

Matplotlib is the foundational plotting library for Python. It gives you fine-grained control over every element of a chart — axes, tick marks, labels, legends, grids, colors, and line styles — making it possible to produce publication-quality figures from a few lines of code. Before you use higher-level libraries like Seaborn, understanding Matplotlib builds the conceptual foundation you'll need to customize any chart to your exact requirements.

## Installation and Import

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

```python theme={null}
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
```

## Two Interfaces

Matplotlib offers two ways to create charts:

| Interface                       | Style                                      | Best For                            |
| ------------------------------- | ------------------------------------------ | ----------------------------------- |
| **State-based** (`plt.xxx`)     | Call functions directly on `pyplot`        | Single charts — simple and concise  |
| **Object-oriented** (`fig, ax`) | Work with explicit figure and axes objects | Multiple subplots, advanced layouts |

For single charts, use the state-based approach. Switch to the object-oriented approach when building subplot grids.

### Your First Plot

```python theme={null}
x = [1, 2, 3]
y = [4, 5, 6]

plt.plot(x, y)
plt.show()
```

## Customizing a Plot

You can control titles, labels, limits, grids, legends, and tick marks with `plt.` commands:

```python theme={null}
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Plot the data
plt.plot(x, y, label="Sine Wave", color="teal", linestyle="--", linewidth=2)

# Labels and title
plt.title("Customized Sine Wave Plot", fontsize=14, fontweight="bold", pad=15)
plt.xlabel("X-Axis Values (Time)", fontsize=11)
plt.ylabel("Y-Axis Values (Amplitude)", fontsize=11)

# Limits and grid
plt.xlim(0, 10)
plt.ylim(-1.5, 1.5)
plt.grid(True, linestyle=":", alpha=0.6)

# Legend and ticks
plt.legend(loc="upper right")
plt.xticks([0, np.pi, 2*np.pi, 3*np.pi], ["0", "π", "2π", "3π"])

plt.show()
```

## Visualizing Numerical Data

Numerical (continuous) data is best explored using plots that reveal trends, distributions, or correlations.

### Line Plots — Trends Over Time

```python theme={null}
years = [2021, 2022, 2023, 2024, 2025]
sales = [150, 220, 290, 410, 500]

plt.plot(years, sales, marker="o", color="blue", linewidth=2)
plt.title("Sales Growth Over Time")
plt.xlabel("Year")
plt.ylabel("Sales")
plt.grid(True, alpha=0.4)
plt.show()
```

### Histograms — Distributions

Histograms group continuous values into "bins" to show frequency distribution.

```python theme={null}
# 1000 exam scores following a normal distribution
scores = np.random.normal(loc=75, scale=10, size=1000)

plt.hist(scores, bins=20, color="skyblue", edgecolor="black", alpha=0.7)
plt.title("Distribution of Student Scores")
plt.xlabel("Exam Scores")
plt.ylabel("Number of Students")
plt.show()
```

<Tip>
  Adjust the `bins` parameter to control granularity. Too few bins hides the shape of the distribution; too many makes it jagged. A starting point of 20–30 bins works well for most datasets.
</Tip>

### Scatter Plots — Correlations

Scatter plots reveal relationships between two continuous variables.

```python theme={null}
study_hours  = [2, 4, 5, 7, 8, 10, 11, 12]
exam_scores  = [55, 62, 70, 78, 85, 92, 95, 100]

plt.scatter(study_hours, exam_scores, color="orange", s=100, edgecolor="red")
plt.title("Study Hours vs. Exam Scores")
plt.xlabel("Hours Studied")
plt.ylabel("Exam Score")
plt.show()
```

## Visualizing Categorical Data

Categorical data (discrete groups like departments or courses) is best represented with bar charts.

### Vertical Bar Chart

```python theme={null}
courses  = ["Python", "SQL", "Machine Learning", "Git"]
students = [450, 320, 540, 180]

plt.bar(courses, students, color=["#10B981", "#3B82F6", "#8B5CF6", "#F59E0B"])
plt.title("Student Enrollment by Course")
plt.ylabel("Number of Students")
plt.show()
```

### Horizontal Bar Chart (`barh`)

Use `barh` when category names are long — it prevents the labels from overlapping on the x-axis.

```python theme={null}
categories = ["Software Engineer", "Data Scientist", "Product Manager", "UI/UX Designer"]
salaries   = [110, 120, 105, 90]   # in thousands

plt.barh(categories, salaries, color="purple")
plt.title("Median Salaries by Role ($k)")
plt.xlabel("Salary ($k)")
plt.show()
```

## Numerical vs. Categorical — Box Plots

A box plot (whisker plot) compares the distribution of a numerical variable across categories. It displays five statistics: minimum, Q1, median, Q3, and maximum, and highlights outliers.

```python theme={null}
class_A = [55, 62, 70, 78, 85, 90, 92, 100]
class_B = [40, 50, 55, 60, 72, 80, 85, 90]
class_C = [65, 75, 80, 85, 90, 95, 98, 100]

plt.boxplot(
    [class_A, class_B, class_C],
    labels=["Class A", "Class B", "Class C"],
    patch_artist=True
)
plt.title("Exam Score Distribution by Class")
plt.ylabel("Scores")
plt.show()
```

## Multi-Panel Layouts with Subplots

When you need multiple charts side by side, switch to the object-oriented interface with `plt.subplots()`.

```python theme={null}
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))

x = np.linspace(0, 5, 50)

# Top-left — Linear
axes[0, 0].plot(x, x, color="blue")
axes[0, 0].set_title("Linear")

# Top-right — Quadratic
axes[0, 1].plot(x, x**2, color="green")
axes[0, 1].set_title("Quadratic")

# Bottom-left — Cubic
axes[1, 0].plot(x, x**3, color="red")
axes[1, 0].set_title("Cubic")

# Bottom-right — Exponential
axes[1, 1].plot(x, np.exp(x), color="purple")
axes[1, 1].set_title("Exponential")

# Prevent overlapping titles and labels
plt.tight_layout()
plt.show()
```

<Note>
  `plt.tight_layout()` automatically adjusts spacing between subplots so titles and axis labels don't overlap. Always call it before `plt.show()` when working with subplot grids.
</Note>

## Chart Type Quick Reference

| Data Type                         | Chart          | Matplotlib Function |
| --------------------------------- | -------------- | ------------------- |
| Trend over time                   | Line plot      | `plt.plot()`        |
| Distribution of numbers           | Histogram      | `plt.hist()`        |
| Correlation between two numbers   | Scatter plot   | `plt.scatter()`     |
| Compare categories (vertical)     | Bar chart      | `plt.bar()`         |
| Compare categories (horizontal)   | Horizontal bar | `plt.barh()`        |
| Number vs. category distributions | Box plot       | `plt.boxplot()`     |
| Multiple charts                   | Subplot grid   | `plt.subplots()`    |
