2424"""
2525
2626import matplotlib .pyplot as plt
27- from matplotlib .transforms import Affine2D
27+ from matplotlib .transforms import Affine2D , offset_copy
2828
2929
3030def rainbow_text (x , y , strings , colors , orientation = 'horizontal' ,
@@ -51,7 +51,8 @@ def rainbow_text(x, y, strings, colors, orientation='horizontal',
5151 if ax is None :
5252 ax = plt .gca ()
5353 t = ax .transData
54- canvas = ax .figure .canvas
54+ fig = ax .figure
55+ canvas = fig .canvas
5556
5657 assert orientation in ['horizontal' , 'vertical' ]
5758 if orientation == 'vertical' :
@@ -63,10 +64,16 @@ def rainbow_text(x, y, strings, colors, orientation='horizontal',
6364 # Need to draw to update the text position.
6465 text .draw (canvas .get_renderer ())
6566 ex = text .get_window_extent ()
67+ # Convert window extent from pixels to inches
68+ # to avoid issues displaying at different dpi
69+ ex = fig .dpi_scale_trans .inverted ().transform_bbox (ex )
70+
6671 if orientation == 'horizontal' :
67- t = text .get_transform () + Affine2D ().translate (ex .width , 0 )
72+ t = text .get_transform () + \
73+ offset_copy (Affine2D (), fig = fig , x = ex .width , y = 0 )
6874 else :
69- t = text .get_transform () + Affine2D ().translate (0 , ex .height )
75+ t = text .get_transform () + \
76+ offset_copy (Affine2D (), fig = fig , x = 0 , y = ex .height )
7077
7178
7279words = "all unicorns poop rainbows ! ! !" .split ()
0 commit comments