簡體   English   中英

在背景圖片上繪制 seaborn 熱圖

[英]Plotting seaborn heatmap on top of a background picture

我正在通過 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 開始?

如果需要查看它的外觀,這里還有指向圖片的鏈接。

如果需要查看它的外觀,這里還有指向圖片的鏈接。

您還需要縮放/翻轉圖像,以便它們一起繪制,因為地圖的分辨率可能比熱圖要精細得多。 我們讓 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()

在縮放地圖上繪制的半透明熱圖

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()

輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM