[英]Plot subplots using seaborn pairplot
如果使用以下代碼繪制該圖,則該圖有效,並且可以在一行中看到所有子圖。 我可以將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.讓我們簡單地定義一個空的熊貓數據框。
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.)中創建的矩陣中的位置。
因此,我們得到了一個矩陣圖:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.