24
24
"""
25
25
26
26
import matplotlib .pyplot as plt
27
- from matplotlib .transforms import Affine2D
27
+ from matplotlib .transforms import Affine2D , offset_copy
28
28
29
29
30
30
def rainbow_text (x , y , strings , colors , orientation = 'horizontal' ,
@@ -51,7 +51,8 @@ def rainbow_text(x, y, strings, colors, orientation='horizontal',
51
51
if ax is None :
52
52
ax = plt .gca ()
53
53
t = ax .transData
54
- canvas = ax .figure .canvas
54
+ fig = ax .figure
55
+ canvas = fig .canvas
55
56
56
57
assert orientation in ['horizontal' , 'vertical' ]
57
58
if orientation == 'vertical' :
@@ -63,10 +64,16 @@ def rainbow_text(x, y, strings, colors, orientation='horizontal',
63
64
# Need to draw to update the text position.
64
65
text .draw (canvas .get_renderer ())
65
66
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
+
66
71
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 )
68
74
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 )
70
77
71
78
72
79
words = "all unicorns poop rainbows ! ! !" .split ()
0 commit comments