我正在尝试将数据框的集群图和箱线图绘制为子图。我无法将 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'])

# 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:
python - 子图中的 Seaborn clustermap-LMLPHP

图 2:
python - 子图中的 Seaborn clustermap-LMLPHP
我需要的是这样的:
python - 子图中的 Seaborn clustermap-LMLPHP
谢谢。

最佳答案

从@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()

这导致:

python - 子图中的 Seaborn clustermap-LMLPHP

关于python - 子图中的 Seaborn clustermap,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39170455/

10-12 21:53