我正在通过 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 开始?如果需要查看它的外观,这里还有指向图片的链接。
最佳答案
您还需要缩放/翻转图像,以便它们一起绘制,因为 map 的分辨率可能比热图要精细得多。我们让 Seaborn 做它的调整工作,然后在显示 map 的 imshow
中进行匹配。
您可以修改或创建颜色图以使透明度接近 0,我留下了代码来向您展示如何操作,但结果图并不理想,因为我无法在高温位置读取 map 。如图所示,整个热图是半透明的。
留给读者:更改刻度以引用 map 坐标,而不是热图索引。
# 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()
关于python - 在背景图片上绘制 seaborn 热图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50091591/