彩虹文本

该示例演示如何将多个文本对象串在一起。

过去

在2012年2月的matplotlib-users列表中,GökhanSever提出以下问题:

matplotlib中有一种可以部分指定字符串的颜色的方法吗?

例子:

  1. plt.ylabel("Today is cloudy.") How can I show "today" as red, "is" as green and "cloudy." as blue?

感谢。

Paul Ivanov 的回答:

彩虹文本

  1. import matplotlib.pyplot as plt
  2. from matplotlib import transforms
  3. def rainbow_text(x, y, strings, colors, ax=None, **kw):
  4. """
  5. Take a list of ``strings`` and ``colors`` and place them next to each
  6. other, with text strings[i] being shown in colors[i].
  7. This example shows how to do both vertical and horizontal text, and will
  8. pass all keyword arguments to plt.text, so you can set the font size,
  9. family, etc.
  10. The text will get added to the ``ax`` axes, if provided, otherwise the
  11. currently active axes will be used.
  12. """
  13. if ax is None:
  14. ax = plt.gca()
  15. t = ax.transData
  16. canvas = ax.figure.canvas
  17. # horizontal version
  18. for s, c in zip(strings, colors):
  19. text = ax.text(x, y, s + " ", color=c, transform=t, **kw)
  20. text.draw(canvas.get_renderer())
  21. ex = text.get_window_extent()
  22. t = transforms.offset_copy(
  23. text.get_transform(), x=ex.width, units='dots')
  24. # vertical version
  25. for s, c in zip(strings, colors):
  26. text = ax.text(x, y, s + " ", color=c, transform=t,
  27. rotation=90, va='bottom', ha='center', **kw)
  28. text.draw(canvas.get_renderer())
  29. ex = text.get_window_extent()
  30. t = transforms.offset_copy(
  31. text.get_transform(), y=ex.height, units='dots')
  32. rainbow_text(0, 0, "all unicorns poop rainbows ! ! !".split(),
  33. ['red', 'cyan', 'brown', 'green', 'blue', 'purple', 'black'],
  34. size=16)
  35. plt.show()

下载这个示例