Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Add a custom border to certain cells in a Matplotlib / Seaborn plot
Adding custom borders to specific cells in Matplotlib/Seaborn plots helps highlight important data points. You can use Rectangle patches to create colored borders around target cells in heatmaps.
Basic Approach
The process involves creating a heatmap, accessing its axes, and adding rectangle patches with custom colors and line widths ?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Create sample data
data = pd.DataFrame({
"col1": [1, 4, 2, 3, 5],
"col2": [3, 4, 1, 5, 2]
})
# Create clustered heatmap
g = sns.clustermap(data, figsize=(7.5, 3.5))
ax = g.ax_heatmap
# Add custom border to specific cells
border_color = "yellow"
ax.add_patch(plt.Rectangle((1, 2), 2, 1, fill=False,
edgecolor=border_color, lw=5))
plt.show()
Multiple Custom Borders
You can add multiple borders with different colors and styles to highlight various cell groups ?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Create sample dataset
data = pd.DataFrame({
"A": [1, 4, 2, 3, 5],
"B": [3, 4, 1, 5, 2],
"C": [2, 1, 4, 2, 3]
})
# Create heatmap
plt.figure(figsize=(8, 6))
ax = sns.heatmap(data, annot=True, cmap="Blues")
# Add multiple custom borders
# Red border around single cell
ax.add_patch(plt.Rectangle((0, 1), 1, 1, fill=False,
edgecolor="red", lw=3))
# Green border around 2x2 area
ax.add_patch(plt.Rectangle((1, 2), 2, 2, fill=False,
edgecolor="green", lw=4))
# Yellow dashed border
ax.add_patch(plt.Rectangle((0, 3), 3, 1, fill=False,
edgecolor="yellow", lw=2, linestyle="--"))
plt.title("Heatmap with Custom Cell Borders")
plt.show()
Rectangle Parameters
| Parameter | Description | Example |
|---|---|---|
(x, y) |
Bottom-left corner position | (1, 2) |
width |
Rectangle width in cells | 2 |
height |
Rectangle height in cells | 1 |
edgecolor |
Border color | "red" |
lw |
Line width | 3 |
Dynamic Border Selection
You can programmatically add borders based on data conditions ?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# Create sample data
data = pd.DataFrame(np.random.randint(1, 10, (4, 4)),
columns=["A", "B", "C", "D"])
plt.figure(figsize=(8, 6))
ax = sns.heatmap(data, annot=True, cmap="viridis")
# Add borders to cells with values greater than 6
for i in range(data.shape[0]):
for j in range(data.shape[1]):
if data.iloc[i, j] > 6:
ax.add_patch(plt.Rectangle((j, i), 1, 1, fill=False,
edgecolor="red", lw=3))
plt.title("Borders Around High Values (> 6)")
plt.show()
Conclusion
Use Rectangle patches with add_patch() to create custom cell borders in heatmaps. Adjust position, size, color, and line style to highlight specific data patterns effectively.
Advertisements
