Quellcode durchsuchen

Grid of plots for swp2 thetas

tforest vor 1 Jahr
Ursprung
Commit
3f174048f1
1 geänderte Dateien mit 74 neuen und 65 gelöschten Zeilen
  1. 74 65
      swp2.py

+ 74 - 65
swp2.py Datei anzeigen

@@ -216,7 +216,7 @@ def plot_k_epochs_thetafolder(folder_path, mu, tgen, breaks = 2, title = "Title"
216 216
     plt.title(title)
217 217
     plt.savefig(title+'_b'+str(breaks)+'.pdf')
218 218
 
219
-def plot_all_epochs_thetafolder(folder_path, mu, tgen, title = "Title", theta_scale = True):
219
+def plot_all_epochs_thetafolder(folder_path, mu, tgen, title = "Title", theta_scale = True, ax = None):
220 220
     #scenari = {}
221 221
     cpt = 0
222 222
     epochs = {}
@@ -239,15 +239,21 @@ def plot_all_epochs_thetafolder(folder_path, mu, tgen, title = "Title", theta_sc
239 239
                                                                   mu = mu, relative_theta_scale = theta_scale)
240 240
     print("\n*******\n"+title+"\n--------\n"+"mu="+str(mu)+"\ntgen="+str(tgen)+"\nbreaks="+str(breaks)+"\n*******\n")
241 241
     print(cpt, "theta file(s) have been scanned.")
242
-
243
-    # intialize figure
244 242
     my_dpi = 300
245
-    plt.figure(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
246
-    plt.xlim(1e-3, 1)
243
+    if ax is None:
244
+        # intialize figure
245
+        my_dpi = 300
246
+        fnt_size = 18
247
+        fig, ax1 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
248
+    else:
249
+        fnt_size = 12
250
+        plt.rcParams['font.size'] = fnt_size
251
+        ax1 = ax[0,0]
252
+    ax1.set_xlim(1e-3, 1)
247 253
     #plt.ylim(0, 10)
248
-    plt.yscale('log')
249
-    plt.xscale('log')
250
-    plt.grid(True,which="both", linestyle='--', alpha = 0.3)
254
+    ax1.set_yscale('log')
255
+    ax1.set_xscale('log')
256
+    ax1.grid(True,which="both", linestyle='--', alpha = 0.3)
251 257
     brkpt_lik = []
252 258
     for epoch, scenari in epochs.items():
253 259
         # sort starting by the smallest -log(Likelihood)
@@ -265,23 +271,24 @@ def plot_all_epochs_thetafolder(folder_path, mu, tgen, title = "Title", theta_sc
265 271
             # divide by N0
266 272
             y[i] = y[i]/N0
267 273
             x[i] = x[i]/N0
268
-        plt.plot(x, y, 'o', linestyle = "-", alpha=0.75, lw=2, label = str(epoch)+' BrkPt | Lik='+greatest_likelihood)
274
+        ax1.plot(x, y, 'o', linestyle = "-", alpha=0.75, lw=2, label = str(epoch)+' BrkPt | Lik='+greatest_likelihood)
269 275
         if theta_scale:
270
-            plt.xlabel("Coal. time")
271
-            plt.ylabel("Pop. size scaled by N0")
276
+            ax1.set_xlabel("Coal. time")
277
+            ax1.set_ylabel("Pop. size scaled by N0")
272 278
             recent_scale_lower_bound = 0.01
273 279
             recent_scale_upper_bound = 0.1
274 280
             #print(recent_scale_lower_bound, recent_scale_upper_bound)
275
-            plt.axvline(x=recent_scale_lower_bound)
276
-            plt.axvline(x=recent_scale_upper_bound)
281
+            ax1.axvline(x=recent_scale_lower_bound)
282
+            ax1.axvline(x=recent_scale_upper_bound)
277 283
         else:
278 284
             # years
279
-            plt.xlabel("Time (years)")
280
-            plt.ylabel("Individuals (N)")
281
-        plt.xlim(1e-5, 1)
282
-        plt.legend(loc='upper right')
283
-        plt.title(title)
284
-        plt.savefig(title+'_b'+str(breaks)+'.pdf')
285
+            plt.set_xlabel("Time (years)")
286
+            plt.set_ylabel("Individuals (N)")
287
+        ax1.set_xlim(1e-5, 1)
288
+        ax1.legend(loc='best', fontsize = fnt_size*0.5)
289
+        ax1.set_title(title)
290
+        if ax is None:
291
+            plt.savefig(title+'_b'+str(breaks)+'.pdf')
285 292
     # plot likelihood against nb of breakpoints
286 293
     # best possible likelihood from SFS
287 294
     # Segregating sites
@@ -299,31 +306,40 @@ def plot_all_epochs_thetafolder(folder_path, mu, tgen, title = "Title", theta_sc
299 306
     res = Ln
300 307
     # print(res)
301 308
     # basic plot likelihood
302
-    plt.figure(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
303
-    plt.rcParams['font.size'] = '18'
304
-    plt.plot(np.array(brkpt_lik)[:, 0], np.array(brkpt_lik)[:, 1].astype(float), 'o', linestyle = "dotted", lw=2)
309
+    if ax is None:
310
+        fig, ax2 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
311
+        plt.rcParams['font.size'] = '18'
312
+    else:
313
+        plt.rcParams['font.size'] = fnt_size
314
+        ax2 = ax[2,0]
315
+    ax2.plot(np.array(brkpt_lik)[:, 0], np.array(brkpt_lik)[:, 1].astype(float), 'o', linestyle = "dotted", lw=2)
305 316
     # plt.ylim(0,100)
306
-    # plt.axhline(y=res)
307
-    plt.yscale('log')
308
-    plt.xlabel("# breakpoints", fontsize=20)
309
-    plt.ylabel("$-\log\mathcal{L}$")
310
-    #plt.legend(loc='upper right')
311
-    plt.title(title)
312
-    plt.savefig(title+'_Breakpts_Likelihood.pdf')
317
+    ax2.axhline(y=-Ln)
318
+    ax2.set_yscale('log')
319
+    ax2.set_xlabel("# breakpoints", fontsize=fnt_size)
320
+    ax2.set_ylabel("$-\log\mathcal{L}$")
321
+    #ax2.legend(loc='best', fontsize = fnt_size*0.5)
322
+    ax2.set_title(title)
323
+    if ax is None:
324
+        plt.savefig(title+'_Breakpts_Likelihood.pdf')
313 325
     # AIC
314
-    plt.figure(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
315
-    plt.rcParams['font.size'] = '18'
326
+    if ax is None:
327
+        fig, ax3 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
328
+        plt.rcParams['font.size'] = '18'
329
+    else:
330
+        ax3 = ax[2,1]
316 331
     AIC = 2*(len(brkpt_lik)+1)+2*np.array(brkpt_lik)[:, 1].astype(float)
317
-    plt.plot(np.array(brkpt_lik)[:, 0], AIC, 'o', linestyle = "dotted", lw=2)
318
-    # plt.axhline(y=106)
319
-    plt.yscale('log')
320
-    plt.xlabel("# breakpoints", fontsize=20)
321
-    plt.ylabel("AIC")
322
-    #plt.legend(loc='upper right')
323
-    plt.title(title)
324
-    plt.savefig(title+'_Breakpts_Likelihood_AIC.pdf')
325
-
326
-def plot_test_theta(folder_path, mu, tgen, title = "Title", theta_scale = True, breaks_max = 12, ax = None):
332
+    ax3.plot(np.array(brkpt_lik)[:, 0], AIC, 'o', linestyle = "dotted", lw=2)
333
+    ax3.axhline(y=2*(len(brkpt_lik)+1)-2*Ln)
334
+    ax3.set_yscale('log')
335
+    ax3.set_xlabel("# breakpoints", fontsize=fnt_size)
336
+    ax3.set_ylabel("AIC")
337
+    #ax3.legend(loc='best', fontsize = fnt_size*0.5)
338
+    ax3.set_title(title)
339
+    if ax is None:
340
+        plt.savefig(title+'_Breakpts_Likelihood_AIC.pdf')
341
+    return ax
342
+def plot_test_theta(folder_path, mu, tgen, title = "Title", theta_scale = True, breaks_max = 10, ax = None):
327 343
     """
328 344
     Use theta values as is to do basic plots.
329 345
     """
@@ -341,15 +357,16 @@ def plot_test_theta(folder_path, mu, tgen, title = "Title", theta_scale = True,
341 357
                 epochs[k] = thetas
342 358
     print("\n*******\n"+title+"\n--------\n"+"mu="+str(mu)+"\ntgen="+str(tgen)+"\nbreaks="+str(k)+"\n*******\n")
343 359
     print(cpt, "theta file(s) have been scanned.")
344
-    # intialize figure 1
345
-    my_dpi = 300
346
-    # plt.figure(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
347 360
     # multiple fig
348 361
     if ax is None:
362
+        # intialize figure 1
363
+        my_dpi = 300
364
+        fnt_size = 18
349 365
         fig, ax1 = plt.subplots(figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
350 366
         # Add some extra space for the second axis at the bottom
351 367
         fig.subplots_adjust(bottom=0.15)
352 368
     else:
369
+        fnt_size = 12
353 370
         ax1 = ax[0, 1]
354 371
         plt.subplots_adjust(wspace=0.3, hspace=0.3)
355 372
 
@@ -389,14 +406,19 @@ def plot_test_theta(folder_path, mu, tgen, title = "Title", theta_scale = True,
389 406
     twin.xaxis.set_ticks_position("bottom")
390 407
     twin.xaxis.set_label_position("bottom")
391 408
     # Offset the twin axis below the host
392
-    twin.spines["bottom"].set_position(("axes", -0.15))
409
+    if ax is None:
410
+        # arrange differently the second x axis if the plot is plain
411
+        twin.spines["bottom"].set_position(("axes", -0.15))
412
+    else:
413
+        # in a combined plot, more space between the fig and the axis
414
+        twin.spines["bottom"].set_position(("axes", -0.35))
393 415
     #ax.legend(handles=[p0]+plots)
394 416
     ax1.set_xlabel("# breaks")
395 417
     # Set the x-axis locator to reduce the number of ticks to 10
396 418
     ax1.xaxis.set_major_locator(MaxNLocator(nbins=10))
397 419
     ax1.set_ylabel("theta")
398
-    # twin.set_ylabel("Proportion")
399
-    plt.legend(handles=plots, loc='upper right')
420
+    twin.set_ylabel("Proportion")
421
+    ax1.legend(handles=plots, loc='best', fontsize = fnt_size*0.5)
400 422
     if ax is None:
401 423
         plt.savefig(title+'_raw'+str(k)+'.pdf')
402 424
     # fig 2 & 3
@@ -439,43 +461,30 @@ def plot_test_theta(folder_path, mu, tgen, title = "Title", theta_scale = True,
439 461
     ax2.set_xlabel("# breaks")
440 462
     ax2.set_ylabel("theta")
441 463
     ax2.set_title("Test")
442
-    ax2.legend(handles=lines_fig2, loc='upper right')
464
+    ax2.legend(handles=lines_fig2, loc='best', fontsize = fnt_size*0.5)
443 465
     if ax is None:
444 466
         plt.savefig(title+'_plot2_'+str(k)+'.pdf')
445 467
     ax3.set_xscale('log')
446 468
     ax3.set_xlabel("log()")
447 469
     ax3.set_ylabel("theta")
448 470
     ax3.set_title("Test")
449
-    ax3.legend(handles=lines_fig3, loc='upper right')
471
+    ax3.legend(handles=lines_fig3, loc='best', fontsize = fnt_size*0.5)
450 472
     if ax is None:
451 473
         plt.savefig(title+'_plot3_'+str(k)+'_log.pdf')
452 474
     # return plots
453 475
     return ax
454 476
 
455
-def save_combined_pdf(output_path):
456
-    with PdfPages(output_path) as pdf:
457
-        pdf.savefig()
458
-
459
-def save_multi_image(filename):
460
-    pp = PdfPages(filename)
461
-    fig_nums = plt.get_fignums()
462
-    figs = [plt.figure(n) for n in fig_nums]
463
-    for fig in figs:
464
-        fig.savefig(pp, format='pdf')
465
-    pp.close()
466
-
467 477
 def combined_plot(folder_path, mu, tgen, breaks, title = "Title", theta_scale = True):
468
-    # plot1, plot2, plot3 = plot_all_epochs_thetafolder(folder_path, mu, tgen, title, theta_scale)
469 478
     my_dpi = 300
470 479
     # Add some extra space for the second axis at the bottom
471
-    fig, axs = plt.subplots(2, 2, figsize=(5000/my_dpi, 2800/my_dpi), dpi=my_dpi)
472
-
480
+    fig, axs = plt.subplots(3, 2, figsize=(4500/my_dpi, 2970/my_dpi), dpi=my_dpi)
481
+    ax = plot_all_epochs_thetafolder(folder_path, mu, tgen, title, theta_scale, ax = axs)
473 482
     ax = plot_test_theta(folder_path, mu, tgen, title, theta_scale, breaks_max = breaks, ax = axs)
474 483
 
475 484
     # Adjust layout to prevent clipping of titles
476 485
     plt.tight_layout()
477 486
     # Adjust absolute space between the top and bottom rows
478
-    plt.subplots_adjust(hspace=0.35)  # Adjust this value based on your requirement
487
+    plt.subplots_adjust(hspace=0.7)  # Adjust this value based on your requirement
479 488
 
480 489
     # Save the entire grid as a single figure
481 490
     plt.savefig(title+'_combined.pdf')