# 20 Matplotlib concepts with Before-and-After Examples

### 1\. **Creating Basic Plots (plt.plot)** 📈

**Boilerplate Code**:

```python
import matplotlib.pyplot as plt
```

**Use Case**: Create a **basic line plot** to visualize data trends. 📈

**Goal**: Plot your data points and connect them with a line to see how they evolve. 🎯

**Sample Code**:

```python
# Create a basic line plot
plt.plot([1, 2, 3, 4], [10, 20, 25, 30])

# Show the plot
plt.show()
```

**Before Example**: has data but no way to visualize trends. 🤔

```python
Data: [1, 2, 3, 4], [10, 20, 25, 30]
```

**After Example**: With **plt.plot()**, the data is now visualized as a line plot! 📈

```python
Line Plot: [X-axis: 1-4, Y-axis: 10-30]
```

**Challenge**: 🌟 Try plotting multiple lines by calling `plt.plot()` multiple times before [`plt.show`](http://plt.show)`()`.

---

### 2\. **Adding Titles and Labels (plt.title, plt.xlabel, plt.ylabel)** 🏷️

**Boilerplate Code**:

```python
plt.title('My Plot')
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')
```

**Use Case**: Add a **title** and **labels** to your plot’s axes for clarity. 🏷️

**Goal**: Make your plots more informative by labeling the axes and adding a title. 🎯

**Sample Code**:

```python
# Add title and labels to the plot
plt.title('My Line Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')

# Plot the data
plt.plot([1, 2, 3, 4], [10, 20, 25, 30])
plt.show()
```

**Before Example**: a plot but it lacks context. 🤷‍♂️

```python
Plot: no title, no axis labels.
```

**After Example**: With **title** and **labels**, the plot is now informative and easy to understand! 🏷️

```python
Title: 'My Line Plot'
X Axis: 'X Axis'
Y Axis: 'Y Axis'
```

**Challenge**: 🌟 Try experimenting with different fonts and sizes for titles and labels using parameters like `fontsize=14`.

---

### 3\. **Changing Line Styles (plt.plot with linestyle)** 🎨

**Boilerplate Code**:

```python
plt.plot(x, y, linestyle='--')
```

**Use Case**: Customize the **line style** (solid, dashed, dotted) in your plots for better distinction. 🎨

**Goal**: Make your plots more visually engaging and easier to read by changing the line style. 🎯

**Sample Code**:

```python
# Create a dashed line plot
plt.plot([1, 2, 3, 4], [10, 20, 25, 30], linestyle='--')

# Show the plot
plt.show()
```

**Before Example**: plot uses default lines, which may not stand out. 😐

```python
Line style: solid.
```

**After Example**: With **linestyle='--'**, the plot now has a dashed line for better visibility! 🎨

```python
Dashed Line Plot: [X: 1-4, Y: 10-30]
```

**Challenge**: 🌟 Try combining different styles like `'-.'` or `':'` for other plots.

---

### 4\. **Adjusting Colors (plt.plot with color)** 🎨

**Boilerplate Code**:

```python
plt.plot(x, y, color='red')
```

**Use Case**: Customize the **line color** in your plot to make it visually distinct. 🎨

**Goal**: Change the line color to enhance plot readability or match a theme. 🎯

**Sample Code**:

```python
# Create a red line plot
plt.plot([1, 2, 3, 4], [10, 20, 25, 30], color='red')

# Show the plot
plt.show()
```

**Before Example**: plot uses the default blue color, which may not stand out. 🤷‍♂️

```python
Line color: blue (default).
```

**After Example**: With **color='red'**, the plot now uses a distinct, bright color! 🎨

```python
Red Line Plot: [X: 1-4, Y: 10-30]
```

**Challenge**: 🌟 Try using different colors like `green`, `orange`, or even hex codes like `#ff5733`.

---

### 5\. **Scatter Plots (plt.scatter)** 🔵

**Boilerplate Code**:

```python
plt.scatter(x, y)
```

**Use Case**: Create a **scatter plot** to visualize relationships between two variables. 🔵

**Goal**: Plot individual data points to explore correlations or clusters. 🎯

**Sample Code**:

```python
# Create a scatter plot
plt.scatter([1, 2, 3, 4], [10, 20, 25, 30])

# Show the plot
plt.show()
```

**Before Example**: want to visualize individual data points but doesn’t know how. 🤔

```python
Data: scattered points [X: 1-4, Y: 10-30].
```

**After Example**: With **plt.scatter()**, the data is now displayed as a scatter plot! 🔵

```python
Scatter Plot: individual points at [X: 1-4, Y: 10-30].
```

**Challenge**: 🌟 Try customizing the size and color of the scatter points using parameters like `s=100`, `c='red'`.

---

### 6\. **Bar Charts (**[**plt.bar**](http://plt.bar)**)** 📊

**Boilerplate Code**:

```python
plt.bar(x, height)
```

**Use Case**: Create a **bar chart** to compare values across categories. 📊

**Goal**: Visualize categorical data using vertical or horizontal bars. 🎯

**Sample Code**:

```python
# Create a bar chart
plt.bar(['A', 'B', 'C', 'D'], [5, 7, 3, 8])

# Show the plot
plt.show()
```

**Before Example**: has categorical data but no visual comparison. 🤷

```python
Categories: ['A', 'B', 'C', 'D'], Values: [5, 7, 3, 8]
```

**After Example**: With [**plt.bar**](http://plt.bar)**()**, the categories are visualized as bars! 📊

```python
Bar Chart: ['A', 'B', 'C', 'D'] with heights [5, 7, 3, 8].
```

**Challenge**: 🌟 Try creating a horizontal bar chart using `plt.barh()` and see how it changes the visualization.

---

### 7\. **Histograms (plt.hist)** 📉

**Boilerplate Code**:

```python
plt.hist(data, bins=10)
```

**Use Case**: Create a **histogram** to visualize the distribution of data. 📉

**Goal**: Show the frequency of different values or ranges in your dataset. 🎯

**Sample Code**:

```python
# Create a histogram with 10 bins
plt.hist([1, 1, 2, 2, 2, 3, 4, 5], bins=5)

# Show the plot
plt.show()
```

**Before Example**: has a dataset but can’t see its distribution. 🤔

```python
Data: [1, 1, 2, 2, 2, 3, 4, 5]
```

**After Example**: With **plt.hist()**, the data distribution is clearly visible as a histogram! 📉

```python
Histogram: data grouped into 5 bins.
```

**Challenge**: 🌟 Try adjusting the number of bins to see how it affects the histogram.

---

### 8\. **Subplots (plt.subplot, plt.subplots)** 📊📊

**Boilerplate Code**:

```python
plt.subplot(1, 2, 1)
plt.subplot(1, 2, 2)
```

**Use Case**: Create **subplots** to display multiple plots side by side or in a grid. 📊📊

**Goal**: Visualize different aspects of your data in a single figure. 🎯

**Sample Code**:

```python
# Create two subplots in a 1x2 grid
plt.subplot(1, 2, 1)
plt.plot([1, 2, 3], [4, 5, 6])

plt.subplot(1, 2, 2)
plt.bar([1, 2, 3], [7, 8, 9])

plt.show()
```

**Before Example**: need to compare different plots but can’t do so in one figure. 🤔

```python
Plot 1: Line plot, Plot 2: Bar chart (separate).
```

**After Example**: With **plt.subplot()**, both plots are displayed side by side! 📊📊

```python
Two Subplots: Line plot and bar chart.
```

**Challenge**: 🌟 Try creating a 2x2 grid of subplots and experiment with different plot types.

---

### 9\. **Logarithmic Scales (plt.xscale, plt.yscale)** 📐

**Boilerplate Code**:

```python
plt.xscale('log')
plt.yscale('log')
```

**Use Case**: Apply **logarithmic scales** to axes to better visualize data with large ranges. 📐

**Goal**: Handle data that spans several orders of magnitude more effectively. 🎯

**Sample Code**:

```python
# Apply log scale to the x-axis
plt.plot([1, 10, 100], [10, 100, 1000])
plt.xscale('log')

plt.show()
```

**Before Example**: data has a wide range, making it hard to visualize on a linear scale. 😬

```python
X values: [1, 10, 100], Y values: [10, 100, 1000]
```

**After Example**: <mark> With </mark> **<mark>log scales</mark>**<mark>, the plot is more readable! 📐</mark>

```python
Logarithmic X-Axis: [1, 10, 100] plotted on log scale.
```

**Challenge**: 🌟 Try applying log scales to both axes (`plt.yscale('log')`) and see the difference.

---

### 10\. **Saving Figures (plt.savefig)** 💾

**Boilerplate Code**:

```python
plt.savefig('my_plot.png')
```

**Use Case**: **Save** your plot to a file (e.g., PNG, PDF) for reports or sharing. 💾

**Goal**: Export your plots to files for later use. 🎯

**Sample Code**:

```python
# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])

# Save the plot to a file
plt.savefig('my_plot.png')

# The plot is saved as 'my_plot.png'!
```

**Before Example**: create plots but doesn’t know how to save them. 🤷‍♂️

```python
Plot created but not saved.
```

**After Example**: With **plt.savefig()**, the plot is saved to a file! 💾

```python
Saved plot as 'my_plot.png'.
```

**Challenge**: 🌟 Try saving the plot in different formats like PDF using `plt.savefig('my_plot.pdf')`.

---

### 11\. **Figure Size and DPI (plt.figure)** 📏

**Boilerplate Code**:

```python
plt.figure(figsize=(8, 6), dpi=100)
```

**Use Case**: Customize the **figure size** and **<mark>DPI</mark>** <mark> (dots per inch</mark>) to adjust plot dimensions and resolution. 📏

**Goal**: Control the size and clarity of your plots for presentations or reports. 🎯

**Sample Code**:

```python
# Set figure size and DPI
plt.figure(figsize=(8, 6), dpi=100)

# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])

# Show the plot
plt.show()
```

**Before Example**: plots are too small or too large for their report. 😕

```python
Plot: small, not clear enough for print.
```

**After Example**: With **figure size** and **DPI**, the plot is perfectly sized and clear! 📏

```python
Plot size: 8x6 inches, DPI: 100 (high resolution).
```

**Challenge**: 🌟 Try creating larger figures for presentations (`figsize=(12, 8)`) or higher resolution for printing (`dpi=300`).

---

### 12\. **Legends (plt.legend)** 🏷️

**Boilerplate Code**:

```python
plt.legend(['Line 1', 'Line 2'])
```

**Use Case**: Add a **legend** to your plot to label different data series. 🏷️

**Goal**: Make your plot easier to interpret by showing which line or data point belongs to which label. 🎯

**Sample Code**:

```python
# Create two line plots
plt.plot([1, 2, 3], [4, 5, 6], label='Line 1')
plt.plot([1, 2, 3], [6, 5, 4], label='Line 2')

# Add legend
plt.legend()

# Show the plot
plt.show()
```

**Before Example**: plot has multiple lines but no explanation for what each line represents. 🤔

```python
Plot: two lines but no labels.
```

**After Example**: With **plt.legend()**, the plot is now labeled and easy to understand! 🏷️

```python
Legend: 'Line 1', 'Line 2'
```

**Challenge**: 🌟 Try positioning the legend in different locations using `loc='upper right'` or `loc='lower left'`.

---

### 13\. **Grid Lines (plt.grid)** 📐

**Boilerplate Code**:

```python
plt.grid(True)
```

**Use Case**: Add **grid lines** to your plot to improve readability by making it easier to interpret data points. 📐

**Goal**: Enable grid lines to help with aligning and reading values. 🎯

**Sample Code**:

```python
# Create a plot with grid lines
plt.plot([1, 2, 3], [4, 5, 6])

# Add grid
plt.grid(True)

# Show the plot
plt.show()
```

**Before Example**: plot lacks grid lines, making it harder to read values. 🤔

```python
Plot: no grid, hard to align data points.
```

**After Example**: With **grid lines**, it’s now much easier to align and interpret the data! 📐

```python
Plot with grid lines for better readability.
```

**Challenge**: 🌟 Try changing the grid style with `plt.grid(color='gray', linestyle='--')`.

---

### 14\. **Customizing Ticks (plt.xticks, plt.yticks)** 🔢

**Boilerplate Code**:

```python
plt.xticks([1, 2, 3], ['One', 'Two', 'Three'])
plt.yticks([4, 5, 6], ['Low', 'Medium', 'High'])
```

**Use Case**: Customize **tick marks** and labels on the x and y axes to make your plot more readable or fit specific requirements. 🔢

**Goal**: Change the values or labels of tick marks on the axes for better customization. 🎯

**Sample Code**:

```python
# Create a plot with custom ticks
plt.plot([1, 2, 3], [4, 5, 6])

# Customize x and y axis tick labels
plt.xticks([1, 2, 3], ['One', 'Two', 'Three'])
plt.yticks([4, 5, 6], ['Low', 'Medium', 'High'])

# Show the plot
plt.show()
```

**Before Example**: plot uses default tick labels, which might not make sense in their context. 🤔

```python
X-axis: [1, 2, 3], Y-axis: [4, 5, 6]
```

**After Example**: With **custom tick labels**, the plot is now more descriptive! 🔢

```python
X-axis: ['One', 'Two', 'Three'], Y-axis: ['Low', 'Medium', 'High']
```

**Challenge**: 🌟 Try rotating the tick labels using `plt.xticks(rotation=45)`.

---

### 15\. **Heatmaps (plt.imshow)** 🌡️

**Boilerplate Code**:

```python
plt.imshow(data, cmap='hot', interpolation='nearest')
```

**Use Case**: Create a **heatmap** to visualize the magnitude of values across a matrix or grid. 🌡️

**Goal**: Show a color-coded representation of data values, with different colors representing different magnitudes. 🎯

**Sample Code**:

```python
# Create a 2D heatmap
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
plt.imshow(data, cmap='hot', interpolation='nearest')

# Show the heatmap
plt.show()
```

**Before Example**: has a matrix of numbers but no way to visualize it clearly. 🤔

```python
Data: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```

**After Example**: With **plt.imshow()**, the matrix is now visualized as a heatmap! 🌡️

```python
Heatmap: color-coded values from 1 to 9.
```

**Challenge**: 🌟 Try using different color maps like `cmap='cool'` or `cmap='viridis'` to change the heatmap style.

---

### 16\. **Pie Charts (plt.pie)** 🥧

**Boilerplate Code**:

```python
plt.pie(data, labels=labels, autopct='%1.1f%%')
```

**Use Case**: Create a **pie chart** to represent categorical data as proportions of a whole. 🥧

**Goal**: Show how different categories contribute to the total. 🎯

**Sample Code**:

```python
# Create a pie chart
data = [30, 20, 50]
labels = ['Category A', 'Category B', 'Category C']
plt.pie(data, labels=labels, autopct='%1.1f%%')

# Show the pie chart
plt.show()
```

**Before Example**: has categorical data but no way to show proportions. 🤷‍♂️

```python
Data: [30%, 20%, 50%]
```

**After Example**: With **plt.pie()**, the data is now visualized as a pie chart! 🥧

```python
Pie Chart: Categories A, B, C with respective proportions.
```

**Challenge**: 🌟 Try adding a `explode` parameter to pull one slice away from the pie.

---

### 17\. **Error Bars (plt.errorbar)** 📏

**Boilerplate Code**:

```python
plt.errorbar(x, y, yerr=0.2, fmt='o')
```

**Use Case**: Add **error bars** to your plot to represent uncertainty or variability in your data. 📏

**Goal**: Show the potential range of error for each data point. 🎯

**Sample Code**:

```python
# Create a plot with error bars
plt.errorbar([1, 2, 3], [4, 5, 6], yerr=0.2, fmt='o')

# Show the plot
plt.show()
```

**Before Example**: has data with variability but no way to show the error range. 🤔

```python
Data points: [1, 2, 3] with errors.
```

**After Example**: With **error bars**, the variability is now clearly represented! 📏

```python
Error Bars: Data points with ±0.2 error range.
```

**Challenge**: 🌟 Try adding both `yerr` and `xerr` to show error bars on both axes.

---

### 18\. **3D Plots (plt.figure with 3D projection)** 🌍

**Boilerplate Code**:

```python
from mpl_toolkits.mplot3d import Axes3D
```

**Use Case**: Create **3D plots**

to visualize data with three dimensions. 🌍

**Goal**: Add a third axis (z-axis) to visualize multi-dimensional data. 🎯

**Sample Code**:

```python
# Create a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter([1, 2, 3], [4, 5, 6], [7, 8, 9])

# Show the 3D plot
plt.show()
```

**Before Example**: has 3D data but is limited to 2D plots. 🤷‍♂️

```python
Data: [X, Y, Z] but visualized in 2D.
```

**After Example**: With **3D plotting**, the intern can now visualize all three dimensions! 🌍

```python
3D Plot: Points in X, Y, Z space.
```

**Challenge**: 🌟 Try adding more points or experimenting with surface plots using `ax.plot_surface()`.

---

### 19\. **Annotations (plt.annotate)** 📝

**Boilerplate Code**:

```python
plt.annotate('Annotation', xy=(x, y), xytext=(x+1, y+1),
             arrowprops=dict(facecolor='black', arrowstyle='->'))
```

**Use Case**: Add **annotations** to your plot to highlight specific points or regions. 📝

**Goal**: Draw attention to important data points or trends with text and arrows. 🎯

**Sample Code**:

```python
# Create a plot
plt.plot([1, 2, 3], [4, 5, 6])

# Add annotation
plt.annotate('Important point', xy=(2, 5), xytext=(3, 6),
             arrowprops=dict(facecolor='black', arrowstyle='->'))

# Show the plot
plt.show()
```

**Before Example**: plot has interesting points, but they aren’t highlighted. 🤔

```python
Plot: No annotations.
```

**After Example**: With **annotations**, the important point is clearly highlighted! 📝

```python
Annotated point with arrow and label.
```

**Challenge**: 🌟 Try using different arrow styles or adding multiple annotations to highlight more points.

---

### 20\. **Twin Axes (plt.twinx)** 🎯

**Boilerplate Code**:

```python
ax1 = plt.gca()
ax2 = ax1.twinx()
```

**Use Case**: Create **twin axes** to plot two different sets of data with different y-axes on the same plot. 🎯

**Goal**: Visualize two related datasets on the same plot but with different scales. 🎯

**Sample Code**:

```python
# Create a line plot with twin axes
fig, ax1 = plt.subplots()

ax1.plot([1, 2, 3], [4, 5, 6], 'g-')
ax1.set_ylabel('Y1 axis', color='g')

ax2 = ax1.twinx()
ax2.plot([1, 2, 3], [10, 20, 30], 'b-')
ax2.set_ylabel('Y2 axis', color='b')

# Show the plot
plt.show()
```

**Before Example**: Has two datasets but struggles to visualize them on the same plot due to different scales. 🤷‍♂️

```python
Dataset 1: Y values [4, 5, 6], Dataset 2: Y values [10, 20, 30]
```

**After Example**: With **twin axes**, both datasets are plotted together with their respective y-axes! 🎯

```python
Twin Axes: Two y-axes for two different datasets.
```

**Challenge**: 🌟 Try changing one axis to a logarithmic scale using `ax2.set_yscale('log')`.

---
