12
6

More than 5 years have passed since last update.

Haskellで図の描画(gnuplot)-使用例-

Last updated at Posted at 2018-04-07

Haskellで図の描画(gnuplot)-解説編-の双子記事です。

Haskell でグラフ作成

Haskellで遊んでいると、どうしてもグラフを出力したくなります(この記事でのグラフはすべて図のグラフです)。代表的なグラフ作成の方法として、Chart と gnuplotがありますが、今回は Gnuplot を紹介します。

gnuplotを使う利点としては、セットアップが簡単であることでしょう。例えば Ubuntuなら、

sudo apt-get install gnuplot
cabal install gnuplot

でインストールできます。
使うときも、

import Graphics.Gnuplot.Simple

で済みます。
以前は使用例と解説両方を書く予定でしたが、想像以上に書きたい内容が多いので、解説は別記事にします。この記事では PNG, EPS に出力するコードのサンプルを載せていく予定です。
基本、コメントアウトの箇所を編集することでグラフを変更することができると思います。
当たり前ですが、不明な点は、gnuplot自体、Graphic.Gnuplotの両方調べるのがポイントです。

2D軌跡

import Graphics.Gnuplot.Simple

--z::[[(Double,Double)]] legend::[String]
costumPlotPaths z legend = plotPathsStyle atribute plotstyle
  where
    fontType = "Helvetica"
    tics     = Custom "tics"   ["font","\""++fontType++",16\""] -- 目盛りのフォントの変更
    xlavel   = Custom "xlabel" ["font","\""++fontType++",20\""] -- xlabelのフォントの変更
    ylavel   = Custom "ylabel" ["font","\""++fontType++",20\""] -- ylabelのフォントの変更
    keyFont  = Custom "key"    ["font","\""++fontType++",18\""] -- 凡例のフォントの変更    
    titleFont= Custom "title"  ["font","\""++fontType++",24\""] -- タイトルのフォントの変更    
    key = [(Key (Just["box lt 8 lw 1"]))]--凡例の枠囲み凡例の位置変更はこのリストに(Key (Just["right bottom"]))等を追加
    label = [(YLabel "y"),(XLabel "x")]--軸の見出し
    save = [EPS "test.eps",Custom "terminal" ["eps","enhanced","color"],Custom "bmargin" ["4"]]
    --save = [PNG "test.png"] -- PNGで出力するときは上の一文をコメントアウトしこれを使う。
    title = [Title "sin and arcsin"]--グラフのタイトル
    size = [Aspect (Ratio 0.7)]--グラフの形 縦/横
    font = [tics,xlavel,ylavel,keyFont,titleFont]
    atribute = (save++key++label++title++size++font)--fontは後述
    plotstyle = [x|i <-[0..(length z-1)],let x = (defaultStyle {lineSpec = CustomStyle [(LineTitle (legend!!i)),(LineWidth 2.0)]},z!!i)]

--例
main = do
  let x = linearScale 1000 ((-2::Double)*pi,2*pi)
  let y = fmap sin x
  let z = zip x y
  let w = zip y x
  let legend = ["sin","arcsin"]--線の名前、凡例に反映
  costumPlotPaths [z,w] legend

test.png

今後の予定

急ぎ解説記事を更新、グラフの種類を増やします。

12
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
6