Создание подзаголовков из вывода (единственного графика) функции - PullRequest
0 голосов
/ 27 мая 2018

У меня есть функция, которая возвращает исключительный график.Я хотел бы повторить эту функцию трижды и иметь 3 графика рядом в формате 1x3.Как мне добиться этого?

def plot_learning_curve(estimator, X, y, ylim=None, cv=None,
                        n_jobs=-1, train_sizes=np.linspace(.1, 1.0, 5)):
    """Generate a simple plot of the test and training learning curve"""
    plt.figure()
    plt.title(str(estimator).split('(')[0]+ " learning curves")
    if ylim is not None:
        plt.ylim(*ylim)
    plt.xlabel("Training examples")
    plt.ylabel("Score")
    train_sizes, train_scores, test_scores = learning_curve(
        estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    plt.grid()

    plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
                     train_scores_mean + train_scores_std, alpha=0.1,
                     color="r")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
                     test_scores_mean + test_scores_std, alpha=0.1, color="g")
    plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
             label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
             label="Cross-validation score")

    plt.legend(loc="best")
    return plt

Я попробовал этот метод, но он просто возвращает пустую сетку 1x3 с графиками под этой пустой сеткой

fig, axes = plt.subplots(nrows = 1, ncols = 3, sharex="all", figsize=(15,5), squeeze=False)

axes[0][0] = plot_learning_curve(tuned_clfs_vert_title2[0][0][1],Xs_train1,Y_train1,cv=skfold)
axes[0][1] = plot_learning_curve(tuned_clfs_vert_title2[0][1][1],Xs_train1,Y_train1,cv=skfold)
axes[0][2] = plot_learning_curve(tuned_clfs_vert_title2[0][2][1],Xs_train1,Y_train1,cv=skfold)

Мне интересно использовать эту функцию построения кривой обучениякак «модуль».Я предполагаю, что альтернативный способ - написать цикл внутри этой функции.

1 Ответ

0 голосов
/ 27 мая 2018

Вы не предоставляете ось для функции построения графика.Я не могу использовать ваш код, потому что это не Минимальный, Полный и Проверяемый пример .Но вот один подход, который вы можете адаптировать к вашим потребностям:

#plot function with defined axis
def plot_subplot(ax, xdata, ydata, plotnr):
    ax.plot(xdata, ydata)
    ax.set_title("Plot {}".format(plotnr))
    return

#subplot grid 2 x 3 to illustrate the example for more than one row/column
fig, axes = plt.subplots(nrows = 2, ncols = 3, sharex = "all", figsize = (15,5), squeeze=False)
#reproducibility seed
np.random.seed(54321)
#loop over axes, we have to flatten the array "axes", if "fig" contains more than one row
for i, ax in enumerate(axes.flatten()):
    #generate random length for data
    lenx = np.random.randint(5, 30)
    #generate random data, provide information to subplot function
    plot_subplot(ax, np.arange(lenx), np.random.randint(1, 100, lenx), i)

plt.show()

Вывод:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...