Skip to content

Commit 6b1d8e1

Browse files
committed
Merge pull request matplotlib#2561 from ivanov/unicorn-fact
multi-colored text example
2 parents 0e7daad + efecc24 commit 6b1d8e1

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
The example shows how to string together several text objects.
4+
5+
HISTORY
6+
-------
7+
On the matplotlib-users list back in February 2012, Gökhan Sever asked the
8+
following question:
9+
10+
Is there a way in matplotlib to partially specify the color of a string?
11+
12+
Example:
13+
14+
plt.ylabel("Today is cloudy.")
15+
How can I show "today" as red, "is" as green and "cloudy." as blue?
16+
17+
Thanks.
18+
19+
Paul Ivanov responded with this answer:
20+
"""
21+
import matplotlib.pyplot as plt
22+
from matplotlib import transforms
23+
24+
def rainbow_text(x, y, strings, colors, ax=None, **kw):
25+
"""
26+
Take a list of ``strings`` and ``colors`` and place them next to each
27+
other, with text strings[i] being shown in colors[i].
28+
29+
This example shows how to do both vertical and horizontal text, and will
30+
pass all keyword arguments to plt.text, so you can set the font size,
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.
35+
"""
36+
if ax is None:
37+
ax = plt.gca()
38+
t = ax.transData
39+
canvas = ax.figure.canvas
40+
41+
# horizontal version
42+
for s,c in zip(strings, colors):
43+
text = ax.text(x, y, " " + s + " ", color=c, transform=t, **kw)
44+
text.draw(canvas.get_renderer())
45+
ex = text.get_window_extent()
46+
t = transforms.offset_copy(text._transform, x=ex.width, units='dots')
47+
48+
# vertical version
49+
for s,c in zip(strings, colors):
50+
text = ax.text(x, y, " " + s + " ", color=c, transform=t,
51+
rotation=90, va='bottom', ha='center', **kw)
52+
text.draw(canvas.get_renderer())
53+
ex = text.get_window_extent()
54+
t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
55+
56+
57+
rainbow_text(0, 0, "all unicorns poop rainbows ! ! !".split(),
58+
['red', 'cyan', 'brown', 'green', 'blue', 'purple', 'black'],
59+
size=18)
60+
61+
plt.show()

0 commit comments

Comments
 (0)