How to: Create Pie and Doughnut Charts

Applies to: Functional Programming

Authors: Tomas Petricek and Jon Skeet

Referenced Image

Get this book in Print, PDF, ePub and Kindle at manning.com. Use code “MSDN37b” to save 37%.

This topic contains the following sections.

  • Introduction
  • Using FSharpChart
  • Using .NET Chart Controls
  • Running the Code
  • See Also

Introduction

Summary: This article shows how to create pie and doughnut charts in F#. The example visualizes the proportion of seats taken by individual parties in the UK general elections.

This article is associated with Real World Functional Programming: With Examples in F# and C# by Tomas Petricek with Jon Skeet from Manning Publications (ISBN 9781933988924, copyright Manning Publications 2009, all rights reserved). No part of these chapters may be reproduced, stored in a retrieval system, or transmitted in any form or by any means—electronic, electrostatic, mechanical, photocopying, recording, or otherwise—without the prior written permission of the publisher, except in the case of brief quotations embodied in critical articles or reviews.

This article looks at how to create pie and doughnut charts from F#. It presents two versions of the example. The first one uses the FSharpChart library that is available as a free download and the second uses the .NET Chart Controls directly. For more information about loading the two libraries from F#, refer to the Running the Code section at the end of the page.

The input data in this example is an F# list of tuples containing the names of political parties and their respective numbers of elected candidates. The example demonstrates how to display a pie/doughnut chart showing the proportion of seats taken by each party. A sample doughnut chart is shown in Figure 1.

Figure 1. Doughnut chart showing proportion of seats

Referenced Image

Using FSharpChart

A pie or a doughnut chart can be created using theFSharpChart.Pie and FSharpChart.Doughnut functions. These functions are overloaded and can be called with various types of parameters. When creating pie or doughnut charts, it is usually desirable to provide both labels and values. This can be done by using two separate collections or using a single collection storing labels and values as tuple. Here are three examples:

let data = 
  [ "Conservative", 306; "Labour", 258; 
    "Liberal Democrat", 57 ]

// Create doughnut chart showing the data
FSharpChart.Doughnut(data)

// Chart showing number of seats in the label
[ for n, v in data -> sprintf "%s (%d)" n v, v ]
|> FSharpChart.Doughnut

// Create pie chart from two separate lists
FSharpChart.Pie( [ "Conservative"; "Labour"; "Liberal Democrat"; ],
           [ 306; 258; 57 ] )

When using F# Interactive, each of these examples needs to be evaluated separately. This way, F# Interactive invokes a handler that automatically shows the created chart.

The first part of the example works with a list containing labels and values as tuples. The benefit of this approach is that data can be easily preprocessed. The second example uses sequence expressions to add the number of seats to the label. This also fits well with pipelining (|> operator), which can process data in several steps and then send the result to a function that visualizes it. The last example uses an alternative approach where the data is stored as two separate collections.

Using .NET Chart Controls

This section shows how to create the same charts using .NET Chart Controls. The following example stores the data as a list of tuples. When constructing the chart, the type of the chart can be specified using the ChartType property of the Series object. To create a pie chart, the property should be set to SeriesChartType.Pie. A doughnut chart can be created using the SeriesChartType.Doughnut option.

let data = 
  [ "Conservative", 306; "Labour", 258; "Liberal Democrat", 57 ]

// Create a chart containing a default area and show it on a form
let chart = new Chart(Dock = DockStyle.Fill)
let form = new Form(Visible = true, Width = 700, Height = 500)
chart.ChartAreas.Add(new ChartArea("MainArea"))
form.Controls.Add(chart)

// Create series and add it to the chart
let series = new Series(ChartType = SeriesChartType.Doughnut)
chart.Series.Add(series)
// Specify data for the series using data binding
series.Points.DataBindXY(data, "Item1", data, "Item2")

After initializing the list, the snippet constructs the user interface elements. The snippet displays the chart in a new window. It creates a Form, the Chart control, and then adds the control to the form. Then it creates a new series and specifies the type of the chart that it represents. Finally, the snippet uses data binding to provide data for the series. When binding to tuples, elements of the tuple can be accessed using the Item1 and Item2 properties.

Running the Code

This section reviews the prerequisites needed to run the two examples discussed above. Both of the approaches build on top of the Microsoft Charting Library, which is available as part of the .NET 4.0 framework and can be downloaded separately for .NET 3.5.

Using the FSharpChart Library

The F# Charting library is available as a free download. The easiest way to use the library from F# Interactive is to download the library source code (FSharpChart.fsx) and load it in F# Interactive using the #load command:

#load "FSharpChart.fsx"

open System
open System.Drawing
open MSDN.FSharp.Charting

This snippet opens the namespaces that is needed when working with the library (the above examples assume these namespaces are opened). The namespace Samples.Charting contains the F# charting functionality. After writing the above lines, charts can be created using the FSharpChart type.

  • When loading the FSharpChart library in F# Interactive using the FSharpChart.fsx script file, it is not necessary to explicitly load the .NET Chart Controls assembly (System.Windows.Forms.DataVisualization.dll), because it is automatically referenced by the library script.

  • When creating a chart in a Windows Forms application, it is easier to reference the compiled version of the FSharpChart library (which can be downloaded as part of the sample source code at the end of the article). The library name is Samples.Charting.dll and it needs to be referenced together with the .NET Chart Controls assembly System.Windows.Forms.DataVisualization.dll. This can be done using the "Add Reference" command in Solution Explorer in Visual Studio.

Using .NET Chart Controls

When creating a chart from an F# script using F# Interactive, the script needs to reference the Microsoft Chart Controls assembly for Windows Forms. This is done by adding the following lines to an F# Script File (e.g. Script.fsx):

#r "System.Windows.Forms.DataVisualization.dll"

open System
open System.Drawing
open System.Windows.Forms
open System.Windows.Forms.DataVisualization.Charting

The code snippets in the first sections don't include these import declarations. In order to compile the code (as a standalone application), the following step is needed as well:

  • When creating a chart in a Windows Forms application or a library, the project needs to reference the .NET Chart Controls assembly using the "Add Reference" command in Solution Explorer in Visual Studio. The name of the assembly is System.Windows.Forms.DataVisualization.dll.

See Also

This article demonstrates how to use the FSharpChart library and .NET Chart Controls to create charts. For more information about charting in F# visit the following page:

This article is based on Real World Functional Programming: With Examples in F# and C#. Book chapters related to the content of this article are:

  • Book Chapter 4: “Exploring F# and .NET libraries by example” demonstrates how to create a simple charting application from scratch. This chapter is useful for learning F# programming when focusing on working with data.

  • Book Chapter 12: “Sequence expressions and alternative workflows” explains how to work with in-memory data sets in F# using sequence expressions and higher-order functions.

  • Book Chapter 13: “Asynchronous and data-driven programming” shows how to use asynchronous workflows to obtain data from the internet, how to convert data to a structured format, and how to chart it using Excel.

To download the code snippets shown in this article, go to https://code.msdn.microsoft.com/Chapter-6-Visualizing-Data-c68a2296

Previous article: How to: Create Bar and Column Charts

Next article: How to: Create Line and Point Charts