Skip to content

Commit efecc24

Browse files
committed
ax is now an optional argument to rainbow_text
I hope @pelson and @tacaswell realize that this is just an example gallery file when they were doing their code review
1 parent 8afa6ca commit efecc24

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

examples/text_labels_and_annotations/rainbow_text.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,35 +21,40 @@
2121
import matplotlib.pyplot as plt
2222
from matplotlib import transforms
2323

24-
def rainbow_text(x, y, strings, colors, **kw):
24+
def rainbow_text(x, y, strings, colors, ax=None, **kw):
2525
"""
26-
Take a list of ``strings`` and colors ``colors`` and place them next to each
26+
Take a list of ``strings`` and ``colors`` and place them next to each
2727
other, with text strings[i] being shown in colors[i].
2828
2929
This example shows how to do both vertical and horizontal text, and will
3030
pass all keyword arguments to plt.text, so you can set the font size,
3131
family, etc.
32+
33+
The text will get added to the ``ax`` axes, if provided, otherwise the
34+
currently active axes will be used.
3235
"""
33-
t = plt.gca().transData
34-
fig = plt.gcf()
36+
if ax is None:
37+
ax = plt.gca()
38+
t = ax.transData
39+
canvas = ax.figure.canvas
3540

36-
#horizontal version
41+
# horizontal version
3742
for s,c in zip(strings, colors):
38-
text = plt.text(x, y, " " + s + " ", color=c, transform=t, **kw)
39-
text.draw(fig.canvas.get_renderer())
43+
text = ax.text(x, y, " " + s + " ", color=c, transform=t, **kw)
44+
text.draw(canvas.get_renderer())
4045
ex = text.get_window_extent()
4146
t = transforms.offset_copy(text._transform, x=ex.width, units='dots')
4247

43-
#vertical version
48+
# vertical version
4449
for s,c in zip(strings, colors):
45-
text = plt.text(x, y, " " + s + " ", color=c, transform=t,
50+
text = ax.text(x, y, " " + s + " ", color=c, transform=t,
4651
rotation=90, va='bottom', ha='center', **kw)
47-
text.draw(fig.canvas.get_renderer())
52+
text.draw(canvas.get_renderer())
4853
ex = text.get_window_extent()
4954
t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
5055

5156

52-
rainbow_text(40, 540, "all unicorns poop rainbows ! ! !".split(),
57+
rainbow_text(0, 0, "all unicorns poop rainbows ! ! !".split(),
5358
['red', 'cyan', 'brown', 'green', 'blue', 'purple', 'black'],
5459
size=18)
5560

0 commit comments

Comments
 (0)