Вставить график из вызова функции в подзаговоры - PullRequest
0 голосов
/ 06 марта 2019

У меня есть функция, которая выдает именно те графики, которые мне нужны:

def graph(x, y, yName, dataset, colour, residuals = False, calc_tau = False):
    """
    Takes as an argument two arrays, one for x and one y, a string for the
    name of the y-variable, and two colours (which could be strings, values
    or iterators).
    Plots a scatter graph of the array against log(z), along with the best fit
    line, its equation and its regression coefficient, as well as Kendall's tau
    and the total number of points plotted.
    """

    arrayresults, arrayresids, arrayparams, arrayfit, arrayequation, arraytau = computeLinearStats(x,
                                                                      y,
                                                                     yName, calc_tau)
    count = np.count_nonzero(~np.logical_or(np.isnan(x), np.isnan(y)))
#    arrayequation = 'r\'' + yName +arrayequation[arrayequation.index('='):]
    plt.scatter(x, y,
#                label = arrayequation,
                s = 10,
                alpha = 0.5,
                c = colour)
    if calc_tau:                #if calc_tau is set to True, display the value
                                #in the legend along with equation, r and n
        plt.plot(x, arrayfit,
                 label = r'''%s
    r=%g
    $\tau$=%g
    n=%d'''%(arrayequation, arrayparams[2], arraytau[0], count),
                 c = colour)
    else:                       #otherwise just display equation, r and n
        plt.plot(x, arrayfit,
                 label = r'''%s
    $r=%g$
    $n=%d$
    $r^2n=%.2f$'''%(arrayequation, arrayparams[2], count, arrayresults.nobs*arrayparams[2]**2),
                 c = colour)
    legendfont = 16
    labelfont = 20
    plt.xlabel('$log_{10}(z)$', fontsize = labelfont)
    plt.ylabel('Magnitude combination, %s dataset'%dataset, fontsize = labelfont)
    plt.legend(fontsize = legendfont)
    plt.xticks(fontsize = labelfont)
    plt.yticks(fontsize = labelfont)
    plt.grid(True, which = 'both')
#    plt.title(r'The three best high-$r$ combinations in both Hunstead and MgII', fontsize = labelfont)
    if residuals:
        plotResids(x, y, yName, dataset, colour)
    plt.show()
    return arrayresults, arrayresids, arrayparams, arrayfit, arrayequation, arraytau

, которые я могу вызвать несколько раз, например:

enter image description here и enter image description here

Это своего рода специальная функция, но она создает графики так, как я хочу, чтобы они выглядели.Существует ли простой способ объединения графиков, выводимых несколькими вызовами функции, в набор вспомогательных участков?Я пробовал что-то вроде

x = sources['z']
    y1 = I-W2
    y2 = W3-U
    fig,ax = plt.subplots(2,1, sharex=True, sharey=False, gridspec_kw={'hspace': 0})
    fig.suptitle('Graphs')
    ax[0].scatter(x, y1, c='red', s = 10, alpha = 0.3)
    ax[1].scatter(x, y2, c='purple', s = 10, alpha = 0.3)

, но я хотел бы их со всеми снаряжениями.В идеале, я бы хотел, чтобы ax1 и ax2 вызывали мою графическую функцию и отображали вывод в субплотах.Возможно ли это?

РЕДАКТИРОВАТЬ: благодаря комментарию я могу использовать

x = sources['z']
y1 = I-W2
y2 = W3-U

fig,ax = plt.subplots(2,1, sharex=True, sharey=True, gridspec_kw={'hspace': 0})
ax1 = qf.graph(x, y1, 'I-W2', dataset, 'blue', ax[0], residuals = False, calc_tau = False)  #2 rows, 1 column, first plot
ax2 = qf.graph(x, y2, 'W3-U', dataset, 'red', ax[1], residuals = False, calc_tau = False)  #2 rows, 1 column, second plot
fig.suptitle('Graphs')

для производства

enter image description here

но как мне получить один график в верхнем положении (топор [0])?

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