【问题标题】:Adding seaborn clustermap to figure with other plots将 seaborn clustermap 添加到其他绘图中
【发布时间】:2019-01-19 13:44:25
【问题描述】:

我正在尝试将以下两个图放在同一个图中:

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)

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

最好的方法是什么?

【问题讨论】:

    标签: python python-3.x matplotlib seaborn


    【解决方案1】:

    确实,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()
    

    对于具有多个图形级函数来组合解决方案的情况要复杂得多,例如in this question.

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 1970-01-01
      • 2020-11-03
      • 2018-08-21
      • 2019-03-25
      • 2016-04-06
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多