matplotlib中文本的部分着色

Gök*_*ver 38 python matplotlib

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

例:

plt.ylabel("Today is cloudy.")
Run Code Online (Sandbox Code Playgroud)

如何将"今天"显示为红色,"是"显示为绿色和"阴天".如蓝色?

谢谢.

Yan*_*ann 24

我只知道如何以非交互方式进行此操作,即使只有'PS'后端.

为此,我将使用Latex格式化文本.然后我会包含'颜色'包,并根据需要设置颜色.

这是一个这样做的例子:

import matplotlib
matplotlib.use('ps')
from matplotlib import rc

rc('text',usetex=True)
rc('text.latex', preamble='\usepackage{color}')
import matplotlib.pyplot as plt

plt.figure()
plt.ylabel(r'\textcolor{red}{Today} '+
           r'\textcolor{green}{is} '+
           r'\textcolor{blue}{cloudy.}')
plt.savefig('test.ps')
Run Code Online (Sandbox Code Playgroud)

这导致(使用ImageMagick从ps转换为png,所以我可以在这里发布): 在此输入图像描述

  • 使用 py3 中的 matplotlib 3.2.2,我必须在“\usepackage{color}”中转义“\u”以获得 unicode。然后,即使在安装了“texlive-extra”之后,我也收到了“type1ec.sty”未找到”错误。 (5认同)
  • 如果仅用于PDF后端,我会使用它:)由于某种原因,当我使用ps后端时,我永远无法将轴正确放置在画布上。 (2认同)

Pau*_*nov 21

这是交互式版本(我发布到列表中的同一个版本)

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.5,0.5,"all unicorns poop rainbows ! ! !".split(), 
        ['red', 'orange', 'brown', 'green', 'blue', 'purple', 'black'],
        size=40)
Run Code Online (Sandbox Code Playgroud)

所有独角兽大便彩虹

  • 看起来这些单词在垂直版本中并没有完全对齐。 (2认同)
  • 在我写那条评论时,这实际上是 matplotlib 中的一个错误。它已被修复,如您所见 [此处](http://matplotlib.org/examples/text_labels_and_annotations/rainbow_text.html)。 (2认同)

Fel*_*lix 5

延伸Yann的答案,LaTeX着色现在也适用于PDF导出:

import matplotlib
from matplotlib.backends.backend_pgf import FigureCanvasPgf
matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)

import matplotlib.pyplot as plt

pgf_with_latex = {
    "text.usetex": True,            # use LaTeX to write all text
    "pgf.rcfonts": False,           # Ignore Matplotlibrc
    "pgf.preamble": [
        r'\usepackage{color}'     # xcolor for colours
    ]
}
matplotlib.rcParams.update(pgf_with_latex)

plt.figure()
plt.ylabel(r'\textcolor{red}{Today} '+
           r'\textcolor{green}{is} '+
           r'\textcolor{blue}{cloudy.}')
plt.savefig("test.pdf")
Run Code Online (Sandbox Code Playgroud)

请注意,此python脚本有时会Undefined control sequence在第一次尝试时失败并显示错误.然后再次运行它是成功的.

  • 想通了。我们现在需要在`savefig()`选项中包含`backend='pgf'`。 (2认同)