关于python:matplotlib中文本的部分着色

Partial coloring of text in matplotlib

matplotlib中是否有方法部分指定字符串的颜色?

例子:

1
plt.ylabel("Today is cloudy.")

我怎么能把"今天"显示为红色,"今天"显示为绿色,"今天"显示为多云,"今天"显示为蓝色?

谢谢。


这是交互式版本(和我在列表中发布的版本相同)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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)

all unicorns poop rainbows


我只知道如何以非交互方式完成这项工作,甚至只知道如何使用"ps"后端。

为此,我将使用LaTex来格式化文本。然后我会包括"颜色"包,并设置您希望的颜色。

下面是这样做的一个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
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')

结果是(使用ImageMagick从PS转换为PNG,所以我可以在这里发布它):enter image description here


扩展Yann的答案,乳胶着色现在也可以与PDF导出一起使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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")

注意,这个python脚本在第一次尝试时有时会出现Undefined control sequence错误。再次运行是成功的。