@@ -495,3 +495,69 @@ def stack_hist(hists, ax=None, **kwargs):
495495 ax = draw_experiment_label (ax , max_height = max_hist , ** kwargs )
496496
497497 return _plot_ax_kwargs (ax , ** kwargs )
498+
499+
500+ def stack_ratio_plot (hists , ** kwargs ):
501+ """
502+ Stack plot on top, ratio plot on bottom
503+ """
504+ fig = kwargs .pop ("fig" , plt .gcf ())
505+
506+ # Scale figure height to deal with ratio subplot being added
507+ fig_height_scale = kwargs .pop ("fig_height_scale" , 1.25 )
508+ _fig_width , _fig_height = get_style ()["figure.figsize" ]
509+ fig .set_size_inches (_fig_width , _fig_height * fig_height_scale , forward = True )
510+
511+ # Setup figure subplot grid and axis dict for hist.plot_ratio
512+ grid = fig .add_gridspec (2 , 1 , hspace = 0 , height_ratios = [3 , 1 ])
513+ main_ax = fig .add_subplot (grid [0 ])
514+ subplot_ax = fig .add_subplot (grid [1 ], sharex = main_ax )
515+ ax_dict = {"main_ax" : main_ax , "ratio_ax" : subplot_ax }
516+
517+ labels = kwargs .pop ("labels" , None )
518+ color = kwargs .pop ("color" , None )
519+ if color is not None and len (color ) != len (hists ):
520+ color = color [: len (hists )]
521+ alpha = kwargs .pop ("alpha" , None )
522+ semilogy = kwargs .pop ("logy" , True )
523+ _data_hist = kwargs .pop ("data_hist" , None )
524+
525+ # Setup and plot the ratio plot
526+ ratio_plot_numerator = kwargs .pop ("ratio_numerator" , "data" )
527+ ratio_plot_kwargs = {
528+ "ax_dict" : ax_dict ,
529+ "rp_ylim" : kwargs .pop ("rp_ylim" , None ),
530+ "rp_uncertainty_type" : kwargs .pop ("rp_uncertainty_type" , "poisson" ),
531+ "rp_uncert_draw_type" : kwargs .pop ("rp_uncert_draw_type" , "line" ),
532+ }
533+
534+ num_hists = utils .sum_hists (hists )
535+ if ratio_plot_numerator .lower () in ["simulation" , "sim" , "mc" ]:
536+ ratio_plot_kwargs ["rp_ylabel" ] = kwargs .pop ("rp_ylabel" , "MC/Data" )
537+ num_hists .plot_ratio (_data_hist , ** ratio_plot_kwargs )
538+ else :
539+ ratio_plot_kwargs ["rp_ylabel" ] = kwargs .pop ("rp_ylabel" , "Data/MC" )
540+ _data_hist .plot_ratio (num_hists , ** ratio_plot_kwargs )
541+ subplot_ax .set_xlabel (kwargs .get ("xlabel" , None ))
542+
543+ # FIXME: Ugly hack to overwrite ratio plot main axis
544+ main_ax .clear ()
545+ main_ax = stack_hist (
546+ hists ,
547+ labels = labels ,
548+ color = color ,
549+ alpha = alpha ,
550+ logy = semilogy ,
551+ data_hist = _data_hist ,
552+ ax = main_ax ,
553+ ** kwargs ,
554+ )
555+
556+ # Hide tick marks of main_ax
557+ plt .setp (main_ax .get_xticklabels (), visible = False )
558+ # Trying to get things looking okay
559+ if semilogy and fig_height_scale < 1.25 :
560+ # Ensure enough space for legend
561+ main_ax .set_ylim (top = main_ax .get_ylim ()[- 1 ] * 100 )
562+
563+ return main_ax , subplot_ax
0 commit comments