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