添加 seaborn clustermap 以与其他图一起显示

Jac*_*tad 6 python matplotlib python-3.x seaborn

我试图将以下两个图放在同一个图上:

import seaborn as sns; sns.set(color_codes=True)
import matplotlib.pyplot as plt
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
iris = sns.load_dataset("iris")
sns.boxplot(data=iris, orient="h", palette="Set2", ax = ax1)
species = iris.pop("species")
lut = dict(zip(species.unique(), "rbg"))
row_colors = species.map(lut)
sns.clustermap(iris, row_colors=row_colors, ax = ax2)
Run Code Online (Sandbox Code Playgroud)

我知道 clustermap 返回一个数字,所以这不起作用。但是,我仍然需要一种方法来将这些图彼此相邻(水平)呈现。sns.heatmap 返回一个轴,但它不支持聚类或颜色注释。

做这个的最好方式是什么 ?

Imp*_*est 6

确实,clustermap像其他一些seaborn 函数一样,创建了自己的图形。您对此无能为力,但只要您希望在最终图形中包含的所有其他内容都可以在轴内创建,例如在这种情况下的boxplot,解决方案就相对简单。

您可以简单地使用clustermap为您创建的图形。然后的想法是操纵轴的网格规格,以便为其他轴留下一些位置。

import seaborn as sns; sns.set(color_codes=True)
import matplotlib.pyplot as plt
import matplotlib.gridspec

iris = sns.load_dataset("iris")
species = iris.pop("species")

lut = dict(zip(species.unique(), "rbg"))
row_colors = species.map(lut)

#First create the clustermap figure
g = sns.clustermap(iris, row_colors=row_colors, figsize=(13,8))
# set the gridspec to only cover half of the figure
g.gs.update(left=0.05, right=0.45)

#create new gridspec for the right part
gs2 = matplotlib.gridspec.GridSpec(1,1, left=0.6)
# create axes within this new gridspec
ax2 = g.fig.add_subplot(gs2[0])
# plot boxplot in the new axes
sns.boxplot(data=iris, orient="h", palette="Set2", ax = ax2)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

对于具有多个图形级函数来组合解决方案的情况要复杂得多,例如在这个问题中看到的。