我正在尝试将数据帧的clustermap和box 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:
我需要的是这样的事情:
感谢。
答案 0 :(得分:1)
从@mwaskom的评论中,我更多地了解了clustermap figure函数,并意识到我可以用boxplot图像替换列树形图图像。但是,我会尝试找到如何添加另一个轴而不是替换列树形图轴,以防万一我需要用方框图显示行和列树形图。但到目前为止,我得到的很好。这是代码:
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()
这导致:
答案 1 :(得分:-2)
您应该将ax作为clustermap函数的参数传递:
cax = sns.clustermap(idf, col_cluster=False, row_cluster=True, ax = ax2)
从函数clustermap(https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.clustermap.html)的文档中可以看出,执行绘图的实际函数是热图https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.heatmap.html,它接受ax作为参数。