考虑使用 pandas DataFrame.plot 和 seaborn 的 regplot 的 ax 参数:
fig, ax = plt.subplots(1, 5, figsize=(16,6))
for i,col in enumerate(boston_df.columns[1:]):
#boston_df.plot(kind='scatter', x=col, y='MEDV', ax=ax[i])
sns.regplot(x=boston_df[col], y=boston_df["MEDV"], ax=ax[i])
fig.suptitle('My Scatter Plots')
fig.tight_layout()
fig.subplots_adjust(top=0.95) # TO ACCOMMODATE TITLE
plt.show()
用随机数据演示:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
### DATA BUILD
np.random.seed(6012019)
random_df = pd.DataFrame(np.random.randn(50,6),
columns = ['MEDV', 'COL1', 'COL2', 'COL3', 'COL4', 'COL5'])
### PLOT BUILD
fig, ax = plt.subplots(1, 5, figsize=(16,6))
for i,col in enumerate(random_df.columns[1:]):
#random_df.plot(kind='scatter', x=col, y='MEDV', ax=ax[i])
sns.regplot(x=random_df[col], y=random_df["MEDV"], ax=ax[i])
fig.suptitle('My Scatter Plots')
fig.tight_layout()
fig.subplots_adjust(top=0.95)
plt.show()
plt.clf()
plt.close()
对于跨多列的多行,将分配调整为 ax,这是一个使用索引的 numpy 数组:ax[row_idx, col_idx]。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
### DATA BUILD
np.random.seed(6012019)
random_df = pd.DataFrame(np.random.randn(50,14),
columns = ['MEDV', 'COL1', 'COL2', 'COL3', 'COL4',
'COL5', 'COL6', 'COL7', 'COL8', 'COl9',
'COL10', 'COL11', 'COL12', 'COL13'])
### PLOT BUILD
fig, ax = plt.subplots(2, 7, figsize=(16,6))
for i,col in enumerate(random_df.columns[1:]):
#random_df.plot(kind='scatter', x=col, y='MEDV', ax=ax[i])
if i <= 6:
sns.regplot(x=random_df[col], y=random_df["MEDV"], ax=ax[0,i])
else:
sns.regplot(x=random_df[col], y=random_df["MEDV"], ax=ax[1,i-7])
ax[1,6].axis('off') # HIDES AXES ON LAST ROW AND COL
fig.suptitle('My Scatter Plots')
fig.tight_layout()
fig.subplots_adjust(top=0.95)
plt.show()
plt.clf()
plt.close()