|
21 | 21 | import matplotlib.pyplot as plt
|
22 | 22 | from matplotlib import transforms
|
23 | 23 |
|
24 |
| -def rainbow_text(x, y, strings, colors, **kw): |
| 24 | +def rainbow_text(x, y, strings, colors, ax=None, **kw): |
25 | 25 | """
|
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 |
27 | 27 | other, with text strings[i] being shown in colors[i].
|
28 | 28 |
|
29 | 29 | This example shows how to do both vertical and horizontal text, and will
|
30 | 30 | pass all keyword arguments to plt.text, so you can set the font size,
|
31 | 31 | family, etc.
|
| 32 | +
|
| 33 | + The text will get added to the ``ax`` axes, if provided, otherwise the |
| 34 | + currently active axes will be used. |
32 | 35 | """
|
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 |
35 | 40 |
|
36 |
| - #horizontal version |
| 41 | + # horizontal version |
37 | 42 | 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()) |
40 | 45 | ex = text.get_window_extent()
|
41 | 46 | t = transforms.offset_copy(text._transform, x=ex.width, units='dots')
|
42 | 47 |
|
43 |
| - #vertical version |
| 48 | + # vertical version |
44 | 49 | 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, |
46 | 51 | rotation=90, va='bottom', ha='center', **kw)
|
47 |
| - text.draw(fig.canvas.get_renderer()) |
| 52 | + text.draw(canvas.get_renderer()) |
48 | 53 | ex = text.get_window_extent()
|
49 | 54 | t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
|
50 | 55 |
|
51 | 56 |
|
52 |
| -rainbow_text(40, 540, "all unicorns poop rainbows ! ! !".split(), |
| 57 | +rainbow_text(0, 0, "all unicorns poop rainbows ! ! !".split(), |
53 | 58 | ['red', 'cyan', 'brown', 'green', 'blue', 'purple', 'black'],
|
54 | 59 | size=18)
|
55 | 60 |
|
|
0 commit comments