25
25
26
26
import matplotlib .pyplot as plt
27
27
28
- from matplotlib .transforms import Affine2D , offset_copy
29
-
30
28
31
29
def rainbow_text (x , y , strings , colors , orientation = 'horizontal' ,
32
30
ax = None , ** kwargs ):
@@ -45,42 +43,32 @@ def rainbow_text(x, y, strings, colors, orientation='horizontal',
45
43
orientation : {'horizontal', 'vertical'}
46
44
ax : Axes, optional
47
45
The Axes to draw into. If None, the current axes will be used.
48
- **kwargs
49
- All other keyword arguments are passed to plt.text(), so you can
50
- set the font size, family, etc.
46
+ **kwargs :
47
+ All other keyword arguments are passed to plt.text() and plt.annotate() , so you
48
+ can set the font size, family, etc.
51
49
"""
52
50
if ax is None :
53
51
ax = plt .gca ()
54
- t = ax .transData
55
- fig = ax .figure
56
- canvas = fig .canvas
57
52
58
53
assert orientation in ['horizontal' , 'vertical' ]
59
- if orientation == 'vertical ' :
60
- kwargs . update ( rotation = 90 , verticalalignment = 'bottom' )
61
-
62
- for s , c in zip ( strings , colors ):
63
- text = ax . text ( x , y , s + " " , color = c , transform = t , ** kwargs )
54
+ if orientation == 'horizontal ' :
55
+ txt = ax . text ( x , y , strings [ 0 ], color = colors [ 0 ], ** kwargs )
56
+ for s , c in zip ( strings [ 1 :], colors [ 1 :]):
57
+ txt = ax . annotate ( ' ' + s , xy = ( 1 , 0 ), xycoords = txt ,
58
+ va = "bottom" , color = c , ** kwargs )
64
59
65
- # Need to draw to update the text position.
66
- text .draw (canvas .get_renderer ())
67
- ex = text .get_window_extent ()
68
- # Convert window extent from pixels to inches
69
- # to avoid issues displaying at different dpi
70
- ex = fig .dpi_scale_trans .inverted ().transform_bbox (ex )
71
-
72
- if orientation == 'horizontal' :
73
- t = text .get_transform () + \
74
- offset_copy (Affine2D (), fig = fig , x = ex .width , y = 0 )
75
- else :
76
- t = text .get_transform () + \
77
- offset_copy (Affine2D (), fig = fig , x = 0 , y = ex .height )
60
+ elif orientation == 'vertical' :
61
+ kwargs .update (rotation = 90 , verticalalignment = 'bottom' )
62
+ txt = ax .text (x , y , strings [0 ], color = colors [0 ], ** kwargs )
63
+ for s , c in zip (strings [1 :], colors [1 :]):
64
+ txt = ax .annotate (' ' + s , xy = (0 , 1 ), xycoords = txt ,
65
+ va = "bottom" , color = c , ** kwargs )
78
66
79
67
80
68
words = "all unicorns poop rainbows ! ! !" .split ()
81
69
colors = ['red' , 'orange' , 'gold' , 'lawngreen' , 'lightseagreen' , 'royalblue' ,
82
70
'blueviolet' ]
83
- plt .figure (figsize = (6 , 6 ))
71
+ plt .figure (figsize = (8 , 8 ))
84
72
rainbow_text (0.1 , 0.05 , words , colors , size = 18 )
85
73
rainbow_text (0.05 , 0.1 , words , colors , orientation = 'vertical' , size = 18 )
86
74
0 commit comments