【问题标题】:Plotting seaborn heatmap on top of a background picture在背景图片上绘制 seaborn 热图
【发布时间】:2018-04-29 21:43:42
【问题描述】:

我正在 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()

我的问题是如何在背景图像上绘制此热图,并使热图中的方块越接近 0 越透明,以便更多地显示背景图像?还有没有办法让热图上的索引从 1 而不是 0 开始?

如果需要查看图片的外观,这里还有图片链接。

【问题讨论】:

  • 您需要在坐标轴上添加一个 imshow 较低的 zorder 绘图,并为热量使用自定义颜色图,其中 alpha 小于 1。一般来说,使用 matplotlib 而不是 seaborn 创建热图可能会使您拥有的选项更加透明,请参阅this example

标签: python matplotlib jupyter seaborn


【解决方案1】:

您还需要缩放/翻转图像,以便将它们绘制在一起,因为地图的分辨率可能比热图要精细得多。我们让 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()

【讨论】:

  • 值得一票。可以改进代码以不产生SyntaxError
【解决方案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()

【讨论】:

    猜你喜欢
    • 2020-10-12
    • 1970-01-01
    • 2018-11-23
    • 2018-11-29
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2022-01-21
    相关资源
    最近更新 更多