実験で出たデータを手っ取り早くグラフ化して確認したいときに毎度gnuplotでぐぐってる気がするので、自分のために必要最低限だけまとめておきます。
環境
- Ubuntu 16.04LTS
インストール
$ sudo apt install gnuplot
実行
グラフ化したいデータファイルを次のように用意しました。
$ cat data.tr # comment # x y z 1 2 1 2 4 4 3 6 9 4 8 16 5 10 25 6 12 36 7 14 49 8 16 64 9 18 81 10 20 100
gnuplotのスクリプトをファイルへ書きます。 今回はxとyの値を使ったグラフを出力します。zの値は使いません。
$ cat graph.plt set xlabel "x" set ylabel "y" plot "data.tr" using 1:2 w lp title "y = x ^ 2" set terminal png set output "graph.png" replot
xlabelとylabelはx軸y軸のラベル名。plot "data.tr"はgnuplotの核で、そのファイルを読み込んでグラフにプロットする。using 1:2は1行にある空白区切りの1個目(=x)の値をx軸、2個目(=y)をy軸の数字として読み取れという意味。w lpはwith linespointsの短縮形で折れ線グラフになる。title "y = x ^ 2"はそのまま。
ここまでがgnuplotによる画面への出力/描画で、出力先をpngファイルへ切り替えて、ファイル名の指定、pngファイルへの再描画をそれ以下で行っています。
gnuplotコマンドに渡して実行してみます。
$ gnuplot graph.plt

ファイルへの出力だけにしたい場合は、いきなり出力先をpngに切り替えておきます。 WSL上でgnuplotを動かす場合はこうしないとうまく動きませんでした。
$ cat graph.plt set terminal png set output "graph.png" set xlabel "x" set ylabel "y" plot "data.tr" using 1:2 w lp title "y = x ^ 2"
指定できるグラフの種類
| with ??? | |
|---|---|
| lines | ライン表示 |
| points | データポイント表示 |
| linespoints | ラインとデータポイント表示(折れ線表示) |
| impulses | インパルス表示 |
| dots | ドット表示 |
| steps | ステップ表示 |
| errorbars | 誤差グラフ |
| boxes | 棒グラフ |
| boxerrorbars | 誤差と棒グラフ |
CSVファイル
ファイルの先頭にset datafile separator ","を入れることで区切り文字をカンマへ変更できます。
引数を渡す
$ gnuplot -e 'indir="input"; outdir="$OUTPUT_DIR"' myscript.plt
set terminal png set output outdir."/my_plot.png" plot indir."/my_data.dat"
.は文字列結合