Bus errorとSegmentation faultに困ったら見るブログ

物理の研究者による日々の研究生活のメモ書きです ( python/emacs/html/Japascript/シェルスクリプト/TeX/Mac/C言語/Linux/git/tmux/R/ポケモンGO)

【gnuplot 6】gsl-histogramの結果を塗りつぶしてプロットしたい

GSLをインストールすると、一緒にgsl-histogramというコマンドもインストールされる

使い方 :
Usage: gsl-histogram xmin xmax [n]

Computes a histogram of the data on stdin using n bins from xmin to xmax.
If n is unspecified then bins of integer width are used.

要するに
gsl-histogram 0 100 50
で0から100の間を50ビンで区切ってヒストグラムを計算してくれる

もしデータが1列じゃないが、3列目のみのヒストグラムを書きたい場合はawkを使って

awk '{print $3}' | gsl-histogram 0 100 50
とかでおk



実例を示すためにサンプルデータを作る

# データ作り
%gsl-randist 0 10 rayleigh 2 > hoge.txt

# データの中身はこれ
% cat hoge.txt
0.0454563
3.81005
3.17951
0.65875
3.42053
2.40609
0.589601
1.53702
2.2201
1.55221

# この行でヒストグラムを取っている、0~5を5ビンで分ける
% awk '{print $1}' hoge.txt | gsl-histogram 0 5 5 > hist.txt

# ヒストグラムの中身、1列目がビンの左端の点、2列目がビンの右端の点、3列目がそのビンに入っているサンプル数
# echo 1 | gsl-histogram 0 2 2 とかで確認できる
% cat hist.txt
0 1 3
1 2 2
2 3 2
3 4 3
4 5 0


gnuplotを使ってプロットしてみる

# with boxesで描いてみる
# with boxesは省略不能
plot [-1:5][0:4] "hist.txt" u 1:3 with boxes

または

# with stepsで描いてみる
# with stと省略可能
plot [-1:5][0:4] "hist.txt" u 1:3 with st


この二つを見比べるとboxesは全体を線で囲って箱にしているのに対して、stepsではそれに沿ってステップ関数を描いているだけ(というかまさに名前がそうなんだけど・・・)

問題はヒストグラムは0から5までなのにboxesの方は-0.5から値があるように描かれていること
理想的にはx=0~1の範囲が3、x=1~2の範囲が2、x=2~3の範囲が2、x=3~4の範囲が3、x=4~5の範囲が0のステップ関数になっていて欲しいので、この場合はstepsの方が求めているものに近い
ただ左端と右端(今回は0だからわからないけど)の挙動がなんか思ってるのと違う・・・
そこも縦棒を描いてほしいんだが・・・


しょうがないのでwith boxesの方にオプションを追加してみる

plot [0:5][0:4] "hist.txt" u ($1+0.5):3 with boxes fs solid 0.25 lc 6 lw 3




他にも

plot [0:5][0:4] "hist.txt" u ($1+0.5):3 with boxes fill pattern 4 lc 6

とかもできる

どういうパターンがあるかは

set term pnt
set output "hoge.png"
test
で確認できる

■ 参考 : gnuplot demo script: fillstyle.dem

■ 参考 : Boxes



同じような塗りつぶしはwith stepsでもできる(最初こっちでやっていて、両端がなんか気に入らなかったので使用をやめた)

plot [-1:5][0:4] "hist.txt" u 1:3 with fillsteps fs solid 0.25 noborder ls 7, "" u 1:3 with steps ls 7 lw 3


やっぱり左端(見えないけど右端も)の扱いがなんか嫌・・・
なので今回はwith boxesのほうを使う

■ 参考 : filling under step functions in gnuplot




まったく関係ないけど、with histepsというのもある(hiは何の略だろう?)
これをwith stepsの代わりに使うとboxesみたいに半ビンだけ左にずれる

plot [-1:5][0:4] "hist.txt" u 1:3 with fillsteps fs solid 0.25 noborder ls 7, "" u 1:3 with histeps ls 7 lw 3



一応上記のwith boxes+囲い線のオプションを使えばこんな感じのグラフも作れる
画像検索でのHIT狙いで追記してみた(スクショだからちょっと線の太さが違う)




2種類のヒストグラムを重ね書きするときに半透明にするオプションもあります

(データ生成の方法はパス)

set style fill transparent solid 0.15
set term png
set output "hoge.png"
plot [0:20]"hist_2.txt" u ($1+0.5):3 with boxes fs lc 7 lw 3 title "rayleigh 2", "hist_5.txt" u ($1+0.5):3 with boxes fs lc 6 lw 3 title "rayleigh 5"
これで


ランキング参加中です

↓クリックしていただけると嬉しいです〜