LoginSignup
0
2

More than 3 years have passed since last update.

Mathematica で文字を装飾する

Last updated at Posted at 2019-09-07

使用したもの

Mathematica 11

目的

Mathematica でグラフを描くときに単なる文字列を使っていては見た目が非常に悪い。そこで、フォントサイズや文字色を変えることを目指す。

方法

Sytle 関数を使えば上記目的は簡単に達成される。使用例は以下の通り。

Style[ "string",
  FontSlant -> Italic, (* Italic or Plain *)
  FontWeight -> Bold, (* Bold or Plain *)
  FontSize -> 20,
  FontColor -> Black,
  FontFamily -> "Times New Roman" ]

文字列を最初に与え、その後に省略可能なオプションを指定していく。以下、オプションの説明。

  • FontSlantItalicPlain を指定することで斜体にするかどうかを選べる。
  • FontWeightBoldPlain を指定することで太字にするかどうかを選べる。
  • FontSize で文字の大きさを指定できる。
  • FontColor で文字色を指定できる。
  • FontFamily でフォントを指定できる。文字列で与えることに注意。

上記の結果として、下の画像のように装飾された文字が得られる。
string.png

上付き文字、下付き文字

上付き文字を作成したい場合はSuperScript 関数を使用する。下付き文字の場合はSubscript 関数を使用する。これを使えばMathematica Notebook だけではなく、Wolfram Script でも上付き文字等が使用できる。

便利な関数を用意する

さて、目的は達成されたわけだが毎回のように上記内容を書き込むのでは手がつかれるのに加えて読みにくくなる。したがって、ある程度オプションを固定した自作のスタイル関数myStyle を用意しよう。

オプションの一部を固定する

オプションの一部を固定するのは簡単だ。下記のようにすればよい。

myStyle[ s_, ib1_, ib2_] := 
  Style[ s,
    FontSlant -> ib1,
    FontWeight -> ib2,
    FontSize -> 20,
    FontColor -> Black,
    FontFamily -> "Times New Roman" ]

オプションの一部を省略する

上記関数を用いれば、ある程度は簡潔にコードを書くことができる。しかし、FontSlantFontWeightPlain を指定するときは引数を省略したい。そこでOptional を用いる。これは引数の後に: を置き、その後にデフォルトの値を指定できる機能である。
以下のように書く。

myStyle[ s_, ib1_:Plain, ib2_:Plain] := 
  Style[ s,
    FontSlant -> ib1,
    FontWeight -> ib2,
    FontSize -> 20,
    FontColor -> Black,
    FontFamily -> "Times New Roman" ]

これで第2引数と第3引数が省略されたときはPlain が指定されるようになる。

しかし、このままではmyStyle["string", Bold] に対応できない。FontSlantBold が指定されエラーとなる。これを回避するために場合分けを行う。
まずib1Bold の場合はib1ib2 を入れ替えたい。したがって下記のようになる。

myStyle[ s_, ib1_:Plain, ib2_:Plain ] := 
  Style[ s,
    FontSlant -> If[ ib1 == Bold, ib2,ib1 ],
    FontWeight -> If[ ib1 == Bold, ib1,ib2 ],
    FontSize -> 20,
    FontColor -> Black,
    FontFamily -> "Times New Roman" ]

このままではmyStyle[Plain, Italic] のときにエラーとなるので、ib1Bold ではなく、かつib2Italic のときにも引数が入れ替わるようにしたい。下記のようになる。

myStyle[ s_, ib1_:Plain, ib2_:Plain ] := 
  Style[ s,
    FontSlant -> If[ ib1 == Bold, ib2, If[ ib2 == Italic, ib2, ib1 ] ],
    FontWeight -> If[ ib1 == Bold, ib1, If[ ib2 == Italic, ib1, ib2 ] ],
    FontSize -> 20,
    FontColor -> Black,
    FontFamily -> "Times New Roman" ]

こうすれば以下の場合に対応できる。

myStyle[ "string", Plain, Plain ]
myStyle[ "string", Italic, Plain ]
myStyle[ "string", Plain, Italic ]
myStyle[ "string", Bold, Plain ]
myStyle[ "string", Plain, Bold ]
myStyle[ "string", Italic, Bold ]
myStyle[ "string", Bold, Italic ]

myStyle[ "string", Plain ]
myStyle[ "string", Italic ]
myStyle[ "string", Bold ]

myStyle[ "string" ]

なお、myStyle[Bold, Bold] みたいなのはエラーのままである。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2