Partial coloring of text

It would be nice to have partial coloring of the text strings.

Example:

plt.ylabel("Sun is shining.")

Show “Sun” as red, “is” as green and “shining.” as blue.

Possible use case: separate coloring can be used as legend for plots.

Author: Fantashit

1 thought on “Partial coloring of text

  1. here’s the interactive version (same one I posted to the list)

    import matplotlib.pyplot as plt
    from matplotlib import transforms
    
    def rainbow_text(x,y,ls,lc,**kw):
        """
        Take a list of strings ``ls`` and colors ``lc`` and place them next to each
        other, with text ls[i] being shown in color lc[i].
    
        This example shows how to do both vertical and horizontal text, and will
        pass all keyword arguments to plt.text, so you can set the font size,
        family, etc.
        """
        t = plt.gca().transData
        fig = plt.gcf()
        plt.show()
    
        #horizontal version
        for s,c in zip(ls,lc):
            text = plt.text(x,y," "+s+" ",color=c, transform=t, **kw)
            text.draw(fig.canvas.get_renderer())
            ex = text.get_window_extent()
            t = transforms.offset_copy(text._transform, x=ex.width, units='dots')
    
        #vertical version
        for s,c in zip(ls,lc):
            text = plt.text(x,y," "+s+" ",color=c, transform=t,
                    rotation=90,va='bottom',ha='center',**kw)
            text.draw(fig.canvas.get_renderer())
            ex = text.get_window_extent()
            t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
    
    
    plt.figure()
    rainbow_text(0.0,0.0,"all unicorns poop rainbows ! ! !".split(), 
            ['red', 'orange', 'brown', 'green', 'blue', 'purple', 'black'],
            size=30)

    all unicorns poop rainbows

Comments are closed.