如何创建没有预定数量子图的图形

How to create a figure without a predetermined number of subplots

我正在尝试将子图行附加到循环内的 Matplotlib 图。

这个有效:

from sklearn.datasets import load_iris 
import numpy as np 
import pandas as pd 

iris_data = load_iris() 
join_pd_df = pd.DataFrame( 
  data = np.c_[ 
    iris_data['data'], 
    iris_data['target'], 
  ], 
  columns = iris_data['feature_names'] + ['target'] 
) 

import matplotlib.pyplot as plt 
import seaborn as sns 

list_of_features = [ 
  "sepal length (cm)", 
  "sepal width (cm)", 
  "petal length (cm)", 
] 

### I want to avoid this bit of pre-allocation
number_of_charts = 2 
number_of_features = len(list_of_features) 
arbitrarily_large_number_of_inches = 10 
fig, axes = plt.subplots( 
  number_of_features, 
  number_of_charts, 
  figsize=(arbitrarily_large_number_of_inches, arbitrarily_large_number_of_inches) 
) 
###:end I want to avoid this bit of pre-allocation

for iteration, feature in enumerate(list_of_features): 
  sns.regplot(x="target", y=feature, data=join_pd_df, ax=axes[iteration, 0]) 
  sns.boxplot(x=feature, y="target", data=join_pd_df, ax=axes[iteration, 1]) 

plt.subplots_adjust( 
  left = 0.1, 
  right = 0.9, 
  top = 0.9, 
  bottom = 0.1, 
  wspace = .4, 
  hspace = .4, 
) 

但我想避免预先分配子图的数量,而只是将一行子图附加到图的底部,所以大致如下:

from sklearn.datasets import load_iris 
import numpy as np 
import pandas as pd 

iris_data = load_iris() 
join_pd_df = pd.DataFrame( 
  data = np.c_[ 
    iris_data['data'], 
    iris_data['target'], 
  ], 
  columns = iris_data['feature_names'] + ['target'] 
) 

import matplotlib.pyplot as plt 
import seaborn as sns 

list_of_features = [ 
  "sepal length (cm)", 
  "sepal width (cm)", 
  "petal length (cm)", 
] 

arbitrarily_large_number_of_inches = 10 
fig = plt.figure( 
  figsize=(arbitrarily_large_number_of_inches, arbitrarily_large_number_of_inches) 
) 

for iteration, feature in enumerate(list_of_features, start=1): 
  ### I can't figure out what I'm doing wrong here because the subplots does not display properly
  correlation_chart_axes = fig.add_subplot(1, 2, 1) 
  sns.regplot(x="target", y=feature, data=join_pd_df, ax=correlation_chart_axes) 
  box_chart_axes = fig.add_subplot(1, 2, 2) 
  sns.boxplot(x=feature, y="target", data=join_pd_df, ax=box_chart_axes) 
  ###:end I can't figure out what I'm doing wrong here because the subplots does not display properly

plt.subplots_adjust( 
  left = 0.1, 
  right = 0.9, 
  top = 0.9, 
  bottom = 0.1, 
  wspace = .4, 
  hspace = .4, 
) 

关于在哪里寻找新手的任何提示或指示?我发现的大多数文章都预先分配了子图的行数和列数。附加到 Matplotlib 图形是不是还没有完成?

这里 post:Dynamically add/create subplots in matplotlib 建议这段代码:

number_of_subplots=3 # I want to avoid this preallocation
...
ax1 = subplot(number_of_subplots,1,v)
ax1.plot(x,y)

但它只添加了 1 个单列的子图。我想添加具有 2 列或更多列的子图行。

感谢您的宝贵时间

听起来目前不可能:(