質問

組み込み機能または無料ライブラリを使用して、F# で基本的なグラフ作成を行いたいと考えています。できればその非常に基本的な例、円グラフを教えていただければ幸いです。

データ例:

[("John",34);("Sara",30);("Will",20);("Maria",16)] 

ここで、int は円で表されるパーセンテージです。

最近 VSLab をインストールしました。たくさんの 3D サンプルを見つけましたが、単純な円グラフしか探していません...

ちなみに、無料ではありませんが、インストールされた Excel の機能を使用することもできます。

役に立ちましたか?

解決

これは、Google Chart APIを使用してまとめたものです。 詳細な説明がなくてもコードが十分に明確であることを願っています:

//Built with F# 1.9.7.8
open System.IO
open System.Net
open Microsoft.FSharp.Control.WebExtensions
//Add references for the namespaces below if you're not running this code in F# interactive
open System.Drawing 
open System.Windows.Forms 

let buildGoogleChartUri input =
    let chartWidth, chartHeight = 250,100

    let labels,data = List.unzip input
    let dataString = 
        data 
        |> List.map (box>>string) //in this way, data can be anything for which ToString() turns it into a number
        |> List.toArray |> String.concat ","

    let labelString = labels |> List.toArray |> String.concat "|"

    sprintf "http://chart.apis.google.com/chart?chs=%dx%d&chd=t:%s&cht=p3&chl=%s"
            chartWidth chartHeight dataString labelString

//Bake a bitmap from the google chart URI
let buildGoogleChart myData =
    async {
        let req = HttpWebRequest.Create(buildGoogleChartUri myData)
        let! response = req.AsyncGetResponse()
        return new Bitmap(response.GetResponseStream())
    } |> Async.RunSynchronously

//invokes the google chart api to build a chart from the data, and presents the image in a form
//Excuse the sloppy winforms code
let test() =
    let myData = [("John",34);("Sara",30);("Will",20);("Maria",16)]

    let image = buildGoogleChart myData
    let frm = new Form()
    frm.BackgroundImage <- image
    frm.BackgroundImageLayout <- ImageLayout.Center
    frm.ClientSize <- image.Size
    frm.Show()

他のヒント

「ホームメイド」を行うのは簡単です;円グラフ:     System.Drawingを開きます

let red = new SolidBrush(Color.Red) in
let green = new SolidBrush(Color.Green) in
let blue = new SolidBrush(Color.Blue) in
let rec colors =
  seq {
    yield red
    yield green
    yield blue
    yield! colors
  }


let pie data (g: Graphics) (r: Rectangle) =
  let vals = 0.0 :: List.map snd data
  let total = List.sum vals
  let angles = List.map (fun v -> v/total*360.0) vals
  let p = new Pen(Color.Black,1)
  Seq.pairwise vals |> Seq.zip colors |> Seq.iter (fun (c,(a1,a2)) -> g.DrawPie(p,r,a1,a2); g.FillPie(c,r,a1,a2))

古い質問ですが、テクノロジーは変化しています。

2013年、F#3とNugetパッケージのインストール

 Install-Package FSharp.Charting

参照先を追加:

    System.Windows.Forms
    System.Windows.Forms.DataVisualization

および1行のコード:

     Application.Run ((Chart.Pie data).ShowChart())

次のF#コードは、bieチャートを生成します。

open System
open System.Windows.Forms
open FSharp.Charting

[<EntryPoint>]
let main argv =  
    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault false   
    let data =[("John",34);("Sara",30);("Will",20);("Maria",16)]      
    Application.Run ((Chart.Pie data).ShowChart())
    0

次のチャートが表示されます:

ここに画像の説明を入力してください

元々は補完するだけだった SSPの ここでは、円を表示する非常に単純な Windows フォーム ダイアログの例を示します。しかし、これを試してみると、ssp のコードにバグが見つかりました。一方では Seq.pairwise で動作します vals の代わりに angles 一方、円グラフのスライスが開始角度からスイープ角度に沿って描画されることは明らかに考慮されていません。

バグを修正し、コメントを付け、再配置し、再フォーマットし、いくつかの名前を変更しました。そして、両方を実現しました。 #load-可能 fsi.exe そして コンパイル可能fsc.exe:

#light
module YourNamespace.PieExample

open System
open System.Drawing
open System.ComponentModel
open System.Windows.Forms

(* (circular) sequence of three colors *)
#nowarn "40"
let red = new SolidBrush(Color.Red)
let green = new SolidBrush(Color.Green)
let blue = new SolidBrush(Color.Blue)
let rec colors =
    seq { yield red
          yield green
          yield blue
          yield! colors }

(* core function to build up and show a pie diagram *)
let pie data (g: Graphics) (r: Rectangle) =
    // a pen for borders of pie slices
    let p = new Pen(Color.Black, 1.0f)
    // retrieve pie shares from data and sum 'em up
    let vals  = List.map snd data
    let total = List.sum vals
    // baking a pie starts here with ...
    vals
    // scaling vals in total to a full circle
    |> List.map (fun v -> v * 360.0 / total)
    // transform list of angles to list of pie slice delimiting angles
    |> List.scan (+) 0.0
    // turn them into a list of tuples consisting of start and end angles
    |> Seq.pairwise
    // intermix the colors successively
    |> Seq.zip colors 
    // and at last do FillPies and DrawPies with these ingredients
    |> Seq.iter (fun (c,(starta,enda))
                     -> g.FillPie(c,r,(float32 starta)
                                     ,(float32 (enda - starta)))
                        g.DrawPie(p,r,(float32 starta)
                                     ,(float32 (enda - starta))))

(* demo data *)
let demolist = [ ("a", 1.); ("b", 2.); ("c", 3.);
                 ("d", 2.); ("e", 2.); ("f", 2.) ]

(* finally a simple resizable form showing demo data as pie with 6 slices *)
let mainform = new Form(MinimumSize = Size(200,200))
// add two event handlers
mainform.Paint.Add (fun e -> pie demolist e.Graphics mainform.ClientRectangle)
mainform.Resize.Add (fun _ -> mainform.Invalidate())
#if COMPILED
Application.Run(mainform)
#else
mainform.ShowDialog() |> ignore
#endif

最後になりましたが、私が役に立ったと感じた 2 つの役立つヒントについて触れたいと思います。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top