gpt4 book ai didi

python - 在 seaborn FacetGrid 热图中获取图例

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:11 44 4
gpt4 key购买 nike

我们如何获得 seaborn FacetGrid 热图的图例? .add_legend() 方法对我不起作用。

使用 this previous question 中的代码:

import pandas as pd
import numpy as np
import itertools
import seaborn as sns

print("seaborn version {}".format(sns.__version__))
# R expand.grid() function in Python
# https://stackoverflow.com/a/12131385/1135316
def expandgrid(*itrs):
product = list(itertools.product(*itrs))
return {'Var{}'.format(i+1):[x[i] for x in product] for i in range(len(itrs))}

methods=['method 1', 'method2', 'method 3', 'method 4']
times = range(0,100,10)
data = pd.DataFrame(expandgrid(methods, times, times))
data.columns = ['method', 'dtsi','rtsi']
data['nw_score'] = np.random.sample(data.shape[0])

def facet(data,color):
data = data.pivot(index="dtsi", columns='rtsi', values='nw_score')
g = sns.heatmap(data, cmap='Blues', cbar=False)

with sns.plotting_context(font_scale=5.5):
g = sns.FacetGrid(data, col="method", col_wrap=2, size=3, aspect=1)
g = g.map_dataframe(facet)
g.add_legend()
g.set_titles(col_template="{col_name}", fontweight='bold', fontsize=18)

enter image description here

最佳答案

您想要的(用 matplotlib 术语)是颜色条,而不是图例。在matplotlib中,前者用于连续数据,后者用于分类数据。 FacetGrid 中并未内置颜色栏支持,但不难扩展您的示例代码以添加颜色栏:

import pandas as pd
import numpy as np
import itertools
import seaborn as sns

methods=['method 1', 'method2', 'method 3', 'method 4']
times = range(0, 100, 10)
data = pd.DataFrame(list(itertools.product(methods, times, times)))
data.columns = ['method', 'dtsi','rtsi']
data['nw_score'] = np.random.sample(data.shape[0])

def facet_heatmap(data, color, **kws):
data = data.pivot(index="dtsi", columns='rtsi', values='nw_score')
sns.heatmap(data, cmap='Blues', **kws) # <-- Pass kwargs to heatmap

with sns.plotting_context(font_scale=5.5):
g = sns.FacetGrid(data, col="method", col_wrap=2, size=3, aspect=1)

cbar_ax = g.fig.add_axes([.92, .3, .02, .4]) # <-- Create a colorbar axes

g = g.map_dataframe(facet_heatmap,
cbar_ax=cbar_ax,
vmin=0, vmax=1) # <-- Specify the colorbar axes and limits

g.set_titles(col_template="{col_name}", fontweight='bold', fontsize=18)
g.fig.subplots_adjust(right=.9) # <-- Add space so the colorbar doesn't overlap the plot

enter image description here

我已将我所做的更改及其基本原理作为内嵌注释指出。

关于python - 在 seaborn FacetGrid 热图中获取图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34552770/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com