[Matplotlib-devel] Multi-colored Text

Michael W. Lance Michael.Lance at trinity-health.org
Tue Mar 29 10:04:18 EDT 2016


Hello,

I have become increasingly frustrated with something that should really be simple in MPL: I want to be able to easily modify the colors of each word (or even letter) of a title (or text) in a plot (inside or outside of the axes).
On the MPL site, there is this:
http://matplotlib.org/1.5.0/examples/text_labels_and_annotations/rainbow_text.html
But there are 2 problems with this approach:

1.       It results in uneven spacing between words

and

2.       I cannot figure out how to apply a custom font style

Here is some sample code:
import matplotlib.pyplot as plt
plt.rcdefaults()
%matplotlib inline
from matplotlib import transforms

fig = plt.figure(figsize=(4,3), dpi=300)
hfont = {'fontname':'Nexa_Light.otf'}

def rainbow_text(x, y, strings, colors, ax=None, **kw):

    if ax is None:
        ax = plt.gca()
        t = ax.transData
        canvas = ax.figure.canvas

    #horizontal version
    for s, c in zip(strings, colors):
        text = ax.text(x, y,' '+s+' ', color=c, transform=t, **kw)
        text.draw(canvas.get_renderer())
        ex = text.get_window_extent()
        t = transforms.offset_copy(text._transform, x=ex.width-5, units='dots')
    print(ex)
plt.show()

rainbow_text(0.2,1.05,"This is a long sentence. I hope it works out well.".split(),
        ['b','r','g','orange','g','b','black','orange','g','b'],
        size=12,**hfont)

Confidentiality Notice:
This e-mail, including any attachments is the property of Trinity Health and is intended for the sole use of the intended recipient(s). It may contain information that is privileged and confidential.  Any unauthorized review, use, disclosure, or distribution is prohibited. If you are not the intended recipient, please delete this message, and reply to the sender regarding the error in a separate email.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/matplotlib-devel/attachments/20160329/323b1908/attachment.html>


More information about the Matplotlib-devel mailing list