I have a following problem. I would like to plot my heatmap over an image. See my simplified code below:
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from PIL import Image df = pd.DataFrame(np.array([[1, 2, 1], [4, 5, 1], [7, 8, 2], [8, 2, 3]]), columns=['a', 'b', 'c']) #make the df heatmap friendly df_cnt = df.reset_index().pivot(index='a', columns='b', values='c') #missing values df_cnt.fillna(0, inplace=True) #load an image my_image = Image.open("./image.png") #plot a an image plt.imshow(my_image, zorder = 0) #Note: I can see the image correctly in my IDE #plot a heatmap h = sns.heatmap(df_cnt) #Heatmap is displayed but it is not over the backroung image....
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.
import matplotlib.image as mpimg # add h = sns.heatmap(df_cnt, alpha=0.1, zorder=2) # update my_image = mpimg.imread("./image.png") # update # update h.imshow(my_image, aspect=h.get_aspect(), extent= h.get_xlim() + h.get_ylim(), zorder=1) plt.show() # add