I have a following problem. I would like to plot my heatmap over an image. See my simplified code below:
JavaScript
x
28
28
1
import pandas as pd
2
import seaborn as sns
3
import matplotlib.pyplot as plt
4
from PIL import Image
5
6
7
df = pd.DataFrame(np.array([[1, 2, 1], [4, 5, 1], [7, 8, 2], [8, 2, 3]]),
8
columns=['a', 'b', 'c'])
9
10
#make the df heatmap friendly
11
df_cnt = df.reset_index().pivot(index='a',
12
columns='b', values='c')
13
14
#missing values
15
df_cnt.fillna(0, inplace=True)
16
17
#load an image
18
my_image = Image.open("./image.png")
19
20
#plot a an image
21
plt.imshow(my_image, zorder = 0)
22
#Note: I can see the image correctly in my IDE
23
24
#plot a heatmap
25
h = sns.heatmap(df_cnt)
26
27
#Heatmap is displayed but it is not over the backroung image....
28
What is the problem here? Is it because the color for 0 values in my heatmap is black?
I tried to follow answer here, but it did not work to me: Plotting seaborn heatmap on top of a background picture
Advertisement
Answer
You can use mpl.image in the answer you are referring to to overlay the image. You need to make sure to specify the transparency of the heatmap.
JavaScript
1
11
11
1
import matplotlib.image as mpimg # add
2
h = sns.heatmap(df_cnt, alpha=0.1, zorder=2) # update
3
my_image = mpimg.imread("./image.png") # update
4
# update
5
h.imshow(my_image,
6
aspect=h.get_aspect(),
7
extent= h.get_xlim() + h.get_ylim(),
8
zorder=1)
9
10
plt.show() # add
11