Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib. Plotting in 'for loops' to same axis

I have a rather simple problem but something that's had me stumped for 2days. I need to plot 2+ files. Each file will need to be plotted on a total of 25 plots but must be plotted on the same set of axes. (ie. if theres 2 files I need 25 plots with 2 lines on each plot).

I have this sudo code which generates 50 plots (One line for each)...which is wrong

with open(bamlist, 'r') as bamlist:
    for bam in bamlist:     #Opens the 2 files
        'Generate data Here'
        dataframe = []
        for line in data:
            line = line.split("\t")
            dataframe.append(line[0:4:1])
        df = pd.DataFrame(dataframe, columns=['Chromosome', 'Position', 'N', 'BaseCount'])

        grouped_df = df.groupby('Chromosome')     #groups dataframe into the required 25plots
        for df in grouped_df:
            density_data = 'Get density data from df'
            f, ax = plt.subplots()          
            sns.kdeplot(density_data, ax=ax, linewidth=1)
            pp.savefig()
pp.close()

Is there a way to revert back to the initial set of axis the 2nd time the for loop is entered so that I will get 2 lines per plot with 25plots (as opposed to 50)?

like image 542
Michael Berry Avatar asked Jun 10 '26 17:06

Michael Berry


2 Answers

Your problem stems from your use of:

f, ax = plt.subplots()

This means that you generate a new subplot every time you hit that line (in your case, 50 times). You need to generate 25 subplots and reference them later on. You can do something like:

axes = []
for i in range(25):
    f,ax = plt.subplots()
    axes.append(ax)

Then in your loop:

for df_index in range(len(grouped_df)):
    df = grouped_df[df_index]
    density_data = 'Get density data from df'
    sns.kdeplot(density_data, ax=axes[df_index], linewidth=1)

You can also do a check to see if the axis doesn't exist (if it extends to more than 25 subplots or something), and if not, create it.

like image 177
Jake Avatar answered Jun 12 '26 07:06

Jake


Using plt.figure() also gets the job done...

iterate = -1
for df in grouped_df:
    iterate += 1
    plt.figure(iterate)
    density_data = 'Get density data from df'
    sns.kdeplot(density_data, linewidth=1)
    pp.savefig()
pp.close()
like image 43
Michael Berry Avatar answered Jun 12 '26 08:06

Michael Berry