【问题标题】:Plot subplots using seaborn pairplot使用 seaborn pairplot 绘制子图
【发布时间】:2018-11-23 11:10:53
【问题描述】:

如果我使用以下代码绘制图,它可以工作,并且我可以在一行中看到所有子图。我可以专门将 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()

不知道我错过了什么。

【问题讨论】:

  • 第一个调用pairplot 的方法似乎是可取的;除非你有理由不使用它。我不明白那个原因。如果您介意更详细地解释它,它会更容易提供帮助。此外,提供可运行的示例代码有助于给出答案。

标签: python pandas matplotlib seaborn


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2021-10-01
    • 2016-10-15
    • 2018-12-09
    • 2020-06-24
    • 1970-01-01
    相关资源
    最近更新 更多