Вставьте фигуру в один из сюжетов - PullRequest
0 голосов
/ 05 ноября 2018

У меня есть сетка подзаговоров в matplotlib.
Для большинства из них я определяю, какой участок будет нормальным. Для одного из них существует некоторая логика, которую я инкапсулировал внутри функции distribution_of_graphs.

Могу ли я использовать фигуру, которую эта функция возвращает в качестве графика, в качестве одного из вспомогательных участков?

def distribution_of_graphs(net):

    # Some logic to get df from net object
    df = net.logic()

    pal = sns.cubehelix_palette(len(list(df)), rot=-.25, light=.7)
    g = sns.FacetGrid(df, row="grad", hue="grad", aspect=15, height=5, palette=pal)

    # Draw the densities in a few steps
    g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=0.6, lw=1.5, bw=.2)
    g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw=.2) ## White contour
    g.map(plt.axhline, y=0, lw=2, clip_on=False) ## Will serve as the x axis

    # Define and use a simple function to label the plot in axes coordinates
    def label(x, color, label):
        ax = plt.gca()
        ax.text(0, .2, label, fontweight="bold", color=color,
                ha="left", va="bottom", transform=ax.transAxes)
        ax.set_xlim([-1.5, 1.5])
    g.map(label, "x")

    # Set the subplots to overlap
    g.fig.subplots_adjust(hspace=-.75)

    # Remove axes details that don't play well with overlap
    g.set_titles("")
    g.set(yticks=[])
    g.despine(bottom=True, left=True)
    return g

Эта функция создает следующее изображение: enter image description here

Я хотел бы использовать результирующий график этой функции в качестве ax4 следующего рисунка:

plt.figure(figsize=(15,15))
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=1)
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=1)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0), colspan=2)
sns.lineplot(xaxis, net.weight_stats['gradWinp'], ax=ax1, color='blue').set_title('grad W1')
sns.lineplot(xaxis, net.weight_stats['gradWout'], ax=ax2, color='red').set_title('grad W2')
sns.lineplot(xaxis, net.weight_stats['gradWinp'], ax=ax3, color='blue', label='grad W1')
sns.lineplot(xaxis, net.weight_stats['gradWout'], ax=ax3, color='red', label='grad W2')

# What I am missing
ax4.plot(distribution_of_graphs(net))

# Previos behavior working properly
#sns.kdeplot(norm_dW1, shade=True, ax=ax4)
#sns.kdeplot(norm_dW2, shade=True, ax=ax4)

plt.plot()

Теперь он оставляет это пространство пустым и создает график из функции на отдельном рисунке:

enter image description here С сообщением об ошибке: TypeError: float() argument must be a string or a number, not 'FacetGrid'

Спасибо!

1 Ответ

0 голосов
/ 05 ноября 2018

Два предложения:

1) Вы можете построить внутри функции. В качестве простого примера,

def plotxy(x,y):
    plot(x,y)
    return

subplot(4,1,3)
plotxy(x,y) # will plot in the 4th subplot

2) Передайте ручку оси в вашу функцию

def plotxy(ax,x,y):
    ax.plot(x,y)
    return

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