绘制在背景图片顶部的seaborn heatmap

时间:2018-04-29 21:43:43

标签: python matplotlib jupyter seaborn

我正在Jupyter中通过seaborn创建一个热图,以显示选择某个坐标点的人数。我目前使用以下代码创建了热图

cm = metrics.confusion_matrix(yVals, xVals)
fig, ax = plt.subplots(figsize=(10,10))
sns.heatmap(cm, annot=True, fmt="0.3f", linewidth=0.5, cbar=False,
              cmap="Reds", square=True, ax=ax)
plt.show()

Here's a link to the picture as well if needed to see how it looks.我的问题是如何在背景图像上绘制此热图并使热图中的方块更加透明,越接近0它们就越能显示背景图像?还有一种方法可以在热图上以1而不是0来启动索引吗?

提前谢谢!

2 个答案:

答案 0 :(得分:2)

您还需要缩放/翻转图像以便它们一起绘制,因为地图可能比热图更精细。我们让Seaborn进行调整工作,然后在显示地图的imshow中进行匹配。

您可以修改或创建一个色彩图,使其透明度接近0,然后我将代码留下来向您展示如何,但结果数字不是最理想的,因为我无法在高热位置读取地图。如图所示,整个热图是半透明的。

留给读者:更改刻度线以引用地图坐标,而不是热图索引。

# add alpha (transparency) to a colormap
import matplotlib.cm from matplotlib.colors 
import LinearSegmentedColormap 
wd = matplotlib.cm.winter._segmentdata # only has r,g,b  
wd['alpha'] =  ((0.0, 0.0, 0.3), 
               (0.3, 0.3, 1.0),
               (1.0, 1.0, 1.0))

# modified colormap with changing alpha
al_winter = LinearSegmentedColormap('AlphaWinter', wd) 

# get the map image as an array so we can plot it 
import matplotlib.image as mpimg 
map_img = mpimg.imread('tunis.png') 

# making and plotting heatmap 
import numpy.random as random 
heatmap_data = random.rand(8,9) 

import seaborn as sns; sns.set()

hmax = sns.heatmap(heatmap_data,
            #cmap = al_winter, # this worked but I didn't like it
            cmap = matplotlib.cm.winter,
            alpha = 0.5, # whole heatmap is translucent
            annot = True,
            zorder = 2,
            )

# heatmap uses pcolormesh instead of imshow, so we can't pass through 
# extent as a kwarg, so we can't mmatch the heatmap to the map. Instead, 
# match the map to the heatmap:

hmax.imshow(map_img,
          aspect = hmax.get_aspect(),
          extent = hmax.get_xlim() + hmax.get_ylim(),
          zorder = 1) #put the map under the heatmap

from matplotlib.pyplot import show 
show()

Translucent heatmap plotted over a scaled map

答案 1 :(得分:2)

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.image as mpimg 

file = "./iris.csv"
df = pd.read_csv(file)
import seaborn as sns
map_img = mpimg.imread('1538287373.02485_image.png') 
 # Custom it with the same argument as 1D density plot
hmax = sns.kdeplot(df.sepal_width, df.sepal_length, cmap="Reds", shade=True, bw=.15)
hmax.collections[0].set_alpha(0)

plt.imshow(map_img, zorder=0, extent=[0.5, 8.0, 1.0, 7.0])
plt.show()

Output