コードDE描画

プログラミングで図を描く練習

【LaTeX】【tikz入門】calcライブラリの構文4選

数式を扱うLaTeXにある描画を行うtikzパッケージ。その中にはcalcライブラリというものがある。

これはtikzが独自に持つライブラリで、座標の四則演算や交点の算出などが出来るようになる。

代表的な構文を4つ紹介する。

準備

tikzパッケージおよびcalcライブラリを使用するためには、プリアンブル(\\begin\{document\}の前)に次のように記述して、tikzパッケージを使えるようにさせる。

\usepackage{tikz}
\usetikzlibrary{calc}

ここでエラーが出る場合は、使っている環境にtikzパッケージがインストールされていないので、別途インストールする必要がある。

具体例

座標の四則演算

座標をドル記号\$で囲むことで座標の足し算とスカラー倍ができる。

計算の構文は次のようになる。

($スカラー1*(座標1)+スカラー2*(座標2)+...+スカラーn*(座標n)$)

\\coordinateコマンドを使うことで、座標に名前をつけることができる。これはcalcライブラリがなくても使える。

\\coordinateコマンドの構文は次のようになる。

\coordinate (名前) at (座標);

また点を描いたり座標定義したりした後に、node構文を置くことで、文字や数式を埋め込むことができる。

node構文は次のようになる。

node [方向] at (座標) {文字列}
\begin{tikzpicture}
\coordinate (a) at (1,0);
\coordinate (b) at (1,1);
\draw (0,0) grid (3,1);
\fill (0,0) circle [radius=0.1] node [below left] {O};
\fill [red] (a) circle [radius=0.1] node [below left] {a};
\fill [blue] (b) circle [radius=0.1] node [below left] {b};
\fill [purple] ($(a)+(b)$) circle [radius=0.1] node [below left] {a+b};
\fill [magenta] ($2*(a)$) circle [radius=0.1] node [below left] {2a};
\fill [violet] ($2*(a)+(b)$) circle [radius=0.1] node [below left] {2a+b};
\end{tikzpicture}
  • 実行結果

座標の四則演算
座標の四則演算

内分、外分

座標1と座標2をt:1-tに内分する点は次のように求められる。t=0で座標1と一致し、 t=1で座標2と一致する。tが0と1の間だと内分点になり、それ以外だと外分点になる。

($(座標1)!t!(座標2)$) 
\begin{tikzpicture}
\coordinate (a) at (0,0);
\coordinate (b) at (4,0);
\draw (-2,0) -- (6,0);
\fill ($(a)!-0.5!(b)$) circle [radius=0.1] node [below] {t=-0.5};
\fill ($(a)!0!(b)$) circle [radius=0.1] node [below] {t=0};
\fill ($(a)!0.5!(b)$) circle [radius=0.1] node [below] {t=0.5};
\fill ($(a)!1!(b)$) circle [radius=0.1] node [below] {t=1};
\fill ($(a)!1.5!(b)$) circle [radius=0.1] node [below] {t=1.5};
\end{tikzpicture}
  • 実行結果

内分、外分
内分、外分

回転させてから 内分、外分

座標1を中心にa度回転させてから座標1と座標2をt:1-tに内分、外分する構文もある。

($(座標1)!t!a:(座標2)$) 
\begin{tikzpicture}
\coordinate (a) at (0,0);
\coordinate (b) at (4,0);
\draw (-2,0) -- (6,0);
\fill ($(a)!-0.5!30:(b)$) circle [radius=0.1] node [below] {t=-0.5};
\fill ($(a)!0!30:(b)$) circle [radius=0.1] node [below] {t=0};
\fill ($(a)!0.5!30:(b)$) circle [radius=0.1] node [below] {t=0.5};
\fill ($(a)!1!30:(b)$) circle [radius=0.1] node [below] {t=1};
\fill ($(a)!1.5!30:(b)$) circle [radius=0.1] node [below] {t=1.5};
\end{tikzpicture}
  • 実行結果

回転させてから 内分、外分
回転させてから 内分、外分

垂線を下ろした足

座標2から、座標1と座標3を結んだ線分へ垂線を下ろしたときの足の座標を求めることができる。

($(座標1)!(座標2)!(座標3)$)

緑色の点から赤い点と青い点を結んだ線分に下ろした垂線の足に黒い点を描く。

\begin{tikzpicture}
\draw (0,0) grid (3,1);
\fill [green] (1,1) circle [radius=0.1];
\fill [red] (0,0) circle [radius=0.1];
\fill [blue] (3,0) circle [radius=0.1];
\fill ($(0,0)!(1,1)!(3,0)$) circle [radius=0.1];
\end{tikzpicture}
  • 実行結果

垂線を下ろした足
垂線を下ろした足

まとめ

calcライブラリでできることをまとめると次のようになる。

  • 座標の四則演算
  • 座標の内分、外分(回転含む)
  • 点から直線に垂線を下ろした足の座標を求める

参考リンク

tikz wiki