How to: Create Bar and Column Charts
Applies to: Functional Programming
Authors: Tomas Petricek and Jon Skeet
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 bar and column charts in F#. The example visualizes the size of the populations of the continents.
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 bar and column 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 continent names and total populations. The article demonstrates how to display a bar/column chart with names of continents as labels and the population as the value. A sample bar chart is shown in Figure 1.
Figure 1. A bar chart showing population of continents
Using FSharpChart
A bar or a column chart can be created using the FSharpChart.Column and FSharpChart.Bar functions. These functions are overloaded and can be called with various types of parameters. To generate a chart with just the Y values, they can be given a sequence of numeric values as the argument. The discussed example provides strings as X values (bar or column labels) in addition to the Y values. Here are two ways this can be done:
[ "Africa", 1033043; "Asia", 4166741;
"Europe", 732759; "South America", 588649;
"North America", 351659; "Oceania", 35838 ]
|> FSharpChart.Bar
FSharpChart.Column
( [ "Africa"; "Asia"; "Europe";
"South America"; "North America"; "Oceania" ],
[ 1033043; 4166741; 732759;
588649; 351659; 35838 ] )
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 version specifies the data source as a single list that contains two-element tuples. The first element of the tuple is the X value (category) and the second element is the population. When calling a function with just a single argument, the code can be written elegantly using pipelining (|> operator). The second version uses separate collections for the labels and the values.
Using .NET Chart Controls
This sections shows how to create the same chart 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 bar chart, the property should be set to SeriesChartType.Bar. A column chart is the default type, so the type doesn't have to be specified (but it is useful to set the proeprty to SeriesChartType.Column to make the code more readable).
// A collection of tuples containing continent
// names with total size of the population
let data =
[ "Africa", 1033043; "Asia", 4166741;
"Europe", 732759; "South America", 588649;
"North America", 351659; "Oceania", 35838 ]
// 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.Bar)
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, the 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 Standard Charts in F#
Next article: How to: Create Pie and Doughnut Charts