Python 在背景图片上绘制海生热图
我正在通过位于朱皮特的seaborn制作一张热图,以显示选择某个坐标点的人数。我目前用以下代码创建了热图Python 在背景图片上绘制海生热图,python,matplotlib,jupyter,seaborn,Python,Matplotlib,Jupyter,Seaborn,我正在通过位于朱皮特的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",
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()
您需要在轴上添加一个
imshow
绘图和较低的zorder
,并为热量使用自定义颜色贴图,其中alpha小于1。一般来说,使用matplotlib而不是seaborn来创建热图可能会使您拥有的选项更加透明,请参见。值得投票。可以改进代码,使其不产生语法错误
。
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()