matplotlib中文本的部分着色
在matplotlib有没有办法部分指定string的颜色?
例:
plt.ylabel("Today is cloudy.")
我怎样才能显示“今天”是红色的,“是”是绿色的和“多云的”。 像蓝色?
谢谢。
我只知道如何以非交互方式做到这一点,即使这样,只有'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')
这导致(使用ImageMagick从ps转换为png,所以我可以在这里发布):
这里是交互式版本(我发布到列表中的一个 )
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)
扩展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")
请注意,这个python脚本有时会在第一次尝试时失败,并且出现Undefined control sequence
错误。 再次运行是成功的。