Chanomic Blog

gnuplotの使い方メモ

(last modified:
)

備忘録に。

インストール

Macの場合はbrewでインストールできる。

$ brew install gnuplot

gnuplotコマンドで起動。

ファイルをプロットする

例えばdata.txtが以下のようになっているとする。

#x #y1 #y2
0 1 2
1 2 1
2 0 2
3 1 1

これを描画する。

using X:Yで、X番目の列を横軸、Y番目の列を縦軸にする。

w lpとは"with linespoints"の略。つまり線と点を描画する。w lだと"with line"、w lp lt 3 lw 2だと"with linepoints linetype 3 linewidth 2"という意味。いろいろある。

$ set xlabel "X axis"
$ set ylabel "Y axis"
$ plot "data.txt" using 1:2 w pl

軸の範囲指定

例えばx軸を[0,3000]の範囲に制限して描画したいなら、次のコマンドを打つ。

$ set xrange [0:3000]

こんな感じで、gnuplotはset 属性名 値で様々な設定をする印象がある。

グラフの重ね書き

replotを使う方法

$ plot "data.txt" using 1:2 w pl
$ replot "data.txt" using 1:3 w pl

カンマで区切る方法

$ plot "data.txt" using 1:2 w pl, "data.txt" using 1:3 w pl

png形式で出力

Macではset terminal qtだったが、Linuxだとset terminal x11みたい。現在のterminalの確認方法については後述。

$ set terminal png
$ set output "output.png"
...(グラフを描画するためのコマンドを入力)
$ set terminal qt
$ set output

グラフを重ねる場合

replotを用いる場合は、replotのたびにset output "output.png"を呼び出す必要がある。これはgnuplotの仕様らしい。

カンマで区切る場合は問題なくできる。

(おまけ) terminalの確認と一覧

Macだとset terminal x11でエラーを起こした。x11は存在しないらしい。そもそもデフォルトのterminalは何か。次のコマンドで調べられる。

$ show terminal

gnuplotが何のterminalを持っているかは、次のコマンドで調べられる。

$ set terminal

スクリプトを書く

gnuplotを起動していちいちコマンドを打つのは面倒なので、あらかじめスクリプトでまとめておく。例えば以下のような感じ。拡張子はなんでも良さそうだが、とりあえずtest.pltとする。バックスラッシュ + 改行でつなげると一つのコマンドとして認識される。

set terminal png
set output "output.png"
set xlabel "X axis"
set ylabel "Y axis"
plot "data.txt" using 1:2 w lp, \
  "data.txt" using 1:3 w lp, \
  "data.txt" using 1:4 w lp
set terminal qt
set output