Click here to Skip to main content
Click here to Skip to main content

WPF Toolkit Charting Controls (Line, Bar, Area, Pie, Column Series) Demo

By , 15 May 2011
 

Introduction

I’m currently working on a few Data Visualization projects and am using WPF most of the time. Charting controls are very useful for the one related to statistics and data handling. WPF toolkit is free and open source, however is used by few because of its limited charting support. In my opinion, it is quite useful and straightforward to use.

Here, I’m just demonstrating the basic charting controls and setting data for display. For articles related to this in future, I shall demonstrate advanced features of WPF Toolkit.

Beginning

No prior knowledge of WPF is required. You just need to be aware of HTML (which I’m pretty sure everyone is, nowadays). XAML coding is pretty fun.

Firstly, I’ll mention the installation steps and then will dive into coding XAML and related C# files for visualizing static set of data.

First Step – Install WPF Toolkit

Install WPF Toolkit from this site:

(Please check the installation and usage instructions as mentioned here.)

Add new WPF application in Visual Studio.

If you are not able to view chart controls in Toolbox, right click Toolbox and select Choose Items. Then click on WPF components and select chart controls (the ones mentioned in the title). This will add the controls to your toolbox and you should be able to drag and drop them on the XAML form.

Second Step – XAML Coding for Charting Controls

XAML (Extensible Application Markup Language) is a markup language for declarative application programming. If you are interested in knowing more about XAML, please refer to the MSDN documentation at http://msdn.microsoft.com/en-us/library/ms747122.aspx.

As you can see in the following MainWindow.xaml code, there are a lot of <chartingToolkit:Chart> tags, each one refers to the 5 different charting controls that we are going to use.

<Window x:Class="WpfToolkitChart.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="1031" Width="855" xmlns:chartingToolkit=
	"clr-namespace:System.Windows.Controls.DataVisualization.Charting;
	assembly=System.Windows.Controls.DataVisualization.Toolkit">
    <ScrollViewer HorizontalScrollBarVisibility="Auto" 
	VerticalScrollBarVisibility="Auto" Margin="0,-28,0,28">
        <Grid Height="921">
            <chartingToolkit:Chart Height="262" HorizontalAlignment="Left" 
		Margin="33,0,0,620" Name="columnChart" Title="Column Series Demo" 
		VerticalAlignment="Bottom" Width="360">
                <chartingToolkit:ColumnSeries DependentValuePath="Value" 
		IndependentValuePath="Key" ItemsSource="{Binding}" />              
            </chartingToolkit:Chart>
            <chartingToolkit:Chart  Name="pieChart" Title="Pie Series Demo" 
		VerticalAlignment="Top" Margin="449,39,43,0" Height="262">
                <chartingToolkit:PieSeries DependentValuePath="Value" 
		IndependentValuePath="Key" ItemsSource="{Binding}" 
		IsSelectionEnabled="True" />
            </chartingToolkit:Chart>
            <chartingToolkit:Chart  Name="areaChart" Title="Area Series Demo" 
		VerticalAlignment="Top" Margin="33,330,440,0" Height="262">
                <chartingToolkit:AreaSeries DependentValuePath="Value" 
		IndependentValuePath="Key" ItemsSource="{Binding}" 
		IsSelectionEnabled="True"/>
            </chartingToolkit:Chart>
            <chartingToolkit:Chart  Name="barChart" Title="Bar Series Demo" 
		VerticalAlignment="Top" Margin="449,330,43,0" Height="262">
                <chartingToolkit:BarSeries  DependentValuePath="Value" 
		IndependentValuePath="Key" ItemsSource="{Binding}" 
		IsSelectionEnabled="True"/>
            </chartingToolkit:Chart>
            <chartingToolkit:Chart  Name="lineChart" Title="Line Series Demo" 
		VerticalAlignment="Top" Margin="33,611,440,0" Height="254">
                <chartingToolkit:LineSeries  DependentValuePath="Value" 
		IndependentValuePath="Key" ItemsSource="{Binding}" 
		IsSelectionEnabled="True"/>
            </chartingToolkit:Chart>
        </Grid>
    </ScrollViewer>
</Window>

Beginning with the <window> tag, you can see that there is an attribute that says xmlns:chartingToolkit which is basically a namespace referring to the added WPF Toolkit.

I’ve used <ScrollViewer> tag in order to add horizontal and vertical scrollbars to the XAML page.

Now starting with first charting control, columnChart, drag and drop the column series control in toolbox on XAML page and you will see a rectangle with nothing inside. Look in the XAML window (usually below the Designer), and you will see:

<chartingToolkit:ColumnSeries DependentValuePath="Value" 
IndependentValuePath="Key" ItemsSource="{Binding}" />

Now all the charting controls needs to be encapsulated in <chartingToolkit:Chart> (which is a good practice). It has different attributes such as height, horizontal alignment, name, title, width, etc. which are just concerned with the way in which it appears on the page.

Our basic concern is understanding the attributes of <chartingTookit:columnSeries> here and in all other charting controls. I’m using three attributes. DependentValuePath and IndependentValuePath are related to the Axis of the Chart (i.e. X-axis, Y-axis). “Value” and “Key” as assigned to them respectively - this is because I’m using KeyValuePair<> data type in my data model (which has Key and Value). You can also use Dictionary or any other data type by just making sure that you have two parameters that are interdependent for visualization. Itemsource attribute is used for binding our data to the control.

Follow the same as above for all the other controls as mentioned and now we shall assign the data model to the controls.

Third Step – Assigning Data Model to the Controls

As you can see in the MainWindow.xaml.cs file, it is pretty straightforward with the way we are assigning data model.

namespace WpfToolkitChart
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();
      showColumnChart();
    }

    private void showColumnChart()
    {
      List<KeyValuePair<string, int>> valueList = new List<KeyValuePair<string, int>>();
      valueList.Add(new KeyValuePair<string, int>("Developer",60));
      valueList.Add(new KeyValuePair<string, int>("Misc", 20));
      valueList.Add(new KeyValuePair<string, int>("Tester", 50));
      valueList.Add(new KeyValuePair<string, int>("QA", 30));
      valueList.Add(new KeyValuePair<string, int>("Project Manager", 40));

      //Setting data for column chart
      columnChart.DataContext = valueList;

      // Setting data for pie chart
      pieChart.DataContext = valueList;

      //Setting data for area chart
      areaChart.DataContext = valueList;

      //Setting data for bar chart
      barChart.DataContext = valueList;

      //Setting data for line chart
      lineChart.DataContext = valueList;
    }

  }
}

I’m using static list with 5 entries. DataContext is the property assigned to charting controls and you can assign the list directly to the controls and you are good to go.

Fourth Step – Compile and Run

Compile and run and you should see the following:

Charting_Controls_Screen.png

Conclusion

I hope this article provides you with enough assistance to keep the work going on for visualizing information. Information Visualization is changing the way people look at data and in my view, it is going to play a key role in future.

I’ll explain advanced features related to assigning complex data model to controls in the future.

History

  • 15th May, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Priyank Kabaria
Student
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionStyling examplesmemberMember 824721922 Feb '13 - 8:53 
Hello, i want to ask if you can make a styling example.
 
how i remove the text "Series 1" for example.
 
(Sorry for my bad english :s)
GeneralThank you... It works fine. And thriugh this i learnt how manipulate graphs.memberShankar_s19 Feb '13 - 23:26 
Great !!
QuestionI have an error with the InternalActualIndependentAxis nullmemberEnricoOliva28 Sep '12 - 6:16 
Thank you for your example.
 
I try to put it in my user control, when I add a key pair value
the system crashes with a null pointer exception on ActualIndependentAxis.
 
Which is the problem?
How can avoid the null axis?
QuestionDatapoint TooltipmemberPaul Tan9 Sep '12 - 22:29 
I'm using the line series. How do I change the Tooltip template for the datapoints? I could only manage to change the tooltip for the line itself but not the datapoints.
GeneralThank you, used your article as a basismemberwoutercx11 Aug '12 - 7:45 
I was trying to solve problem 66 at projecteuler.net, and I wanted to plot some data in a chart. Your article was just what I needed to get started doing a simple Line chart. 5 stars!
GeneralMy vote of 5memberMember 53622918 Jun '12 - 1:35 
The sample works and is easy to understand
QuestionChange color to ColumnDatamemberstranet4 Jun '12 - 23:37 
Hi to all,
is possible to change the series element color?
I can't find how!
 
Please Help
GeneralThank YoumemberGil.Y29 May '12 - 21:17 
It is simple, short, precise and saved me alot of time.   Cool | :cool:
Questionhow to put two different data with different color in single area chartmemberd474211 May '12 - 0:40 
how to put two different data with different color in single area chart
 
if you have some sollutions for this then pls provide me asap
QuestionHow to display both +ve and -ve values in chart control for LineSeriesmemberMember 831376710 May '12 - 23:51 
How to show the positive and negative values in chart control specially on y axis. The x axis must be positive values only. And type of series is line series.
 
I am using WPFToolKit chart control.
 
I need both +ve and -ve values to be displayed in 'Y'- axis and only +ve values in 'X'- axis. I used Location property for LinearAxis but all -ve and +ve values are coming in one quadrant only. I want the +ve values to come in 1st quadrant and -ve values to come in 4th quadrant.
QuestionConnectivity with databasememberwizardbot2 Apr '12 - 1:18 
I am completely new to WPF. I want to use it for a project. I have multi-dimensional database and want my application to interact with it and draw pie/bar charts. How can this be done?
 
Please reply, thank you.
QuestionHow to add Spline chartmembertan28131 Dec '11 - 6:41 
Thanks for the article
I have got a lot of things but can't understand that how to add a curve chart (which is known as
spline chart in Windows Form application)to the WPF window
GeneralMy vote of 5membertan28131 Dec '11 - 6:32 
thanks.I have got lot of things
QuestionErrormemberSoftware200716 Nov '11 - 17:16 
I added simple columnchart like in the sample above, I get the following error:
"Cannot modify the logical children for this node at this time because a tree walk is in progress"
 
Any ideas?
AnswerRe: ErrormemberPriyank Kabaria16 Nov '11 - 18:03 
Hi,
 
I believe error you are facing has to do with DataContext.
You can get detailed description of solution here:

[^]
 
Hope it helps,
Priyank
GeneralRe: ErrormemberSoftware200717 Nov '11 - 13:16 
Thanks, I will read up and try again. By the way, I used the same example as above.
GeneralRe: ErrormemberPriyank Kabaria17 Nov '11 - 13:21 
Okay. I thought you wrote your own code. I'm pretty sure there is no problem with my code. I've received all working reviews till now. Maybe there must be something that's not configured properly. Still, I'll recheck my code.
Thanks !
Priyank
GeneralRe: ErrormemberSoftware200717 Nov '11 - 13:23 
It works if I call showColumnChart()from the constructor of the window, but not from anywhere else, like I can't call it on a button click event, I would get the error message in my original post.
 
Any ideas?
GeneralRe: ErrormemberMember 874695028 Mar '12 - 12:26 
I am having the same issue. I'm trying to refresh the data bound to the graph in real time and it won't let me. I cannot find any means to fix this issue.
GeneralWPF Toolkit Charting Controls (Line, Bar, Area, Pie, Column Series) Demomemberpeirone1 Nov '11 - 6:37 
Thank you for an excellent article, clear and concise. Hopefully future articles can deal with more advanced properties & styling.
GeneralRe: WPF Toolkit Charting Controls (Line, Bar, Area, Pie, Column Series) DemomemberPriyank Kabaria1 Nov '11 - 8:42 
Thank you for your comment ! I certainly have discovered depths of WPF Toolkit and am in process of writing more detailed articles. Currently, I'm in midst of my independent project work and shall post a new article soon as am done with it.
Questiongreat samplememberAndre Suchitra5 Sep '11 - 17:06 
hi priyank,
 
thanks alot for the simple but very helpful sample.
 
May i know whether it is possible to have stacked column chart using WPF charting?
 
thanks!
AnswerRe: great samplememberPriyank Kabaria5 Sep '11 - 17:26 
Hi Andre Suchitra,
 
I tried looking for stacked column chart while I wrote this article, but came across certain blogs that stated that certain versions of toolkit didn't support one. I'm not sure if the current one does but I suggest you check on wpf.codeplex.com.
 
I'll try my best to find out regarding this and reply you accordingly.
 
Thanks for your message !
QuestionGreat demo!memberpatzerFish28 Jul '11 - 10:04 
This is just what I needed to get started with the WPF Toolkit charting controls. Great work!
AnswerRe: Great demo!memberPriyank Kabaria29 Jul '11 - 8:56 
Thanks patzerFish ! I'm glad it helped you !

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 15 May 2011
Article Copyright 2011 by Priyank Kabaria
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid