1+ def title_and_subtitle (title , subtitle = '' , pad = 0.1 , fig = None , ax = None ):
2+ """
3+ This function adds a centered title and subtitle to a plot.
4+ Four parameters: title, subtitle, pad, and fig, ax.
5+ 1. title. Required parameter
6+ 2. subtitle. By default empty (optional)
7+ 3. pad. By default 0.1 (optional)
8+ It controls the padding between texts
9+ 4. fig. By Default None (optional)
10+ 5. ax. By Default None (optional)
11+
12+ If ax = None -> ax = plt.gca
13+ The gca function stands for "Get Current Axes".
14+ It returns the current Axes instance on the current figure.
15+ If no current figure exists, a new one is created with a single subplot.
16+
17+ If fig = None -> fig = plt.gcf
18+ The gcf function stands for "Get Current Figure".
19+ It returns the current Axes instance on the current figure.
20+ If no current figure exists, a new one is created with a single subplot.
21+
22+ """
23+ if ax == None :
24+ ax = plt .gca ()
25+ if fig == None :
26+ fig = plt .gcf ()
27+ fig .canvas .draw ()
28+
29+ top_of_figure = 1 #axes coordinates
30+
31+ # Calculate the position of the top of the frist x-axis tick label in axes space
32+ # Useful for positioning other elements on the plot relative to the ticks labels
33+ tick0 = ax .get_xticklabels ()[0 ]
34+ top_of_ticklabels = tick0 .get_window_extent ().transformed (ax .transAxes .inverted ()).y1
35+ top_of_figure = max ([top_of_ticklabels , top_of_figure ])
36+
37+ # Create subtitle
38+ if subtitle :
39+ subt = ax .text (0.5 , top_of_figure + pad ,
40+ s = subtitle ,
41+ ha = 'center' ,
42+ va = 'bottom' ,
43+ fontproperties = font2 ,
44+ size = '11' ,
45+ transform = ax .transAxes )
46+ # update top_of_figure to top of subtitle
47+ top_of_figure = subt .get_window_extent ().transformed (ax .transAxes .inverted ()).y1
48+
49+ # Create title
50+ ax .text (0.5 , top_of_figure + pad ,
51+ s = title ,
52+ ha = 'center' ,
53+ va = 'bottom' ,
54+ fontproperties = font2 ,
55+ size = '14' ,
56+ transform = ax .transAxes )
57+
0 commit comments