Search code examples
pythonsubplot

Using multiple datasets in Gridspec


I am trying to create subplot inside a subplot, and I have found some code which can do this using the gridspec method. I have managed to fix the code so the figures are displayed as I want, but I can't figure out how to get a different dataset in each sub-figure. This is what I have:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(10, 8))
outer = gridspec.GridSpec(2, 2, wspace=0.1, hspace=0.1)

for i in range(4):
    inner = gridspec.GridSpecFromSubplotSpec(4, 1,
                    subplot_spec=outer[i], wspace=0.1, hspace=0.1)

    for j in range(4):
        ax = plt.Subplot(fig, inner[j])
        a = ax.plot(df)
        t.set_ha('center')
        ax.set_xticks([])
        ax.set_yticks([])
        fig.add_subplot(ax)

enter image description here

I have tried multiple options to achieve what I want without success.

IF anyone could help with this I would appreciate it.

Thanks.


Solution

  • I have managed to solve my problem now. What I did was, instead of trying to put multple ax.plot() lines or putting multiple DataFrames inside ax.plot(df1, df2, df3) etc. I created a list which I put inside the For Loop. I also created a column variable to go in the "inner loop". If using Nested Loops like this, the value that changes horizontally must go in the outer loop while the value that changes vertically must go in the inner loop. In my case, the first subplot contains four different columns from the same DataFrame, the second contains four different columns for another DataFrame, and so on.

    This is how it is implemented in the code:

    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    
    residual_list = (['df_168h', 'residuals_168', 'residuals_168_d', 'residuals_168_weekend'])
    
    fig = plt.figure(figsize=(10, 8))
    outer = gridspec.GridSpec(2, 2, wspace=0.1, hspace=0.1)
    
    
    for i, s in zip(range(4), residual_list):
        inner = gridspec.GridSpecFromSubplotSpec(4, 1,
                        subplot_spec=outer[i], wspace=0.1, hspace=0.1)
    
        for j, column in zip(range(4), df_168h):
            ax = plt.Subplot(fig, inner[j])
            a = ax.plot(locals()[s][column])
            t.set_ha('center')
            ax.set_xticks([])
            ax.set_yticks([])
            fig.add_subplot(ax)