Home > Software engineering >  Join subplots in one single image in matplotlib
Join subplots in one single image in matplotlib

Time:03-11

I have this function which receives a dataframe, a string and a list of parameters:

def descriptive_analysis(df, net, parameters): 
    '''
    df: pandas dataframe
    net: str with network name
    parameters: list of 7 (str) features
    '''

    for parameter in parameters:
        fig = plt.figure(figsize=(20,5))
        # subplot 1
        plt.subplot(1, 3, 1)
        # histogram
        sns.histplot(df[parameter])
        # subplot 2
        plt.subplot(1, 3, 2)
        # boxplot
        df[parameter].plot(kind = 'box')
        # subplot 3 
        ax3 = plt.subplot(1,3,3)
        # qqplot Gráfico de probabilidade da Normal
        sm.qqplot(df[parameter], line='s', ax=ax3)
        # add legend
        fig.legend(labels=[f'network:{net}, metric:{parameter}'])

The above generates multiple triad subplots, for each parameter, for each network, like so:

enter image description here

so:

enter image description here

and so etc:

enter image description here


How do I plot one single image with all triad subplots (total 7) joined together, for each network?

CodePudding user response:

  1. Create a 7x3 ax_grid of subplots outside the loop.
  2. Zip the parameters with ax_grid to iterate each parameter with an ax_row.
  3. Place the hist/box/qq plots onto its respective ax=ax_row[...].
def descriptive_analysis(df, net, parameters):
    '''
    df: pandas dataframe
    net: str with network name
    parameters: list of 7 (str) features
    '''

    fig, ax_grid = plt.subplots(len(parameters), 3, constrained_layout=True)

    for parameter, ax_row in zip(parameters, ax_grid):
        sns.histplot(df[parameter], ax=ax_row[0])
        df[parameter].plot(kind='box', ax=ax_row[1])
        sm.qqplot(df[parameter], line='s', ax=ax_row[2])

    fig.savefig('results.png', dpi=300)
  • Related