Python Forum
Trying to loop through code to plot seaborn line plots across multiple subplots - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Trying to loop through code to plot seaborn line plots across multiple subplots (/thread-38870.html)



Trying to loop through code to plot seaborn line plots across multiple subplots - eyavuz21 - Dec-05-2022

Hey all,

I am trying to loop through a dataframe 'out' and create a separate subplot for each group and level.

There are 35 groups and 5 levels, producing 175 plots in total.

I thus want to create 5 figures each with 35 subplots (7 rows and 5 columns).

However, when I try to do this with the code below, all of the subplots produced are empty.

I would be so grateful for a helping hand!

I have attached some example data below.

h = 0
l = 0 

for j in range(0,len(individualoutliers)):
    fig = plt.figure(figsize=(70,70))
    fig,axes = plt.subplots(7,5)
    for i in range(0,len(individualoutliers[j])):
        individualoutliersnew = individualoutliers[j]
        out = individualoutliersnew.loc[:, ["newID", "x", "y","level"]].apply(lambda x: pd.Series(x).explode())
        while (int(h) < 6 & int(l) < 4): 
            for k,g in out.groupby("newID"):
                     globals()['interestingvariable'] = g
                     newframe = interestingvariable 
                     sns.lineplot(data=newframe,x='x',y='y',ax=axes[int(h),int(l)])
                     axes[int(h),int(l)].set_xlabel('x-coordinate',labelpad = 40,fontsize=70,weight='bold')
                     axes[int(h),int(l)].set_ylabel('y-coordinate',labelpad = 40,fontsize=70,weight='bold')
                     plt.xticks(weight='bold',fontsize=60,rotation = 30)
                     plt.yticks(weight='bold',fontsize=60)
                     title = (newframe.iloc[0,0]+' '+'level'+' '+str(newframe.iloc[0,3]))
                     axes[int(h),int(l)].set_title(title,fontsize=70,pad=40,weight='bold') 
                     h = int(h)+1
                     l = int(l)+1 
    dir_name = "/Users/macbook/Desktop/"
    plt.rcParams["savefig.directory"] = os.chdir(os.path.dirname(dir_name))
    plt.savefig('figure'+' '+str(j))
    plt.show()
out.head(10)

newID   x   y   level
24  610020  55  60  1
24  610020  55  60  1
24  610020  55  60  1
24  610020  60  60  1
24  610020  60  65  1
24  610020  60  65  1
24  610020  65  70  1
24  610020  70  70  1
24  610020  70  75  1
24  610020  75  75  1
newframe.head(10)

newID   x   y   level
3313    5d254d  55  60  1
3313    5d254d  55  60  1
3313    5d254d  55  60  1
3313    5d254d  60  60  1
3313    5d254d  60  65  1
3313    5d254d  60  65  1
3313    5d254d  65  65  1
3313    5d254d  65  70  1
3313    5d254d  70  75  1
3313    5d254d  75  75  1