🐳
Typstで実験レポート用の表を作る
はじめに
大学の実験レポートでは、表の形式が指定されていることがあります。大学や学部によって違いがあると思いますが、私の場合は次のような形式を指定されることが多かったです。
これを愚直に書くと、こうなります(表以外の設定は省略)。
#set table(inset: (x: 0.8em, y: 0.6em), stroke: none)
#set table.hline(stroke: 0.6pt)
#set table.vline(stroke: 0.6pt)
#figure(
table(
columns: 3,
table.hline(),
table.header([試料], [加熱前の質量 [g]], [加熱後の質量 [g]]),
table.hline(),
[A], [0.823], [0.813],
[B], [0.880], [0.872],
[C], [0.590], [0.585],
table.hline()
)
)
tableのかっこ()の中を見ると、たった4行の表を入れるために8行も書いています。在学中何度も書くであろう実験レポートで毎回こんなことをしていたら大変なので、もっと楽にやろう、というのがこの記事の内容です。
結論、ラッパー関数を定義しよう
目的の表を表示するラッパー関数を定義するのがよかったです。かっこ{}で挟むことで簡単に作れます。
#let mytable(header, cells) = {
table(
columns: header.len(),
table.hline(),
table.header(..header.flatten()),
table.hline(),
..cells,
table.hline(),
)
}
以下のように使います。
#figure(
mytable(
([試料], [加熱前の質量 [g]], [加熱後の質量 [g]]),
([A], [0.823], [0.813],
[B], [0.880], [0.872],
[C], [0.590], [0.585]),
),
caption: [表のサンプル]
)
もともと8行あったのが4行になりました。全体的に文字数が減って書きやすくなっています。
これでも十分ですが、せっかくなので縦線を簡単に入れられるように拡張していきます。
今回はTypst Universeで提供されているpillarというライブラリを使います。新しい引数colsを追加し、colsが指定されている場合にpillarの機能で縦線を入れるようにします。
#import "@preview/pillar:0.3.2"
#set table(inset: (x: 0.8em, y: 0.6em), stroke: none)
#set table.hline(stroke: 0.6pt)
#set table.vline(stroke: 0.6pt)
#let mytable(header, cells, cols: none) = {
if cols == none {
table(
columns: header.len(),
table.hline(),
table.header(..header.flatten()),
table.hline(),
..cells,
table.hline(),
)
}
else {
table(
..pillar.cols(cols),
columns: header.len(),
table.hline(),
table.header(..header.flatten()),
table.hline(),
..cells,
table.hline(),
)
}
}
以下のように、引数colsで縦棒(|)を入れたところに縦線が入ります。
#figure(
mytable(
([試料], [加熱前の質量 [g]], [加熱後の質量 [g]]),
([A], [0.823], [0.813],
[B], [0.880], [0.872],
[C], [0.590], [0.585]),
cols: "c|cc"
),
caption: [表のサンプル]
)
フッターをつけたい場合
フッターつきの表を作る関数は以下のようになります。合計や平均を表に入れたいときに使えます。
#let mytable_with_footer(header, cells, footer, cols: none) = {
if cols == none {
table(
columns: header.len(),
table.hline(),
table.header(..header.flatten()),
table.hline(),
..cells,
table.hline(),
table.footer(..footer.flatten()),
table.hline()
)
}
else {
table(
..pillar.cols(cols),
columns: header.len(),
table.hline(),
table.header(..header.flatten()),
table.hline(),
..cells,
table.hline(),
table.footer(..footer.flatten()),
table.hline()
)
}
}
#figure(
mytable_with_footer(
([試料], [加熱前の質量 [g]], [加熱後の質量 [g]]),
([A], [0.823], [0.813],
[B], [0.880], [0.872],
[C], [0.590], [0.585]),
([合計], [2.293], [2.270])
),
caption: [表のサンプル]
)
余談:CSVファイルを読み込む
TypstにはCSVファイルのデータから表を作る機能がありますが、上で定義したmytable関数でも問題なく使えます。
次のようなCSVファイルを用意しておき、引数cellsにファイル名を指定することで表にすることができます。
data.csv
A, 0.823, 0.813
B, 0.880, 0.872
C, 0.590, 0.585
#figure(
mytable(
([試料], [加熱前の質量 [g]], [加熱後の質量 [g]]),
(csv("data.csv").flatten()),
),
caption: [表のサンプル]
)
参考文献
Discussion