Joe*_*Joe 6 python matplotlib seaborn jupyter
我正在通过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()
Run Code Online (Sandbox Code Playgroud)
如果需要查看图片的外观,也可以使用此图片的链接。我的问题是,如何将这个热图绘制在背景图像的上方,并使热图中的正方形越接近0,则它们越能显示背景图像,从而使其更加透明?还有一种方法可以将热图上的索引从1而不是0开始?
先感谢您!
cph*_*wis 10
您还需要缩放/翻转图像,以便它们一起绘制,因为地图的分辨率可能比热图要精细得多。我们让 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()
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4031 次 |
最近记录: |