python - Python:如何并排绘制多个 seaborn 热图?
问题描述
我有一个具有 20 多个功能的 Pandas 数据框。我想看看他们的相关矩阵。我使用如下代码创建热图,使用subset1
,subset2
等:
import seaborn as sns
cmap = sns.diverging_palette( 220 , 10 , as_cmap = True )
sb1 = sns.heatmap(
subset1.corr(),
cmap = cmap,
square=True,
cbar_kws={ 'shrink' : .9 },
annot = True,
annot_kws = { 'fontsize' : 12 })
我希望能够并排显示上述代码生成的多个热图,如下所示:
display_side_by_side(sb1, sb2, sb3, . . .)
我不确定如何执行此操作,因为上面的第一个代码块不仅将结果保存到sb1
,而且还绘制了热图。另外,不知道如何编写函数,display_side_by_side()
. 我将以下内容用于 Pandas 数据框:
# create a helper function that takes pd.dataframes as input and outputs pretty, compact EDA results
from IPython.display import display_html
def display_side_by_side(*args):
html_str = ''
for df in args:
html_str = html_str + df.to_html()
display_html(html_str.replace('table','table style="display:inline"'),raw=True)
根据 Simas Joneliunas 下面的第一个答案,我提出了以下工作解决方案:
import matplotlib.pyplot as plt
import seaborn as sns
# Here we create a figure instance, and two subplots
fig = plt.figure(figsize = (20,20)) # width x height
ax1 = fig.add_subplot(3, 3, 1) # row, column, position
ax2 = fig.add_subplot(3, 3, 2)
ax3 = fig.add_subplot(3, 3, 3)
ax4 = fig.add_subplot(3, 3, 4)
ax5 = fig.add_subplot(3, 3, 5)
# We use ax parameter to tell seaborn which subplot to use for this plot
sns.heatmap(data=subset1.corr(), ax=ax1, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})
sns.heatmap(data=subset2.corr(), ax=ax2, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})
sns.heatmap(data=subset3.corr(), ax=ax3, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})
sns.heatmap(data=subset4.corr(), ax=ax4, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})
sns.heatmap(data=subset5.corr(), ax=ax5, cmap = cmap, square=True, cbar_kws={'shrink': .3}, annot=True, annot_kws={'fontsize': 12})
解决方案
你应该看看 matplotlib.add_subplot:
# Here we create a figure instance, and two subplots
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
# We use ax parameter to tell seaborn which subplot to use for this plot
sns.pointplot(x="x", y="y", data=data, ax=ax1)
推荐阅读
- facebook - 如何使用测试用户将 Facebook 页面链接到 Instagram 页面?
- python - 如何使用仅提供两个点的宽度来创建线条/多边形?
- ruby - 有没有办法专门循环多次
- r - R Shiny selectizeInput - 每次拖动后拖放而不打开下拉菜单
- sql - 删除导致死锁的旧行
- vb.net - RadComboBox 上的自定义验证不起作用
- google-cloud-platform - 在 GCP 控制台中创建磁盘显示加载失败
- google-chrome - google chrome devtools 元素/属性的问题
- ios - 当我尝试运行我的项目时,我收到此错误“Command PrecompileSwiftBridgingHeader failed with a nonzero exit code”
- python - 如何pytest装饰器分配给多个功能