Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add rectangle patches in Python Heatmap?

enter image description here

Below code gives me the heatmap output. but I want to add rectangle patches to highlight values in the range of 0.4 to 0.99 and -0.4 to -0.99

plt.figure(figsize=(15,10))
mask = np.triu(np.ones_like(corr, dtype=np.bool)) 
sns.heatmap(corr,annot=True,fmt=".2f", mask=mask,cmap="YlGnBu");

like image 543
Data_Beetle Avatar asked Jan 30 '26 16:01

Data_Beetle


1 Answers

The heatmap data for the categorical variables was taken from Kaggle's home price data. To add a rectangle, add a rectangle to add_patch(). The coordinates are based on the lower left corner, so specify the x and y of each in tuples, and specify the width and height. We also specify not to fill it.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig, ax = plt.subplots(figsize=(18,18))
df_house = pd.read_csv('./data/house_prices_train.csv', index_col=0)
df_house_corr = df_house.corr()
mask = np.triu(np.ones_like(df_house_corr, dtype=np.bool)) 
sns.heatmap(df_house_corr, annot=True, fmt=".2f", mask=mask, cmap="YlGnBu")

ax.add_patch(
     patches.Rectangle(
         (5, 6),
         1.0,
         35.0,
         edgecolor='red',
         fill=False,
         lw=2
     ) )

plt.show()

enter image description here

like image 61
r-beginners Avatar answered Feb 01 '26 04:02

r-beginners



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!