2012-02-06 27 views
31

部分的に文字列の色を指定する方法はありますか?matplotlibのテキストの部分的な色付け

例:

plt.ylabel("Today is cloudy.") 

は、私は赤で "今日" を表示するにはどうすればよい、緑として "ある" "曇り。"青い?

ありがとうございました。

+2

私はあなたが3つの別々のテキストボックスでそれをハックする必要があると思います。 – wim

+0

matplotlibメーリングリストにお尋ねください。おそらく、カスタムレンダラーや「アーティスト」で可能かもしれません。 –

+1

また、https://github.com/matplotlib/matplotlib/issues/697 –

答えて

18

私はこれを非インタラクティブに、そして「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のを使用してPNGにPSから変換されたので、私はそれをここに投稿できる)、その結果: enter image description here

+1

でも、これはPDFバックエンドでしか動作しない場合に使用します:)何らかの理由で、軸を正しく配置することはできません私がpsバックエンドで作業している間、キャンバス。 –

+0

申し訳ありません - 私はこれをdownvoteするつもりはありませんでした。私はそれをupvoteすることを意味し、私は早くmisclickedする必要があります。 – mixedmath

+0

非常に良い解決策。 '' pdf''を作成する方法はありますか? 'ps'と' ps2pdf'で保存するのとは別に、私のグラフの中のすべてをねじ込みます。 –

18

ここインタラクティブバージョンは(です私はthe listに投稿されたものと同じもの)

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

+0

単語が縦型バージョンで正確に整列していないようです。 – Alex

+1

これは実際に私がそのコメントを書いた時のmatplotlibのバグでした。それ以来、[ここ](http://matplotlib.org/examples/text_labels_and_annotations/rainbow_text.html)が見られるように修正されています。 –

4

also works with PDF exportヤンの答え、LaTeXの着色拡張:このPythonスクリプトは時々最初の試みで、Undefined control sequenceエラーで失敗したことを

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") 

注意を。それを再度実行すると成功します。

関連する問題