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

# Matplotlib

# Introduction to Matplotlib

## What is Data Visualization?

Data Visualization is the process of converting raw data into charts, graphs, and plots to:

* Understand patterns
* Detect trends
* Find outliers
* Analyze relationships

***

# What is Matplotlib?

Matplotlib is a Python library used for creating:

* Line charts
* Histograms
* Boxplots
* Pie charts
* Scatter plots
* Bar charts
* 3D plots

Widely used in:

* Data Science
* Machine Learning
* Analytics

***

# Installing Matplotlib

## Installation

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

***

# Importing Libraries

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

### Explanation

* `matplotlib.pyplot` → plotting functions
* `pandas` → data handling

***

# Basic Plot Function

## `plt.plot()`

Creates a line plot.

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

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

### Output

A line graph connecting points:

* (1,4)
* (2,5)
* (3,6)

### Explanation

* `plot()` → creates line graph
* `grid()` → adds background grid
* `show()` → displays graph
  <Frame>
    <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/basicline.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=f75ebb00b0f6912d5867e2b0c0796a28" alt="Basicline" width="556" height="413" data-path="images/basicline.png" />
  </Frame>

***

# Components of a Figure

| Component | Purpose               |
| :-------- | :-------------------- |
| Figure    | Entire canvas         |
| Axes      | X and Y plotting area |
| Title     | Graph heading         |
| Labels    | Axis descriptions     |
| Legend    | Explains colors/lines |
| Grid      | Improves readability  |
| Ticks     | Scale markings        |

***

# Univariate Analysis

Analyzing one variable.

***

# Line Plot

Shows trends or changes in numerical data.

```python theme={null}
plt.plot(df['Salary'],
         color='red',
         marker='o',
         linestyle=':',
         linewidth=2)

plt.grid()
plt.show()
```

### Explanation

* `color='red'` → line color
* `marker='o'` → circle markers
* `linestyle=':'` → dotted line
* `linewidth=2` → line thickness

### Output

Salary trend line graph.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/lineplot.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=dd154566d82518468232a3afed701f31" alt="Lineplot" width="483" height="377" data-path="images/lineplot.png" />
</Frame>

***

# Histogram

## `plt.hist()`

Shows frequency distribution.

```python theme={null}
plt.hist(df['Salary'], bins=5, color='green')
plt.show()
```

### Explanation

* `bins=5` → divides data into 5 ranges
* Shows how many values fall into each range

### Output

Bar-like histogram distribution.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/histogram.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=185d33ca7460868316034080b5c86b94" alt="Histogram" width="534" height="413" data-path="images/histogram.png" />
</Frame>

***

# Box Plot

## `plt.boxplot()`

Used for:

* detecting outliers
* understanding spread
* quartile analysis

```python theme={null}
plt.boxplot(df['Salary'])
plt.show()
```

### Output

Boxplot showing median and quartiles.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/boxplot.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=98be07ee6378b0c1eddc7174caeec412" alt="Boxplot" width="510" height="370" data-path="images/boxplot.png" />
</Frame>

***

# Outlier Detection

```python theme={null}
df.loc[15] = [0]

plt.boxplot(df['Salary'])
plt.show()
```

### Explanation

Adding `0` creates an outlier visible in boxplot.

***

# Categorical Analysis

***

# Pie Chart

Shows percentage contribution.

```python theme={null}
count = df['dept'].value_counts()

plt.pie(count,
        labels=count.index,
        autopct='%1.2f%%',
        explode=[0,0.1,0])

plt.axis('equal')
plt.show()
```

### Explanation

* `labels` → category names
* `autopct` → percentage display
* `explode` → separates slice
* `axis('equal')` → perfect circle

### Output

Department percentage pie chart.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/pie.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=179fe79dc09585738f2cc4357d3fa623" alt="Pie" width="444" height="343" data-path="images/pie.png" />
</Frame>

***

# Count Plot / Bar Chart

## `plt.bar()`

Shows category frequencies.

```python theme={null}
plt.bar(count.index, count)
plt.show()
```

### Output

Bar chart of department counts.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/rMXPoCC-aGrxYDbP/images/countplot25.png?fit=max&auto=format&n=rMXPoCC-aGrxYDbP&q=85&s=48a9081ffc5434eb260aa0d7d5225b91" alt="Countplot25" width="478" height="374" data-path="images/countplot25.png" />
</Frame>

***

# Bivariate Analysis

Analyzing relationship between two variables.

***

# Scatter Plot

## `plt.scatter()`

Shows relationship between two numerical variables.

```python theme={null}
plt.scatter(df['Salary'], df['age'])
plt.show()
```

### Explanation

Each dot represents:

* X → Salary
* Y → Age

### Output

Scatter plot showing salary vs age.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/8fmDYpC4CP_K6VA6/images/scatterplot26.png?fit=max&auto=format&n=8fmDYpC4CP_K6VA6&q=85&s=98c514ce2ed3a8da8b98f88477914171" alt="Scatterplot26" width="484" height="373" data-path="images/scatterplot26.png" />
</Frame>

***

# Sorted Line Plot

```python theme={null}
sort_salary = df.sort_values('Salary')

plt.plot(sort_salary['Salary'],
         df['age'],
         color='red',
         marker='o',
         linestyle=':')
plt.grid()
plt.show()
```

### Explanation

Sorting improves line continuity.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/lineplot.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=dd154566d82518468232a3afed701f31" alt="Lineplot" width="483" height="377" data-path="images/lineplot.png" />
</Frame>

***

# Bar Chart

```python theme={null}
plt.bar(df['age'], df['Salary'], color='green')
plt.show()
```

### Explanation

Compares salary for each age.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/bar1.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=cabdf59caad4bf76f8724a5db44c5b80" alt="Bar1" width="507" height="361" data-path="images/bar1.png" />
</Frame>

***

# Numerical vs Categorical Analysis

***

# Multiple Boxplots

```python theme={null}
plt.boxplot([hr_sal, it_sal, finance_sal],
            labels=['HR', 'IT', 'Finance'])

plt.show()
```

### Explanation

Compares salary distributions across departments.

### Output

Three side-by-side boxplots.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/multibox.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=3b43f3d985d5a70fcaf3025f5ffe68b7" alt="Multibox" width="515" height="365" data-path="images/multibox.png" />
</Frame>

***

# Department Salary Pie Chart

```python theme={null}
salary_by_dept = df.groupby('dept')['Salary'].sum()

plt.pie(salary_by_dept,
        labels=salary_by_dept.index,
        autopct='%1.2f%%',
        explode=[0,0.1,0],
        shadow=True)

plt.axis('equal')
plt.show()
```

### Explanation

Shows total salary contribution by department.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/pie2.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=28639f8352375688fd7fc9ed203fab0c" alt="Pie2" width="515" height="389" data-path="images/pie2.png" />
</Frame>

***

# Mean Salary Bar Chart

```python theme={null}
plt.bar(['HR','IT','Finance'],
        [hr_mean,it_mean,finance_mean])

plt.show()
```

### Explanation

Displays average salary per department.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/meanbar.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=22bd1042723d51021ec111a22ed7b99a" alt="Meanbar" width="569" height="413" data-path="images/meanbar.png" />
</Frame>

***

# Multivariate Analysis

Analyzing 3 or more variables.

***

# Bubble Plot

```python theme={null}
plt.scatter(df['Salary'],
            df['age'],
            s=df['experience']*100)

plt.title('Salary vs Age vs Experience')
plt.xlabel('Salary')
plt.ylabel('Age')

plt.show()
```

### Explanation

* X → Salary
* Y → Age
* Bubble Size → Experience

### Output

Bubble plot with varying circle sizes.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/bubble.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=bac07acd010a0ddf2045cbe66d9de900" alt="Bubble" width="562" height="455" data-path="images/bubble.png" />
</Frame>

***

# Color-Based Scatter Plot

```python theme={null}
plt.scatter(df['Salary'],
            df['age'],
            c=df['dept'].map({
                'HR':'red',
                'IT':'green',
                'Finance':'blue'
            }))

plt.show()
```

### Explanation

Different colors represent departments.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/colorscatter.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=da877962827257056ad9ebc1bf8e39e4" alt="Colorscatter" width="562" height="455" data-path="images/colorscatter.png" />
</Frame>

***

# Scatter Plot with Legend

```python theme={null}
color = {'HR':'red',
         'IT':'green',
         'Finance':'blue'}

for dept in color:
    dept_data = df[df['dept'] == dept]

    plt.scatter(dept_data['Salary'],
                dept_data['age'],
                label=dept,
                color=color[dept])

plt.legend()
plt.show()
```

### Explanation

Adds department-wise legend.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/scatterlegend.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=3d31d34194d2393a10ee66004dd76c23" alt="Scatterlegend" width="562" height="455" data-path="images/scatterlegend.png" />
</Frame>

***

# Object Oriented API

Provides more control over plots.

***

# `plt.subplots()`

Creates multiple plots.

```python theme={null}
fig, axs = plt.subplots(2,2, figsize=(10,10))
```

### Explanation

* 2 rows
* 2 columns
* Figure size = 10x10
  <Frame>
    <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/download.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=2fca57f4c93b49f57339d618b81d2383" alt="Download" width="837" height="819" data-path="images/download.png" />
  </Frame>

***

# Multiple Plots

## Line Plot

```python theme={null}
axs[0,0].plot(df['Salary'],
              color='red',
              marker='o',
              linestyle=':')

axs[0,0].grid()
```

***

## Histogram

```python theme={null}
axs[0,1].hist(df['Salary'],
              bins=5,
              color='green')
```

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/multiplot2.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=33e5c3284b23e934c7ea929545935286" alt="Multiplot2" width="859" height="813" data-path="images/multiplot2.png" />
</Frame>

***

## Boxplot

```python theme={null}
axs[1,0].boxplot(df['Salary'])
```

***

# Saving Figures

## `savefig()`

Saves plot locally.

```python theme={null}
plt.savefig('plot.png')
```

### Explanation

Saves graph as PNG image.

***

# Multiple Line Plots

```python theme={null}
plt.plot(df2['Year'], df2['Sales'], label='Sales')

plt.plot(df2['Year'], df2['Profit'], label='Profit')

plt.plot(df2['Year'], df2['Expenses'], label='Expenses')

plt.legend()
plt.show()
```

### Explanation

Displays multiple lines in same graph.

### Output

Sales, Profit, and Expenses comparison graph.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/multilineplot.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=7be53afe8010f9dc5691cf5d00c1fe68" alt="Multilineplot" width="569" height="413" data-path="images/multilineplot.png" />
</Frame>

***

# 3D Plot

```python theme={null}
ax = plt.figure().add_subplot(projection='3d')

ax.scatter(df2['Year'],
           df2['Sales'],
           df2['Profit'])

plt.show()
```

### Explanation

Creates 3D scatter plot.

Axes:

* X → Year
* Y → Sales
* Z → Profit
  <Frame>
    <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/3d.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=4457800d224730282b220e79a308d575" alt="3d" width="420" height="398" data-path="images/3d.png" />
  </Frame>

***

# Plotly 3D Plot

```python theme={null}
import plotly.express as px

fig = px.scatter_3d(df2,
                    x='Year',
                    y='Sales',
                    z='Profit')

fig.show()
```

### Explanation

Interactive 3D visualization using Plotly.

<Frame>
  <img src="https://mintcdn.com/ai-923f8160/iV3h4XlkynEO9cPv/images/i3d.png?fit=max&auto=format&n=iV3h4XlkynEO9cPv&q=85&s=e99c258782cc08eb768fd9463502e7bb" alt="I3d" width="734" height="438" data-path="images/i3d.png" />
</Frame>

***

# Important Plot Types Summary

| Plot Type    | Used For                       |
| :----------- | :----------------------------- |
| Line Plot    | Trends over time               |
| Histogram    | Frequency distribution         |
| Boxplot      | Outlier detection              |
| Pie Chart    | Percentage distribution        |
| Bar Chart    | Category comparison            |
| Scatter Plot | Relationship between variables |
| Bubble Plot  | 3-variable analysis            |
| 3D Plot      | Three-dimensional analysis     |

***

# Important Matplotlib Functions

| Function    | Purpose       |
| :---------- | :------------ |
| `plot()`    | Line graph    |
| `hist()`    | Histogram     |
| `boxplot()` | Boxplot       |
| `pie()`     | Pie chart     |
| `bar()`     | Bar chart     |
| `scatter()` | Scatter plot  |
| `legend()`  | Show legend   |
| `title()`   | Graph title   |
| `xlabel()`  | X-axis label  |
| `ylabel()`  | Y-axis label  |
| `grid()`    | Show grid     |
| `show()`    | Display graph |
| `savefig()` | Save figure   |

***

# Matplotlib Usage

Matplotlib helps to:

* Visualize datasets
* Understand trends
* Detect outliers
* Compare categories
* Analyze relationships
* Create professional graphs
