tags:

views:

203

answers:

2

I would like to do some basic charting in F# using build in features or a free library. And I would be very very pleased with a very basic example of it, a pie chart if possible.

Example data :

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

Where the ints are percentages to be represented in the pie.

I have recently installed VSLab and though I find a lot of 3D examples, I am only looking for a simple pie chart...

It is also fine to use excel features by the way, not free, but installed nevertheless..

+5  A: 

Here's something I smashed together using the Google Chart API, I hope the code is clear enough without further explanation:

//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()
cfern
+1 for your effort, no time to go into in now, I will except it laterif it works
Peter
+1  A: 

It's easy to do "made in home" pie chart: open 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))
ssp
+1 probably not the one I will end up using, but kudos for home cooking!
Peter