Machine Learning
39.2K subscribers
3.82K photos
32 videos
41 files
1.3K links
Machine learning insights, practical tutorials, and clear explanations for beginners and aspiring data scientists. Follow the channel for models, algorithms, coding guides, and real-world ML applications.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Topic: Python Matplotlib – From Easy to Top: Part 5 of 6: Images, Heatmaps, and Colorbars

---

### 1. Introduction

Matplotlib can handle images, heatmaps, and color mapping effectively, making it a great tool for visualizing:

• Image data (grayscale or color)
• Matrix-like data with heatmaps
• Any data that needs a gradient of colors

---

### 2. Displaying Images with `imshow()`

import matplotlib.pyplot as plt
import numpy as np

# Create a random grayscale image
img = np.random.rand(10, 10)

plt.imshow(img, cmap='gray')
plt.title("Grayscale Image")
plt.colorbar()
plt.show()


Key parameters:

cmap – color map (gray, hot, viridis, coolwarm, etc.)
interpolation – for smoothing pixelation (nearest, bilinear, bicubic)

---

### 3. Displaying Color Images

import matplotlib.image as mpimg

img = mpimg.imread('example.png') # image must be in your directory
plt.imshow(img)
plt.title("Color Image")
plt.axis('off') # Hide axes
plt.show()


Note: Image should be PNG or JPG. For real projects, use PIL or OpenCV for more control.

---

### 4. Creating a Heatmap from a 2D Matrix

matrix = np.random.rand(6, 6)

plt.imshow(matrix, cmap='viridis', interpolation='nearest')
plt.title("Heatmap Example")
plt.colorbar(label="Intensity")
plt.xticks(range(6), ['A', 'B', 'C', 'D', 'E', 'F'])
plt.yticks(range(6), ['P', 'Q', 'R', 'S', 'T', 'U'])
plt.show()


---

### 5. Customizing Color Maps

You can reverse or customize color maps:

plt.imshow(matrix, cmap='coolwarm_r')  # Reversed coolwarm


You can also create custom color ranges using vmin and vmax:

plt.imshow(matrix, cmap='hot', vmin=0.2, vmax=0.8)


---

### 6. Using `matshow()` for Matrix-Like Data

matshow() is optimized for visualizing 2D arrays:

plt.matshow(matrix)
plt.title("Matrix View with matshow()")
plt.colorbar()
plt.show()


---

### 7. Annotating Heatmaps

fig, ax = plt.subplots()
cax = ax.imshow(matrix, cmap='plasma')

# Add text annotations
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
ax.text(j, i, f'{matrix[i, j]:.2f}', ha='center', va='center', color='white')

plt.title("Annotated Heatmap")
plt.colorbar(cax)
plt.show()


---

### 8. Displaying Multiple Images in Subplots

fig, axs = plt.subplots(1, 2, figsize=(10, 4))

axs[0].imshow(matrix, cmap='Blues')
axs[0].set_title("Blues")

axs[1].imshow(matrix, cmap='Greens')
axs[1].set_title("Greens")

plt.tight_layout()
plt.show()


---

### 9. Saving Heatmaps and Figures

plt.imshow(matrix, cmap='magma')
plt.title("Save This Heatmap")
plt.colorbar()
plt.savefig("heatmap.png", dpi=300)
plt.close()


---

### 10. Summary

imshow() and matshow() visualize 2D data or images
Heatmaps are great for matrix or correlation data
• Use colorbars and annotations to add context
• Customize colormaps with cmap, vmin, vmax
• Save your visualizations easily using savefig()

---

### Exercise

• Load a grayscale image using NumPy and display it.
• Create a 10×10 heatmap with annotations.
• Display 3 subplots of the same matrix using 3 different colormaps.
• Save one of the heatmaps with high resolution.

---

#Python #Matplotlib #Heatmaps #DataVisualization #Images #ColorMapping

https://t.iss.one/DataScienceM
6