3
3
import collections .abc
4
4
import inspect
5
5
import warnings
6
+ import logging
6
7
from collections import OrderedDict , namedtuple
7
8
from typing import TYPE_CHECKING , Any , Union
8
9
@@ -962,6 +963,10 @@ def _draw_leg_bbox(ax):
962
963
"""
963
964
fig = ax .figure
964
965
leg = ax .get_legend ()
966
+ if leg is None :
967
+ leg = [
968
+ c for c in ax .get_children () if isinstance (c , plt .matplotlib .legend .Legend )
969
+ ][0 ]
965
970
966
971
fig .canvas .draw ()
967
972
return leg .get_frame ().get_bbox ()
@@ -973,6 +978,7 @@ def _draw_text_bbox(ax):
973
978
"""
974
979
fig = ax .figure
975
980
textboxes = [k for k in ax .get_children () if isinstance (k , AnchoredText )]
981
+ fig .canvas .draw ()
976
982
if len (textboxes ) > 1 :
977
983
print ("Warning: More than one textbox found" )
978
984
for box in textboxes :
@@ -984,15 +990,17 @@ def _draw_text_bbox(ax):
984
990
return bbox
985
991
986
992
987
- def yscale_legend (ax = None ):
993
+ def yscale_legend (ax = None , otol = 0 ):
988
994
"""
989
- Automatically scale y-axis up to fit in legend()
995
+ Automatically scale y-axis up to fit in legend().
996
+ Set `otol > 0` for less strict scaling.
990
997
"""
991
998
if ax is None :
992
999
ax = plt .gca ()
993
1000
994
1001
scale_factor = 10 ** (1.05 ) if ax .get_yscale () == "log" else 1.05
995
- while overlap (ax , _draw_leg_bbox (ax )) > 0 :
1002
+ while overlap (ax , _draw_leg_bbox (ax )) > otol :
1003
+ logging .info ("Scaling y-axis by 5% to fit legend" )
996
1004
ax .set_ylim (ax .get_ylim ()[0 ], ax .get_ylim ()[- 1 ] * scale_factor )
997
1005
ax .figure .canvas .draw ()
998
1006
return ax
0 commit comments