Skip to content

Further cleanup rainbow_text example. #26057

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 24 additions & 68 deletions galleries/examples/text_labels_and_annotations/rainbow_text.py
Original file line number Diff line number Diff line change
@@ -1,75 +1,31 @@
"""
============
Rainbow text
============

The example shows how to string together several text objects.

History
-------
On the matplotlib-users list back in February 2012, Gökhan Sever asked the
following question:

| Is there a way in matplotlib to partially specify the color of a string?
|
| Example:
|
| plt.ylabel("Today is cloudy.")
|
| How can I show "today" as red, "is" as green and "cloudy." as blue?
|
| Thanks.

The solution below is modified from Paul Ivanov's original answer.
====================================================
Concatenating text objects with different properties
====================================================

The example strings together several Text objects with different properties
(e.g., color or font), positioning each one after the other. The first Text
is created directly using `~.Axes.text`; all subsequent ones are created with
`~.Axes.annotate`, which allows positioning the Text's lower left corner at the
lower right corner (``xy=(1, 0)``) of the previous one (``xycoords=text``).
"""

import matplotlib.pyplot as plt


def rainbow_text(x, y, strings, colors, orientation='horizontal',
ax=None, **kwargs):
"""
Take a list of *strings* and *colors* and place them next to each
other, with text strings[i] being shown in colors[i].

Parameters
----------
x, y : float
Text position in data coordinates.
strings : list of str
The strings to draw.
colors : list of color
The colors to use.
orientation : {'horizontal', 'vertical'}
ax : Axes, optional
The Axes to draw into. If None, the current axes will be used.
**kwargs :
All other keyword arguments are passed to plt.text() and plt.annotate(), so you
can set the font size, family, etc.
"""
if ax is None:
ax = plt.gca()

assert orientation in ['horizontal', 'vertical']
if orientation == 'horizontal':
txt = ax.text(x, y, strings[0], color=colors[0], **kwargs)
for s, c in zip(strings[1:], colors[1:]):
txt = ax.annotate(' ' + s, xy=(1, 0), xycoords=txt,
va="bottom", color=c, **kwargs)

elif orientation == 'vertical':
kwargs.update(rotation=90, verticalalignment='bottom')
txt = ax.text(x, y, strings[0], color=colors[0], **kwargs)
for s, c in zip(strings[1:], colors[1:]):
txt = ax.annotate(' ' + s, xy=(0, 1), xycoords=txt,
va="bottom", color=c, **kwargs)


words = "all unicorns poop rainbows ! ! !".split()
colors = ['red', 'orange', 'gold', 'lawngreen', 'lightseagreen', 'royalblue',
'blueviolet']
plt.figure(figsize=(8, 8))
rainbow_text(0.1, 0.05, words, colors, size=18)
rainbow_text(0.05, 0.1, words, colors, orientation='vertical', size=18)
plt.rcParams["font.size"] = 20
ax = plt.figure().add_subplot(xticks=[], yticks=[])

# The first word, created with text().
text = ax.text(.1, .5, "Matplotlib", color="red")
# Subsequent words, positioned with annotate(), relative to the preceding one.
text = ax.annotate(
" says,", xycoords=text, xy=(1, 0), verticalalignment="bottom",
color="gold", weight="bold") # custom properties
text = ax.annotate(
" hello", xycoords=text, xy=(1, 0), verticalalignment="bottom",
color="green", style="italic") # custom properties
text = ax.annotate(
" world!", xycoords=text, xy=(1, 0), verticalalignment="bottom",
color="blue", family="serif") # custom properties

plt.show()