首页 文章

使用seaborn pairplot绘制子图

提问于
浏览
0

如果我使用以下代码绘制绘图,它可以工作,我可以在一行中看到所有子图 . 我可以专门将cols的数量分成三个或两个并显示它们 . 但我有30列,我想使用循环机制,以便它们绘制在4x4子图的网格中

regressionCols = ['col_a', 'col_b', 'col_c', 'col_d', 'col_e']
sns.pairplot(numerical_df, x_vars=regressionCols, y_vars='price',height=4, aspect=1, kind='scatter')
plt.show()

代码使用循环如下 . 但是,我没有看到任何渲染 .

nr_rows = 4
 nr_cols = 4

 li_cat_cols = list(regressionCols)
 fig, axs = plt.subplots(nr_rows, nr_cols, figsize=(nr_cols*4,nr_rows*4), squeeze=False)

 for r in range(0, nr_rows):
      for c in range(0,nr_cols):  
         i = r*nr_cols+c

         if i < len(li_cat_cols):
             sns.set(style="darkgrid")
             bp=sns.pairplot(numerical_df, x_vars=li_cat_cols[i], y_vars='price',height=4, aspect=1, kind='scatter')
             bp.set(xlabel=li_cat_cols[i], ylabel='Price')
 plt.tight_layout()    
 plt.show()

不知道我错过了什么 .

1 回答

  • 1

    我认为你没有在矩阵图中连接每个子图空间来分散循环中生成的图 .

    也许这种带有内部熊猫图的解决方案可能适合您:例如,

    1.让我们简单地定义一个空的pandas数据帧 .

    numerical_df = pd.DataFrame([])
    

    2.根据它们创建一些随机功能和价格:

    numerical_df['A'] = np.random.randn(100)
    numerical_df['B'] = np.random.randn(100)*10 
    numerical_df['C'] = np.random.randn(100)*-10
    numerical_df['D'] = np.random.randn(100)*2
    numerical_df['E'] = 20*(np.random.randn(100)**2)
    numerical_df['F'] = np.random.randn(100)
    numerical_df['price'] = 2*numerical_df['A'] +0.5*numerical_df['B'] - 9*numerical_df['C'] + numerical_df['E'] + numerical_df['D']
    

    3.定义行数和列数 . 使用nr_rows和nr_cols创建子图空间 .

    nr_rows = 2 
    nr_cols = 4
    fig, axes = plt.subplots(nrows=nr_rows, ncols=nr_cols, figsize=(15, 8))
    for idx, feature in enumerate(numerical_df.columns[:-1]):
        numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])
    

    4.枚举数据框中的每个要素并绘制带有价格的散点图:

    for idx, feature in enumerate(numerical_df.columns[:-1]):
    
        numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])
    

    其中 axes[idx // 4, idx % 4] 定义了您在(3.)中创建的矩阵中每个散点图的位置

    所以,我们得到了一个矩阵图:

    Scatterplot matrix

相关问题