Seaborn集群图在子图中的应用

5

我想要将一个数据框的clustermap和box plots作为子图一起绘制。但是由于clustermap是一个figure level plot,所以我无法成功将其作为子图绘制。有没有什么办法可以实现这个目标呢?

import pandas as pd
import seaborn as sns

# initiliaze a dataframe with index and column names
idf = pd.DataFrame.from_items([('A', [1, 2, 3]), 
                               ('B', [4, 5, 6]), 
                               ('C', [10, 20, 30]), 
                               ('D', [14, 15, 16])], 
                               orient='index', columns=['x', 'y','z'])

# Get the figure and two subplots, unpack the axes array immediately
fig, (ax1, ax2) = plt.subplots(2, sharex=True)

# Plot a boxplot in one of the subplot
idf.plot(kind='box', ax=ax1)

# Plot the clustermap in the other subplot
cax = sns.clustermap(idf, col_cluster=False, row_cluster=True)

# I tried to change the axis from the clustermap to subplot axis
# but I don't think this works like this
cax.ax_heatmap=ax2

# Show the plot
plt.show()

我现在得到的是:
图片1: enter image description here
图片2: enter image description here 我需要的是像这样的东西: enter image description here 谢谢。

1
绘制聚类图,然后向图形添加坐标轴并将箱线图放入其中。 - mwaskom
非常感谢您的帮助。我尝试使用您的解决方案并得到了一些结果。我仍然需要更多的理解,但现在我从您的建议中找到了一个解决方法。如果有用的话,我会将其发布为答案。 - Gaurav Jain
2个回答

3

从@mwaskom的评论中,我进一步了解了clustermap图形函数,并意识到我可以用箱线图图像替换列树状图像。但是,为了防止需要同时显示行和列树状图与箱线图,我会尝试找到如何添加另一个轴。但目前我得到的结果对我来说已经很好了。以下是代码:

import pandas as pd
import seaborn as sns

# initiliaze a dataframe with index and column names
idf = pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6]), ('C', [10, 20, 30]), ('D', [14, 15, 16])], orient='index', columns=['x', 'y', 'z'])

# Plot the clustermap which will be a figure by itself
cax = sns.clustermap(idf, col_cluster=False, row_cluster=True)

# Get the column dendrogram axis
cax_col_dend_ax = cax.ax_col_dendrogram.axes

# Plot the boxplot on the column dendrogram axis
# I still need to figure out how to show the axis for this boxplot
idf.plot(kind='box', ax=cax_col_dend_ax)

# Show the plot
plt.show()

这将导致:

输入图像描述


-5

1
谢谢。那是我尝试的第一件事,但我收到了错误信息:http://paste2.org/YdtGPBUf - Gaurav Jain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接