gnuplot memo
インストール
gnuplotだけだとx11で描画されないので注意
$ sudo apt-get install gnuplot gnuplot-x11
- テンプレート
set title "y=sin(x)" # グラフタイトル set grid # grid表示 set size ratio 0.5 # x:y = 1:0.5 set xl "x-axis name" # x軸名 set xl "x-axis name" # y軸名 set xtics 0.1 # x軸の刻み set xrange [0:3.14] # x軸のレンジ set terminal png # 出力デバイス set out "sin.png" # 出力ファイル名 plot sin(x) title "sin(x)" # 凡例
良く使うけど忘れるコマンド
- CSV形式のセパレータ
set datafile separator ","
- 生データから計算した値を使っての描画
iカラムは$iでアクセスできる.(GNUPLOTはインデックスは1から開始)
plot "hoge.dat" using 1:$2+$3
- 凡例の消し方
unset key # 全部消す plot f(x) notitle # 特定のプロットだけ消す
- プロットする色を変更する
4.2以降ではrgb variableというのでline colorを指定できるようになっている.
そして,plotなら3つのカラムを指定して,第3カラムが色をRGBで指定する.
splotも同様に4つのカラムで指定して,第4カラムで色をRGBで指定する.
rgb(r,g,b) = 65536 * int(r) + 256 * int(g) + int(b) plot "hoge.dat" using 1:2:(rgb($3,$4,$5)) with points pt 7 lc rgb variable
# hoge.dat 1 1 255 0 0 2 2 0 255 0 3 3 0 0 255 4 4 255 255 0 5 5 255 0 255 6 6 255 255 0
- リアルタイムな描画
- plot '-' で標準入力からプロットデータを待つようになる.
- プロットの前にeを入力するとそこまでが一つのプロットとして扱われる.
これを使えば,つまりpopenでgnuplotとパイプで繋いで,そこに命令を適時流し込んでいけばリアルタイム描画ができる.
注意としては,各コマンドの最後に改行(\n)が必要.fputsじゃなぜかうまく行かなかった.また,plot '-'からeまでで一つのプロットなので,次のplot '-'に流し込んでも前の点とは繋がらない.
- パイプから使う場合はset mouseしないとマウス効かない.
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> int main() { FILE *fp; // getchar() waiting can be used instead of "persist" option. // fp = popen("gnuplot -persist", "w"); fp = popen("gnuplot", "w"); if (fp == NULL) { fprintf(stderr, "gnuplot can't open\n"); exit(1); } // statically assign the x-y axis fprintf(fp, "set multiplot\n"); fprintf(fp, "set xrange [0:4*3.14]\n"); fprintf(fp, "set yrange [-1.0:1.0]\n"); fflush(fp); // for (int i=0; i<100; ++i) { fprintf(fp, "plot '-' with lines\n"); for (double x=0; x<4*M_PI; x+=0.01) { fprintf(fp, "%f %f\n",x, cos(x+0.1*i)); } fprintf(fp, "e\n"); fflush(fp); } // close getchar(); fprintf(fp, "exit\n"); fflush(fp); pclose(fp); return 0; }
GNUPLOT4.6からはgifアニメーションの作成が容易になった.
reset # set term gif size 1000,800 animate delay 2 set term gif animate set output "animate.gif" n=24 #n frames dt=2*pi/n set xrange [0:4*pi] set yrange [-1:1] do for [i=0:n]{ plot sin(x+i*dt)/(1. + i/12.) w l lw 1.5 title sprintf("t=%i",i) } set output
連番ファイルからgifアニメーション作るのも同様.例えば,d1.dat, d2.dat, ... d10.datがある時.
reset set term gif animate set output "animate.gif" do for [i=0:10]{ plot sprintf("d%i.dat",i) w l } set output
-
- プロット点にラベルを付ける
Webにはテキストを座標に貼り付ける古い情報が多く見られるけど,4.2以降は"with labels"で簡単に描ける.
下みたいにusingでラベル列を指定する.(lineとの併用はできない)
plot "hoge.dat" using 1:2:3 with labels # 3列目にラベルを入れておく