Silverlight Chart
Silverlight Chart
Corporate Headquarters
ComponentOne LLC
201 South Highland Avenue
3rd Floor
Pittsburgh, PA 15206 ∙ USA
Internet: info@ComponentOne.com
Web site: http://www.componentone.com
Sales
E-mail: sales@componentone.com
Telephone: 1.800.858.2739 or 1.412.681.4343 (Pittsburgh, PA USA Office)
Trademarks
The ComponentOne product name is a trademark and ComponentOne is a registered trademark of ComponentOne LLC. All
other trademarks used herein are the properties of their respective owners.
Warranty
ComponentOne warrants that the original CD (or diskettes) are free from defects in material and workmanship, assuming
normal use, for a period of 90 days from the date of purchase. If a defect occurs during this time, you may return the defective
CD (or disk) to ComponentOne, along with a dated proof of purchase, and ComponentOne will replace it at no charge. After
90 days, you can obtain a replacement for a defective CD (or disk) by sending it and a check for $25 (to cover postage and
handling) to ComponentOne.
Except for the express warranty of the original CD (or disks) set forth here, ComponentOne makes no other warranties, express
or implied. Every attempt has been made to ensure that the information contained in this manual is correct as of the time it was
written. We are not responsible for any errors or omissions. ComponentOne’s liability is limited to the amount you paid for the
product. ComponentOne is not liable for any special, consequential, or other damages for any reason.
iii
Chart View .......................................................................................................................................................... 53
Axes ....................................................................................................................................................... 53
Axes Annotation................................................................................................................................... 61
Data Aggregation ................................................................................................................................................ 65
Data Labels ......................................................................................................................................................... 66
End User Interaction .......................................................................................................................................... 67
Run-Time Chart Editor ...................................................................................................................................... 68
Chart Tab .............................................................................................................................................. 69
Data Tab ............................................................................................................................................... 69
Axes Tab ............................................................................................................................................... 70
Data-Binding ....................................................................................................................................................... 71
Data-Binding to C1.Silverlight.Data ................................................................................................... 72
Data Labels and Tooltips ..................................................................................................................... 74
Advanced Topics ................................................................................................................................................ 77
Animation ............................................................................................................................................. 77
Zooming and Panning.......................................................................................................................... 80
Attaching Elements to Data Points ..................................................................................................... 84
Using XAML ...................................................................................................................................................... 86
Plotting Functions............................................................................................................................................... 88
Using a Code String to Define a Function ......................................................................................... 89
Calculating the Value for Functions ................................................................................................... 89
TrendLines .......................................................................................................................................................... 89
Chart for Silverlight Appearance ....................................................................................................................... 89
XAML Elements .................................................................................................................................. 89
Chart Resource Keys ............................................................................................................................ 90
Chart Themes ....................................................................................................................................... 91
Data Series Color Palette ..................................................................................................................... 99
Visual Effects ...................................................................................................................................... 107
Chart for Silverlight Samples ........................................................................................................................... 112
Chart for Silverlight Task-Based Help ............................................................................................................. 113
Adding a ScrollBar to C1Chart ......................................................................................................... 113
Rotating the Chart Labels in the X-Axis........................................................................................... 114
Creating a Custom Axis Label to Set the Mark at the Middle of the Year .................................... 114
Breaking Chart Lines when the Y-Value is Null .............................................................................. 114
Exporting the Chart Image to the PDF on the Client ...................................................................... 115
Saving the Chart Image as Jpeg or Png ............................................................................................ 115
Adding Data Values to a Pie Chart ................................................................................................... 116
iv
Converting DataSet to DataSeries .................................................................................................... 116
Finding the Default Color Used for the Series ................................................................................. 117
Setting Custom Colors in DataSeries.Loaded Event ....................................................................... 117
Showing Trend Marks in C1Chart .................................................................................................... 118
Placing the Chart Annotations on Top ............................................................................................. 119
Display DataSeries Label as Tooltip on Mouseover in Line Chart ................................................ 119
Showing the X-Values in the Tooltip ................................................................................................ 120
Creating Wrap Around Text Blocks for Large Number of Series ................................................... 121
Creating a Mouse Move Event for Chart with Multiple Lines ....................................................... 121
v
Chart
The C1.Silverlight.Chart assembly contains two main objects: the C1Chart and C1ChartLegend controls.
C1Chart is a powerful charting tool that allows you to display quantitative data in clear and attractive ways.
C1Chart also supports advanced features such as animations and user interactions, including zooming and
panning.
C1ChartLegend is a separate control used to display a chart legend for a given C1Chart control. The legend is
implemented as a separate control to leverage the Silverlight/WPF layout mechanism.
1
Stacking charts offers a simplified approach for representing complex data. Line, area, bar, radar, and plot
charts can be stacked to display more complex data in a smaller space.
Dynamic Graphics
Chart takes advantage of the dynamic graphics available in the Silverlight platform including perspective
and animation.
Silverlight Toolkit Themes Support
In addition to the 12 built-in themes, Chart ships with the most popular Microsoft Silverlight Toolkit
themes including ExpessionDark, ExpressionLight, WhistlerBlue, RainerOrange, ShinyBlue, and
BureauBlack.
2
The chart appears empty since we did not add the data for it yet.
C#
using C1.Silverlight.Chart;
3. Add the following code in the constructor Window1 class to create the Bar chart:
Visual Basic
' Clear previous data
c1Chart1.Data.Children.Clear()
' Add Data
Dim ProductNames As String() = {"Hand Mixer", "Stand Mixer", "Can
Opener", "Toaster", "Blender", "Food Processor", _
"Slow Cooker", "Microwave"}
Dim PriceX As Integer() = {80, 400, 20, 60, 150, 300, _
130, 500}
C#
// Clear previous data
c1Chart1.Data.Children.Clear();
// Add Data
3
string[] ProductNames = { "Hand Mixer", "Stand Mixer", "Can Opener",
"Toaster", "Blender", "Food Processor", "Slow Cooker", "Microwave" };
int[] PriceX = { 80, 400, 20, 60, 150, 300, 130, 500 };
In the next step, Step 3 of 4: Format the Axes (page 4), you’ll learn how to customize the axes
programmatically
In the next step you will add a ChartView object so you can customize the X-Axis.
4
C1Chart1.View.AxisY.Title = New TextBlock(New Run("Kitchen
Electronics"))
C1Chart1.View.AxisX.Title = New TextBlock(New Run("Price"))
C#
// set axes titles
c1Chart1.View.AxisY.Title= new TextBlock() { Text = "Kitchen
Electronics" };
c1Chart1.View.AxisX.Title = new TextBlock() { Text = "Price" };
// financial formatting
c1Chart1.View.AxisX.AnnoFormat = "c";
In the next step, Step 4 of 4: Adjust the Chart’s Appearance (page 6), you’ll learn how to customize the
chart’s appearance programmatically.
5
In the next step you will apply a theme and palette to C1Chart to adjust its appearance.
C#
c1Chart1.Palette = Palette.Module;
c1Chart1.Theme = ChartTheme.Office2007Blue;
6
Congratulations! You've completed the Chart for Silverlight quick start and created a chart application, added
data to the chart, set the axes bounds, formatted the axes annotation, and customized the appearance of the chart.
7
C1Chart1.EndUpdate()
C#
// start update
c1Chart1.BeginUpdate();
// finish update
c1Chart1.EndUpdate();
Tip 2: Use the line or area chart type for large data arrays
The line and area charts provide the best performance when you have a lots of data values.
To get better performance, enable built-in optimization for large data by setting the attached property,
LineAreaOptions.OptimizationRadius. For example:
Visual Basic
LineAreaOptions.SetOptimizationRadius(C1Chart1, 1.0)
C#
LineAreaOptions.SetOptimizationRadius(c1Chart1, 1.0);
It's recommended you use small values 1.0 - 2.0 as radius. A larger value may affect the accuracy of the plot.
Tip 3: Update the appearance and behavior of a plot element using the DataSeries.PlotElementLoaded event
When any plot element (bar,column,pie, etc) is loaded it fires the PlotElementLoaded event. During this event you
have access to the plot element properties as well as to the corresponding data point.
The following code sets the colors of points depending on its y-value. For example:
Visual Basic
' create data arrays
Dim npts As Integer = 100
Dim x(npts - 1) As Double, y(npts - 1) As Double
For ipt As Integer = 0 To npts - 1
x(ipt) = ipt
y(ipt) = Math.Sin(0.1 * ipt)
8
Next
...
C#
// create data arrays
int npts = 100;
double[] x = new double[npts], y = new double[npts];
for (int ipt = 0; ipt < npts; ipt++)
{
x[ipt] = ipt;
y[ipt] = Math.Sin(0.1 * ipt);
}
// normalized y-value(from 0 to 1)
double nval = 0.5*(dp.Value + 1);
9
// fill from blue(-1) to red(+1)
pe.Fill = new SolidColorBrush(
Color.FromRgb((byte)(255 * nval), 0, (byte)(255 * (1-nval))));
}
};
<c1chart:XYDataSeries SymbolSize="16,16"
XValueBinding="{Binding X}" ValueBinding="{Binding Y}">
<c1chart:XYDataSeries.PointLabelTemplate>
<DataTemplate>
<!-- display point index at the center of point symbol -->
<TextBlock
c1chart:PlotElement.LabelAlignment="MiddleCenter"
Text="{Binding PointIndex}" />
</DataTemplate>
</c1chart:XYDataSeries.PointLabelTemplate>
</c1chart:XYDataSeries>
</c1chart:ChartData>
</c1chart:C1Chart.Data>
</c1chart:C1Chart>
The data context of element created from the template is set to the instance of DataPoint class which contains
information about the corresponding data point.
Tip 5: Save chart as image
The following method saves chart image as png-file.
Visual Basic
Sub Using stm = System.IO.File.Create(fileName)
c1Chart1.SaveImage(stm, ImageFormat.Png)
10
End Using
C#
using (var stm = System.IO.File.Create(fileName))
{
c1Chart1.SaveImage(stm, ImageFormat.Png);
}
C#
new PrintDialog().PrintVisual(c1Chart1, "chart");
C#
int nser = 3, npts = 25;
for (int iser = 0; iser < nser; iser++)
{
// create data arrays
11
double[] x = new double[npts], y = new double[npts];
for (int ipt = 0; ipt < npts; ipt++)
{
x[ipt] = ipt;
y[ipt] = (1 + 0.05 * iser) * Math.Sin(0.1 * ipt + 0.1 * iser);
}
// 1st series
c1Chart1.Data.Children[0].ChartType = ChartType.Area;
// 2nd series
c1Chart1.Data.Children[1].ChartType = ChartType.Step;
12
1. Choose the chart type (ChartType property)
C1Chart supports about 30 chart types, including Bar, Column, Line, Area, Pie, Radial, Polar, Candle,
and several others. The best chart type depends largely on the nature of the data, and will be discussed
later.
2. Set up the axes (AxisX and chart.View.AxisY properties)
Setting up the axes typically involves specifying the axis title, major and minor intervals for the tick marks,
content and format for the labels to show next to the tick marks.
3. Add one or more data series (chart.Data.Children collection)
This step involves creating and populating one DataSeries object for each series on the chart, then adding
the object to the chart.Data.Children collection. If your data contains only one numeric value per point
(Y coordinate), use regular DataSeries objects. If the data contains two numeric values per point (X and Y
coordinates), then use XYDataSeries objects instead.
4. Adjust the chart’s appearance using the Theme and Palette properties.
The Theme property allows you to select one of over 10 built-in sets of properties that control the
appearance of the overall chart. The Palette property allows you to select one of over 20 built-in color
palettes used to specify colors for the data series. Together, these two properties provide about 200 options
to create professionally-looking charts with little effort.
Simple Charts
The simplest charts are those in which each data point has a single numeric value associated with it. A typical
example would be a chart showing sales data for different regions, similar to the following chart:
Before we can create any charts, we need to generate the data that will be shown as a chart. Here is some code to
create the data we need.
Note: There is nothing chart-specific in this code, this is just some generic data. We will use this data to create
the Time Series and XY charts as well in the next topics.
13
// Simple class to hold dummy sales data
public class SalesRecord
{
// Properties
public string Region { get; set; }
public string Product { get; set; }
public DateTime Date { get; set; }
public double Revenue { get; set; }
public double Expense { get; set; }
public double Profit { get { return Revenue - Expense; } }
// Constructor 1
public SalesRecord(string region, double revenue, double expense)
{
Region = region;
Revenue = revenue;
Expense = expense;
}
// Constructor 2
public SalesRecord(DateTime month, string product, double revenue,
double expense)
{
Date = month;
Product = product;
Revenue = revenue;
Expense = expense;
}
}
// Return a list with one SalesRecord for each region
List<SalesRecord> GetSalesPerRegionData()
{
var data = new List<SalesRecord>();
Random rnd = new Random(0);
foreach (string region in "North,East,West,South".Split(','))
{
data.Add(new SalesRecord(region, 100 + rnd.Next(1500),
rnd.Next(500)));
}
return data;
}
// Return a list with one SalesRecord for each product,// Over a period
of 12 months
List<SalesRecord> GetSalesPerMonthData()
{
var data = new List<SalesRecord>();
Random rnd = new Random(0);
string[] products = new string[] {"Widgets", "Gadgets", "Sprockets"
};
for (int i = 0; i < 12; i++)
{
foreach (string product in products)
{
data.Add(new SalesRecord(
DateTime.Today.AddMonths(i - 24),
product,
rnd.NextDouble() * 1000 * i,
14
rnd.NextDouble() * 1000 * i));
}
}
return data;
}
}
Note that the SalesData class is public. This is required for data-binding.
We will follow the following four main steps in creating a chart:
Step 1) Choose the chart type:
The following code clears any existing series, then sets the chart type:
public Window1()
{
InitializeComponent();
// Clear current chart
c1Chart.Reset(true);
// Set chart type
c1Chart.ChartType = ChartType.Bar;
}
Step 2) Set up the axes:
We will start by by obtaining references to both axes. In most charts, the horizontal axis (X) displays labels
associated with each point, and the vertical axis (Y) displays the values. The exception is the Bar chart type, which
displays horizontal bars. For this chart type, the labels are displayed on the Y axis and the values on the X:
Next we will assign titles to the axes. The axis titles are UIElement objects rather than simple text. This means you
have complete flexibility over the format of the titles. In fact, you could use complex elements with buttons, tables,
or images for the axis titles. In this case, we will use simple TextBlock elements created by a CreateTextBlock
method described later.
We will also configure the value axis to start at zero, and to display the annotations next to the tick marks using
thousand separators:
// configure label axis
labelAxis.Title = CreateTextBlock("Region", 14, FontWeights.Bold);
Next, we want to display the regions along the label axis. To do this, we will use a Linq statement that retrieves the
Region property for each record. The result is then converted to an array and assigned to the ItemNames property.
15
c1Chart.ChartData.ItemNames = (from r in data select
r.Region).ToArray();
Note how the use of Linq makes the code direct and concise. Things are made even simpler because our sample
data contains only one record per region. In a more realistic scenario, there would be several records per region,
and we would use a more complex Linq statement to group the data per region.
Now we are ready to create the actual DataSeries objects that will be added to the chart. We will create three
series: "Revenue", "Expenses", and "Profit":
16
ChartType.Bar
ChartType.AreaStacked
ChartType.Pie
17
Note: By default the chart displays a legend describing the series. To remove the C1ChartLegend, delete the
following XAML code:
Time-Series Charts
Time-series charts display time along the X-axis. This is a very common type of chart, used to show how values
change as time passes.
Most time-series charts show constant time intervals (yearly, monthly, weekly, daily). In this case, the time-series
chart is essentially identical to a simple value type chart like the one described above. The only difference is that
instead of showing categories along the X axis, the chart will show dates or times. (If the time intervals are not
constant, then the chart becomes an XY chart, described in the next section.)
We will now walk through the creation of some time-series charts.
//Get axes
Axis valueAxis = c1Chart.View.AxisY;
Axis labelAxis = c1Chart.View.AxisX;
if (c1Chart.ChartType == ChartType.Bar)
{
18
valueAxis = _c1Chart.View.AxisX;
labelAxis = _c1Chart.View.AxisY;
}
Next we will assign titles to the axes. The axis titles are UIElement objects rather than simple text. This We will
set up the axis titles using the CreateTextBlock method, the same way we did before. We will also set up the
annotation format, minimum value, and major unit. The only difference is we will use a larger interval for the tick
marks between values:
valueAxis.AutoMin = false;
valueAxis.Min = 0;
Next, we want to display the dates along the label axis. To do this, we will use a Linq statement that retrieves the
distinct Date values in our data records. The result is then converted to an array and assigned to the ItemsSource
property of the label axis.
19
The code starts by building a list of products in the data source. Next, it creates one DataSeries for each product.
The label of the data series is simply the product name. The actual data is obtained by filtering the records that
belong to the current product and retrieving their Revenue property. The result is assigned to the ValuesSource
property of the data series as before.
Step 4) Adjust the chart’s appearance
Once again, we will finish by setting the Theme and Palette properties to quickly configure the chart appearance:
c1Chart.Theme = "Office2007Black"
This concludes the code that generates our time-series charts. You can test it by running it and changing the
ChartType property to Bar, Column, AreaStacked, or Pie to create charts of different types. The result should be
similar to the images below:
ChartType.Column
Note: The AnnoAngle property was set to “30” to make room for the Axis X labels in the images above.
ChartType.Bar
20
Note: The AnnoAngle property was set to “30” to make room for the Axis Y labels in the images above.
ChartType.AreaStacked
Note: The AnnoAngle property was set to “30” to make room for the Axis X labels in the image above.
ChartType.Pie
You would probably never display a time-series chart as a pie. As you can see from the image, the pie chart
completely masks the growth trend that is clearly visible in the other charts.
XY Charts
XY charts (also known as scatter plots) are used to show relationships between variables. Unlike the charts we
introduced so far, in XY charts each point has two numeric values. By plotting one of the values against the X axis
and one against the Y axis, the charts show the effect of one variable on the other.
We will continue our C1Chart tour using the same data we created earlier, but this time we will create XY charts
that show the relationship between revenues from two products. For example, we might want to determine
whether high Widget revenues are linked to high Gadgets revenues (perhaps the products work well together), or
whether high Widget revenues are linked to low Gadgets revenues (perhaps people who buy one of the products
don’t really need the other).
21
To do this, we will follow the same steps as before. The main differences are that this time we will add
XYDataSeries objects to the chart’s Data.Children collection instead of the simpler DataSeries objects. The Linq
statement used to obtain the data is also a little more refined and interesting.
Step 1) Choose the chart type:
The code clears any existing series, then sets the chart type:
public Window1()
{
InitializeComponent();
// Clear current chart
c1Chart.Reset(true);
// Set chart type
c1Chart.ChartType = ChartType.XYPlot;
// get axes
var yAxis = _c1Chart.View.AxisY;
var xAxis = _c1Chart.View.AxisX;
// configure Y axis
yAxis.Title = CreateTextBlock("Widget Revenues", 14,
FontWeights.Bold);
yAxis.AnnoFormat = "#,##0 ";
yAxis.AutoMin = false;
yAxis.Min = 0;
yAxis.MajorUnit = 2000;
yAxis.AnnoAngle = 0;
// configure X axis
xAxis.Title = CreateTextBlock("Gadget Revenues", 14,
FontWeights.Bold);
xAxis.AnnoFormat = "#,##0 ";
xAxis.AutoMin = false;
xAxis.Min = 0;
xAxis.MajorUnit = 2000;
xAxis.AnnoAngle = -90; // rotate annotations
Next, we need to obtain XY pairs that correspond to the total revenues for Widgets and Gadgets at each date. We
can use Linq to obtain this information directly from our data:
22
var dataGrouped = from r in data
group r by r.Date into g
select new
{
Date = g.Key, // group by date
Widgets = (from rp in g // add Widget revenues
where rp.Product == "Widgets"
select g.Sum(p => rp.Revenue)).Single(),
Gadgets = (from rp in g // add Gadget revenues
where rp.Product == "Gadgets"
select g.Sum(p => rp.Revenue)).Single(),
};
The first Linq query starts by grouping the data by Date. Then, for each group it creates a record containing the
Date and the sum of revenues within that date for each of the products we are interested in. The result is a list of
objects with three properties: Date, Widgets, and Gadgets. This type of data grouping and aggregation is a
powerful feature of Linq.
The second Linq query simply sorts the data by Gadget revenue. These are the values that will be plotted on the X
axis, and we want them to be in ascending order. Plotting unsorted values would look fine if we displayed only
symbols (ChartType = XYPlot), but it would look messy if we chose other chart types such as Line or Area.
Once the data has been properly grouped, summarized, and sorted, all we need to do is create one single data
series, and assign one set of values to the ValuesSource property and the to the XValuesSource property:
// populate Y values
ds.ValuesSource = (
from r in dataSorted
select r.Widgets).ToArray();
// populate X values
ds.XValuesSource = (
from r in dataSorted
select r.Gadgets).ToArray();
23
You can test it by running the program and changing the ChartType property to XYPlot, LineSymbols, or Area to
create charts of different types. The result should be similar to the images below:
ChartType.XYPlot
ChartType.LineSymbols
ChartType.Area
24
The most appropriate chart type in this case is the first, an XYPlot. The chart shows a positive correlation between
Gadget and Widget revenues.
This concludes the basic charting topic. You already have the tools you need to create all types of common charts.
Formatting Charts
The previous section introduced the Theme that you can use to select the appearance of your charts quickly and
easily. The Theme and Palette properties offer a long list of built-in options that were carefully developed to
provide great results with little effort from developers.
In most applications, you will choose the combination of settings for the Theme and Palette properties that is
closest to the feel you want for your application, then customize a few items if necessary. Items you may want to
customize include:
1. Axis titles: The axis titles are UIElement objects. You can customize them directly, and with complete
flexibility. The chart samples used in the Common Usage for Basic 2D Charts (page 13) topic uses the
TextElement objects, but you could use many other elements, including panels such as Border and Grid
objects. For more information on axis titles, see Axis Title (page 56).
2. Axis: The chart samples used in the Common Usage for Basic 2D Charts (page 13) topic shows how you
can customize axis scale, annotation angle, and annotation format. All these are accessible through the
Axis object exposed by the AxisX and AxisY properties. For more information on C1Chart’s axis, see
Axes (page 53).
The C1Chart control has the usual Font properties that determine how annotations are displayed along
both axes (FontFamily, FontSize, etc). If you need more control over the appearance of the annotations,
the Axis object also exposes an AnnoTemplate property that can be used to customize annotations even
further.
3. Grid lines: Grid lines are controlled by the Axis properties. There are properties for the major and minor
grid lines (MajorGridStrokeThickness, MajorGridStrokeThickness, MinorGridStrokeThickness,
MinorGridStrokeThickness, and so on). For more information on grid lines, see Axis Grid Lines (page
58).
4. Tick Marks: Tick marks are also controlled by the Axis properties. There are properties for the major and
minor ticks (MajorTickStroke, MajorTickThickness, MinorTickStroke, MinorTickThickness, and so on).
For more information on tick marks, see Axis Tick Marks (page 56).
25
Specialized Charts
The chart types discussed so far have been fairly standard.
There are a few specialized chart types that are slightly different from the ones described so far. These are described
in the following sections.
Financial Charts
C1Chart implements two types of financial chart: Candle and HighLowOpenClose. Both are commonly used to
display variations in stock prices over a period of time.
The difference between common chart types and financial charts is that Candle and HighLowOpenClose charts
require a special type of data series object, the HighLowOpenCloseSeries. In this type of data series, each point
corresponds to a period (typically one day) and contains five values:
Time
Price at the beginning of period (Open)
Price at the end of period (Close)
Minimum price during period (Low)
Maximum price during period (High)
To create financial charts you need to provide all these values. For example, if the values were provided by the
application as collections, then you could use the code below to create the data series:
// Create data series
HighLowOpenCloseSeries ds = new HighLowOpenCloseSeries();
ds.XValuesSource = dates; // Dates are along x-axis
ds.OpenValuesSource = open;
ds.CloseValuesSource = close;
ds.HighValuesSource = hi;
ds.LowValuesSource = lo;
26
ds.OpenValueBinding = new Binding("Open");
ds.CloseValueBinding = new Binding("Close");
ds.HighValueBinding = new Binding("High");
ds.LowValueBinding = new Binding("Low");
Gantt Charts
C1Chart implements Gantt charts, which show tasks organized along time.
Gantt charts use data series objects of type HighLowSeries. Each data series represents a single task, and each task
has a set of start and end values. Simple tasks have one start value and one end value. Tasks that are composed of
multiple sequential sub-tasks have multiple pairs of start and end values.
To demonstrate Gantt charts, let us start by defining a Task object:
class Task
{
public string Name { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public bool IsGroup { get; set; }
public Task(string name, DateTime start, DateTime end, bool isGroup)
{
Name = name;
Start = start;
End = end;
IsGroup = isGroup;
}
}
Next, let us define a method that creates a set of Task objects that will be shown as a Gantt chart:
Task[] GetTasks()
{
return new Task[]
{
new Task("Alpha", new DateTime(2008,1,1), new DateTime(2008,2,15), true),
new Task("Spec", new DateTime(2008,1,1), new DateTime(2008,1,15), false),
new Task("Prototype", new DateTime(2008,1,15), new DateTime(2008,1,31),
false),
new Task("Document", new DateTime(2008,2,1), new DateTime(2008,2,10),
false),
new Task("Test", new DateTime(2008,2,1), new DateTime(2008,2,12), false),
new Task("Setup", new DateTime(2008,2,12), new DateTime(2008,2,15),
false),
27
new Task("Fix bugs", new DateTime(2008,3,1), new DateTime(2008,3,15),
false),
new Task("Ship", new DateTime(2008,3,14), new DateTime(2008,3,15),
false),
};
}
Now that the tasks have been created, we are ready to create the Gantt chart:
private void CreateGanttChart()
{
// Clear current chart
_c1Chart.Reset(true);
// Populate chart
var tasks = GetTasks();
foreach (var task in tasks)
{
// Create one series per task
var ds = new HighLowSeries();
ds.Label = task.Name;
ds.LowValuesSource = new DateTime[] { task.Start };
ds.HighValuesSource = new DateTime[] { task.End };
ds.SymbolSize = new Size(0, task.IsGroup ? 30 : 10);
// Customize Y axis
var ax = _c1Chart.View.AxisY;
ax.Reversed = true;
ax.MajorGridStroke = null;
// Customize X axis
ax = _c1Chart.View.AxisX;
ax.MajorGridStrokeDashes = null;
ax.MajorGridFill = new SolidColorBrush(Color.FromArgb(20, 120, 120, 120));
ax.Min = new DateTime(2008, 1, 1).ToOADate();
}
After clearing the C1Chart and setting the chart type, the code enumerates the tasks and creates one
HighLowSeries for each. In addition to setting the series Label, LowValuesSource and HighValuesSource
properties, the code uses the SymbolSize property to set the height of each bar. In this sample, we define some
tasks as "Group" tasks, and make them taller than regular tasks.
Next, we use a LINQ statement to extract the task names and assign them to the ItemNames property. This causes
C1Chart to display the task names along the Y axis.
Finally, the code customizes the axes. The Y axis is reversed so the first task appears at the top of the chart. The
axes are configured to show vertical grid lines and alternating bands.
The final result looks like this:
28
Chart Types
This section introduces all of the specific chart types available in C1Chart.
Using built-in types is the simplest way to set up the chart's appearance. For example, to set up a stacked bar chart,
specify the corresponding string in the ChartType property:
<c1chart:C1Chart ChartType="BarStacked">
...
</c1chart:C1Chart>
The available chart types are specified by the members of enumeration ChartType.
The list of available built-in chart types is presented in the table below.
Name in gallery
Area
AreaSmoothed
AreaStacked
AreaStacked100pc
Bar
BarStacked
29
BarStacked100pc
Bubble
Candle
Column
ColumnStacked
ColumnStacked100pc
Gantt
HighLowOpenClose
Line
LineSmoothed
LineStacked
LineStacked100pc
LineSymbols
LineSymbolsSmoothed
LineSymbolsStacked
LineSymbolsStacked100pc
Pie
PieDoughnut
PieExploded
PieExplodedDoughnut
PolarLines
PolarLinesSymbols
PolarSymbols
Radar
RadarFilled
RadarSymbols
Step
StepArea
StepSymbols
XYPlot
Area3D
Area3DSmoothed
30
Area3DStacked
Area3DStacked100pc
Bar3D
Bar3DStacked
Bar3DStacked100pc
Pie3D
Pie3DDoughnut
Pie3DExploded
Pie3DExplodedDougnut
Ribbon
Area Charts
An Area chart draws each series as connected points of data, filled below the points. Each series is drawn on top of
the preceding series. The series can be drawn independently or stacked. Chart for Silverlight supports the
following types of Area charts:
AreaSmoothed
AreaStacked
AreaStacked100pc
Area
The following image represents the Area chart when you set the ChartType property to Area:
Area Smoothed
The following image represents the Area Smoothed chart when you set the ChartType property to AreaSmoothed:
31
Area Stacked
The following image represents the Area Stacked chart when you set the ChartType property to AreaStacked:
Bar Charts
Chart for Silverlight supports the following types of Bar charts:
32
Bar
BarStacked
BarStacked100pc
Bar
The following image represents the Bar chart when you set the ChartType property to Bar:
Bar Stacked
The following image represents the Bar Stacked chart when you set the ChartType property to BarStacked:
33
Bubble Charts
The following image represents the Bubble chart when you set ChartType property to Bubble:
<c1chart:C1Chart.Data>
<c1chart:ChartData>
<c1chart:BubbleSeries Values="20 22 19 24 25" SizeValues="1 2 3
2 1" />
<c1chart:BubbleSeries Values="8 12 10 12 15" SizeValues="3 2 1
2 3"/>
</c1chart:ChartData>
</c1chart:C1Chart.Data>
</c1chart:C1Chart>
Financial Charts
C1Chart implements two types of financial chart: Candle and HighLowOpenClose. Both are commonly used to
display variations in stock prices over a period of time.
34
A Candle chart is a special type of HiLoOpenClose chart that is used to show the relationship between the open
and close as well as the high and low. Like, HiLoOpenClose charts, Candle charts use the same price data (time,
high, low, open, and close values) except they include a thick candle-like body that uses the color and size of the
body to reveal additional information about the relationship between the open and close values. For example, long
transparent candles show buying pressure and long filled candles show selling pressure.
The Candle chart is made up of the following elements: candle, wick, and tail. The candle or the body (the solid
bar between the opening and closing values) represents the change in stock price from opening to closing. The thin
lines, wick and tail, above and below the candle depict the high/low range. A hollow candle or transparent candle
indicates a rising stock price (close was higher than open). In a hollow candle, the bottom of the body represents
the opening price and the top of the body represents the closing price. A filled candle indicates a falling stock price
(open was higher than close). In a filled candle the top of the body represents the opening price and the bottom of
the body represents the closing price.
Candle Chart
The following image represents the Candle chart when you set ChartType property to Candle and specifiy the data
values for the XValuesSource, OpenValuesSource, CloseValuesSource, HighValuesSource, and LowValuesSource,
like the following:
<c1chart:C1Chart ChartType="Candle">
<c1chart:C1Chart.Data>
<c1chart:ChartData>
<c1chart:HighLowOpenCloseSeries
XValues="1 2 3 4 5"
HighValues="103 105 107 102 99"
LowValues="100 99 101 98 97"
OpenValues="100 100 105 100 99"
CloseValues="102 103 103 99 98"
/>
</c1chart:ChartData>
</c1chart:C1Chart.Data>
</c1chart:C1Chart>
HighLowOpenClose Chart
The following image represents the HighLowOpenClose chart when you set ChartType property to
HighLowOpenClose and specifiy the data values for the XValuesSource, OpenValuesSource, CloseValuesSource,
HighValuesSource, and LowValuesSource, like the following:
35
<c1chart:C1Chart ChartType="HighLowOpenClose">
<c1chart:C1Chart.Data>
<c1chart:ChartData>
<c1chart:HighLowOpenCloseSeries
XValues="1 2 3 4 5"
HighValues="103 105 107 102 99"
LowValues="100 99 101 98 97"
OpenValues="100 100 105 100 99"
CloseValues="102 103 103 99 98"
/>
</c1chart:ChartData>
</c1chart:C1Chart.Data>
</c1chart:C1Chart>
The difference between common chart types and financial charts is that Candle and HighLowOpenClose charts
require a special type of data series object, the HighLowOpenCloseSeries. In this type of data series, each point
corresponds to a period (typically one day) and contains five values:
Time
Price at the beginning of period (Open)
Price at the end of period (Close)
Minimum price during period (Low)
Maximum price during period (High)
To create financial charts you need to provide all these values.
For example, if the values were provided by the application as collections, then you could use the code below to
create the data series:
// create data series
HighLowOpenCloseSeries ds = new HighLowOpenCloseSeries();
ds.XValuesSource = dates; // dates are along x-axis
ds.OpenValuesSource = open;
ds.CloseValuesSource = close;
ds.HighValuesSource = hi;
ds.LowValuesSource = lo;
36
chart.ChartType = isCandle
? ChartType.Candle
: ChartType.HighLowOpenClose;
Another option is to use data-binding. For example, if the data is available as a collection of StockQuote objects
such as:
public class Quote
{
public DateTime Date { get; set; }
public double Open { get; set; }
public double Close { get; set; }
public double High { get; set; }
public double Low { get; set; }
}
Then the code that creates the data series would be as follows:
// create data series
HighLowOpenCloseSeries ds = new HighLowOpenCloseSeries();
Column Charts
Chart for Silverlight supports the following types of Column charts:
Column
ColumnStacked
ColumnStacked100pc
Column
The following image represents the Column chart when you set the ChartType property to Column:
37
Column Stacked
The following image represents the Column Stacked 100% when you set the ChartType property to
ColumnStackedc:
38
Gantt Charts
Gantt charts use data series objects of type HighLowSeries. Each data series represents a single task, and each task
has a set of start and end values. Simple tasks have one start value and one end value. Tasks that are composed of
multiple sequential sub-tasks have multiple pairs of start and end values.
The following image represents a Gantt chart when the following code is used:
Next, let us define a method that creates a set of Task objects that will be shown as a Gantt chart:
Task[] GetTasks()
{
return new Task[]
{
new Task("Alpha", new DateTime(2008,1,1), new DateTime(2008,2,15),
true),
new Task("Spec", new DateTime(2008,1,1), new DateTime(2008,1,15),
false),
new Task("Prototype", new DateTime(2008,1,15), new
DateTime(2008,1,31), false),
new Task("Document", new DateTime(2008,2,1), new
DateTime(2008,2,10), false),
new Task("Test", new DateTime(2008,2,1), new DateTime(2008,2,12),
false),
39
new Task("Setup", new DateTime(2008,2,12), new DateTime(2008,2,15),
false),
Now that the tasks have been created, we are ready to create the Gantt chart:
private void CreateGanttChart()
{
// clear current chart
c1Chart.Reset(true);
// populate chart
var tasks = GetTasks();
foreach (var task in tasks)
{
// create one series per task
var ds = new HighLowSeries();
ds.Label = task.Name;
ds.LowValuesSource = new DateTime[] { task.Start };
ds.HighValuesSource = new DateTime[] { task.End };
ds.SymbolSize = new Size(0, task.IsGroup ? 30 : 10);
// customize Y axis
var ax = c1Chart.View.AxisY;
ax.Reversed = true;
ax.MajorGridStroke = null;
// customize X axis
ax = c1Chart.View.AxisX;
ax.MajorGridStrokeDashes = null;
ax.MajorGridFill = new SolidColorBrush(Color.FromArgb(20, 120, 120,
120));
ax.Min = new DateTime(2008, 1, 1).ToOADate();
}
40
After clearing the C1Chart and setting the chart type, the code enumerates the tasks and creates one
HighLowSeries for each. In addition to setting the series Label, LowValuesSource and HighValuesSource
properties, the code uses the SymbolSize property to set the height of each bar. In this sample, we define some
tasks as “Group” tasks, and make them taller than regular tasks.
Next, we use a Linq statement to extract the task names and assign them to the ItemNames property. This causes
C1Chart to display the task names along the Y axis.
Finally, the code customizes the axes. The Y axis is reversed so the first task appears at the top of the chart. The
axes are configured to show vertical grid lines and alternating bands.
Line Charts
Chart for Silverlight supports the following types of Line charts:
Line
LineSmoothed
LineStacked
LineStacked100pc
LineSymbols
LineSymbolsSmoothed
LineSymbolsStacked
LineSymbolsStacked100pc
Line
The following image represents the Line chart when you set the ChartType property to Line:
Line Smoothed
The following image represents the Line Smoothed chart when you set the ChartType property to LineSmoothed:
41
Line Stacked
Select the LineStacked member from the ChartType enumeration to create a specific stacking Line chart.. Stacking
charts represent the data by stacking the values for each series on top of the values from the previous series.
The following image represents the Line Stacked chart when you set the ChartType property to LineStacked:
42
Line Symbols
The following image represents the Line Symbols when you set the ChartType property to LineSymbols:
43
Line Symbols Stacked 100%
Select the LineSymbolsStacked100pc member from the ChartType enumeration to create a specific stacking Line
chart. Stacking charts represent the data by stacking the values for each series on top of the values from the
previous series.
The following image represents the Line Stacked 100% chart when you set the ChartType property to
LineSymbolsStacked100pc:
Pie Charts
Pie charts are commonly used to display simple values. They are visually appealing and often displayed with 3D
effects such as shading and rotation.
Pie charts have one significant difference when compared to other C1Chart chart types in Pie charts; each series
represents one slice of the pie. Therefore, you will never have Pie charts with a single series (they would be just
circles). In most cases, Pie charts have multiple series (one per slice) with a single data point in each series.
C1Chart represents series with multiple data points as multiple pies within the chart.
Chart for Silverlight supports the following types of Pie charts:
44
Pie
Dougnut Pie
Exploded Pie
Exploded Doughnut Pie
Pie
The following image represents the Pie chart when you set the ChartType property to Pie:
Doughnut Pie
The following image represents the Doughnut Pie chart when you set the ChartType property to PieDoughnut.
Exploded Pie
The following image represents the Exploded Pie chart when you set ChartType property to PieExploded:
45
Special Pie Chart Properties
Pie charts are quite different from the other chart types since they do not follow the concept of a two-dimensional
grid or axes. Altering the diameter of the pie or the properties of the exploding slices can be accomplished with the
properties of the Pie class.
Starting Angle
Use the PieOptions.StartingAngleAttached property to specify the angle at which the slices for the first series
start. The default angle is 0 degrees. The angle represents the arc between the most clockwise edge of the first slice
and the right horizontal radius of the pie, as measured in the counter-clockwise direction.
Exploding Pies
A slice of a Pie chart can be emphasized by exploding it, which extrudes the slice from the rest of the pie. Use the
Offset property of the series to set the exploded slice's offset from the center of the pie. The offset is measured as a
percentage of the radius of the pie.
46
The following image represents the Polar chart with symbols and lines when you set ChartType property to
PolarLines.
<c1chart:C1Chart Name="c1Chart1" ChartType="PolarLines">
<c1chart:C1Chart.Data>
<c1chart:ChartData>
<c1chart:XYDataSeries Label="Series 1" Values="5 10 5 10 5 10 5 10
5"
XValues="0 45 90 135 180 225 270 315
0"/>
<c1chart:XYDataSeries Label="Series 2" Values="0 2 4 6 8 10 12 14
16"
XValues="0 45 90 135 180 225 270 315
0"/>
</c1chart:ChartData>
</c1chart:C1Chart.Data>
<c1chart:C1ChartLegend/> </c1chart:C1Chart>
47
The following image represents the Polar chart when you set ChartType property to PolarSymbols.
<c1chart:C1Chart Name="c1Chart1" ChartType="PolarSymbols">
<c1chart:C1Chart.Data>
<c1chart:ChartData>
<c1chart:XYDataSeries Label="Series 1" Values="5 10 5 10 5 10 5 10
5"
XValues="0 45 90 135 180 225 270 315
0"/>
<c1chart:XYDataSeries Label="Series 2" Values="0 2 4 6 8 10 12 14
16"
XValues="0 45 90 135 180 225 270 315
0"/>
</c1chart:ChartData>
</c1chart:C1Chart.Data>
<c1chart:C1ChartLegend/> </c1chart:C1Chart>
Radar Charts
A Radar chart is a variation of a Polar chart. A Radar chart draws the y value in each data set along a radar line. If
the data has n unique points, then the chart plane is divided into n equal angle segments, and a radar line is drawn
(representing each point) at n/360 degree increments. By default, the radar line representing the first point is drawn
vertically (at 90 degrees).
The labels for radar chart can be set using ItemNames property. These labels are located at end of each radial line.
The following image represents the Radar chart when you set ChartType property to Radar.
48
The following image represents the Radar chart with symbols when you set ChartType property to RadarSymbols.
The following image represents the filled Radar chart when you set ChartType property to RadarFilled.
49
Step Chart
A Step chart is a form of a XY Plot chart. Step charts are often used when Y values change by discreet amounts, at
specific values of X with a sudden change of value. A simple, everyday example would be a plot of a checkbook
balance with time. As each deposit is made, and each check is written, the balance (Y value) of the check register
changes suddenly, rather than gradually, as time passes (X value). During the time that no deposits are made, or
checks written, the balance (Y value) remains constant as time passes.
Similar to Line and XY plots, the appearance of the step chart can be customized by using the Connection and
Symbol properties for each series by changing colors, symbol size, and line thickness. Symbols can be removed
entirely to emphasize the relationship between points or included to indicate actual data values. If data holes are
present, the step chart behaves as expected, with series lines demonstrating known information up to the X value of
the data hole. Symbols and lines resume once non-hole data is again encountered.
As with most XY style plots, step charts can be stacked when appropriate.
The following image represents the Step chart when you set ChartType property to Step.
The following image represents the Step chart with symbols when you set ChartType property to StepArea.
The following image represents the filled Step chart when you set ChartType property to StepSymbols.
50
XYPlot Chart
The XYPlot is also known as a Scatter plot chart. For more information on the XYPlot chart see XY Charts (page
21).
The following image represents the XYPlot chart when you set ChartType property to XYPlot:
51
The Label property in the DataSeries class represents the label for the Series name in the Chart Legend.
There are several DataSeries classes inherited from the same base class DataSeries, each of them combines several
data sets depending on appropriate data nature. For instance, the XYDataSeries provides two sets of data values
that correspond to x- and y-coordinates. The list of available data series classes is presented in the table below.
Each data series class may have its own default template for plotting, for instance HighLowOpenCloseSeries
displays financial data as a set of lines that mark high, low, open and close values.
52
Chart View
The ChartView object represents the area of the chart that contains data (excluding the titles and legend, but
including the axes). The View property returns a ChartView object with the following main properties:
Property Description
Axes Gets the axis collection. Stores x, y, and z axes. These axes are responsible for
the chart range (minimum, maximum, unit, and linear/logarithmic scale) and the
appearance of the axis lines, grid lines, tick marks and axis labels.
AxisX, AxisY, Each of these properties returns Axis objects that allow you to customize the
ChartView.AxisZ appearance of the chart axes.
ChartView.Margin Returns a Margin object that allows you to specify the distance between the chart
area and the plot area. The axes labels are displayed in this space.
PlotRect Returns a Rect object that controls the appearance of the area inside the axes.
ChartView.Style Contains properties that set the color and border of the chart area.
Axes
The axes are represented by sub-properties of the View property: AxisX and AxisY. Each of these properties
returns an Axis object with the following main properties:
Layout, Style, and Value properties
The following properties below represent the layout and style of the axes in C1Chart:
Property Description
Position Allows you to set the position of the axis. For example, you may want
to display the X-axis above the data instead of below. For more
information see Axis Position (page 56).
Reversed Allows you to reverse the direction of the axis. For example, you can
show Y values going down instead of up. For more information see
Inverted and Reversed Chart Axes (page 60).
Title Sets a string to display next to the axis (this is typically used to
describe the variable and units being depicted by the axis). For more
information see Axis Title (page 56).
AxisLine Gets or sets the axis line. The axis line connects the points on the plot
that correspond to the Min and Max of the axis.
Annotation properties
The following properties below represent the format for the annotation of the axes in C1Chart:
Property Description
53
AnnoFormat A set of predefined formats used to format the values displayed next to
the axis.
AnnoAngle Allows you to rotate the values so they take up less space along the
axis. For more information see Axis Annotation Rotation (page 62).
AutoMin, AutoMax Determine whether the minimum and maximum values for the axis
should be calculated automatically. For more information see Axis
Bounds.
Min, Max Set the minimum and maximum values for the axis (when AutoMin and
AutoMax are set to False). For more information see Axis Bounds (page
58).
MajorUnit, MinorUnit Set the spacing between the major and minor tickmarks (when the
AutoMajor and AutoMinor properties are set to False).
MajorGridFill Gets or sets the fill based of the major grid. The MajorGridFill enables
you to create a striped plot appearance.
MajorGridStrokeDashes, Gets or sets the dash pattern of the major/minor grid lines.
MinorGridStrokeDashes
Axis Lines
The axis lines are lines that appear horizontally from the starting value to the ending value for the Y-Axis and
vertically from the starting value to the ending value for the X-Axis.
You can use either the Axis.Foreground or the ShapeStyle.Stroke property to apply color to the axis line. Note
that the Axis.Foreground property overrides the ShapeStyle.Stroke property.
Property Description
54
Stroke Gets or sets the stroke brush of the shape.
Dependent Axis
The IsDependent allows to link the auxiliary axis with one from the main axes(AxisX or AxisY, depending on
AxisType). The dependent axis always has the same minimum and maximum as the main axis.
New property DependentAxisConverter and delegate Axis.AxisConverter specifies function that is used to convert
coordinate from main axis to the dependent axis.
The following code creates a depepdent Y-Axis:
c1Chart1.Reset(true);
c1Chart1.Data.Children.Add(
new DataSeries() { ValuesSource = new double[] { -10, 0, 10,
20, 30, 40 } });
c1Chart1.ChartType = ChartType.LineSymbols;
c1Chart1.View.Axes.Add(axis);
The following image displays the dependent (leftmost) Y-Axis that shows values in Fahrenheits corresponding to
the Celsius on the main Y-axis:
55
Axis Position
You can specify the axis position by setting the Position property to near or far values. For vertical axis
Axis.Position.Near corresponds to the left and Axis.Position.Far corresponds to the right. For horizontal axis
Axis.Position.Near corresponds to bottom and Axis.Position.Far corresponds to the top.
Axis Title
Adding a title to an axis clarifies what is charted along that axis. For example if your data includes measurements
its helpful to include the unit of measurement (grams, meters, liters, etc) in the axis title. Axis titles can be added to
Area, XY-Plot, Bar, HiLoOpenClose or Candle charts.
The axis titles are UIElement objects rather than simple text. This means you have complete flexibility over the
format of the titles. In fact, you could use complex elements with buttons, tables, or images for the axis titles.
To set the Axis Title programmatically
// Set axes titles
c1Chart1.View.AxisY.Title= new TextBlock() { Text = "Kitchen
Electronics" };
c1Chart1.View.AxisX.Title = new TextBlock() { Text = "Price" };
56
whole tick is inside the plot area. As you increase the MajorTickOverlap value for the X-Axis, the tick mark moves
up and down as you descrease the value. As you increase the MajorTickOverlap value for the Y-Axis the tick mark
moves to the left.
c1Chart1.Reset(true);
c1Chart1.Data.Children.Add(
new DataSeries() { ValuesSource = new double[] { 1, 2, 1, 2 } });
c1Chart1.ChartType = ChartType.LineSymbols;
c1Chart1.View.AxisX.MajorGridStrokeThickness = 0;
c1Chart1.View.AxisX.MajorTickThickness = 3;
c1Chart1.View.AxisX.MajorTickHeight = 10;
c1Chart1.View.AxisX.MajorTickOverlap = 0;
c1Chart1.View.AxisY.MajorGridStrokeThickness = 0;
c1Chart1.View.AxisY.MajorTickThickness = 3;
c1Chart1.View.AxisY.MajorTickHeight = 10;
c1Chart1.View.AxisY.MajorTickOverlap = 0;
c1Chart1.Data.Children.Add(
new DataSeries() { ValuesSource = new double[] { 1, 2, 1, 2 } });
c1Chart1.ChartType = ChartType.LineSymbols;
c1Chart1.View.AxisX.MinorGridStrokeThickness = 0;
c1Chart1.View.AxisX.MinorTickThickness = 3;
c1Chart1.View.AxisX.MinorTickHeight = 10;
57
c1Chart1.View.AxisX.MinorTickOverlap = .5;
c1Chart1.View.AxisY.MinorGridStrokeThickness = 0;
c1Chart1.View.AxisY.MinorTickThickness = 3;
c1Chart1.View.AxisY.MinorTickHeight = 10;
c1Chart1.View.AxisY.MinorTickOverlap = 1;
Axis Bounds
Normally a graph displays all of the data it contains. However, a specific part of the chart can be displayed by
fixing the axis bounds.
58
The chart determines the extent of each axis by considering the lowest and highest data value and the numbering
increment. Setting the Min and Max, AutoMin, and AutoMax properties allows the customization of this process.
Axis Min and Max
Use the Min and Max properties to frame a chart at specific axis values. If the chart has X-axis values ranging from
0 to 100, then setting Min to 0 and Max to 10 will only display the values up to 10.
The chart can also calculate the Min and Max values automatically. If the AutoMax and AutoMin properties are
set to True then the chart automatically formats the axis numbering to fit the current data set.
Axis Scrolling
In circumstances when you have a substantial amount of X-values or Y-values in your chart data, you can add a
scrollbar to the axes. Adding a scrollbar can make the data on the chart easier to read by scrolling through it so you
can closely view pieces of data one at a time. The following image has the ScrollBar set to the View.AxisX.Value
property.
A scrollbar can appear on the X-Axis or Y-Axis simply by setting the ScrollBar’s Value property to AxisX for the
X-Axis or AxisY for the Y-Axis.
The following XAML code shows how to assign a horizontal scrollbar to the X-Axis:
Setting the Minimum and Maximum values for the Scrollbar will prevent the scrollbar from changing the Axis
values when you are scrolling.
59
Inverted and Reversed Chart Axes
When a data set contains X or Y values which span a large range, sometimes the normal chart setup does not
display the information most effectively. Formatting a chart with a vertical Y-axis and axis annotation that begins
at the minimum value can sometimes be more visually appealing if the chart could be inverted or the axes reversed.
Therefore, C1Chart provides the Inverted property and the Reversed property of the axis.
Setting the Reversed property of the ChartView to True will reverse the axes. This means that the Max side of the
axis will take the place of the Min side of the axis, and the Min side of the axis will take the place of the Max side
of the axis. Initially, the chart displays the Minimum value on the left side of the X-axis, and on the bottom side of
the Y-axis. Setting the Reversed property of the Axis, however will juxtapose these Maximum and Minimum
values.
Multiple Axes
Multiple axes are commonly used when you have the following:
Two or more Data Series that have mixed types of data which make the scales very different
Wide range of data values that vary from Data Series to Data Series
The following chart uses five axes to effectively display the length and temperature in both metric and non-metric
measurements:
You can add multiple axes to the chart by adding a new Axis object and then specifying its type (X, Y, or Z) for the
Axis.AxisType property.
The following XAML code shows how to add multiple Y-axes to the chart:
<c1chart:C1Chart Margin="0" Name="c1Chart1">
<c1chart:C1Chart.View>
<c1chart:ChartView>
<!-- Auxiliary y-axes -->
<c1chart:Axis Name="ay2" AxisType="Y" Position="Far" Min="0"
Max="10" />
<c1chart:Axis Name="ay3" AxisType="Y" Position="Far" Min="0"
Max="20" />
<c1chart:Axis Name="ay4" AxisType="Y" Position="Far" Min="0"
Max="50" />
</c1chart:ChartView>
60
</c1chart:C1Chart.View>
<c1chart:C1Chart.Data>
<c1chart:ChartData>
<c1chart:DataSeries Values="1 2 3 4 5" />
<c1chart:DataSeries AxisY="ay2" Values="1 2 3 4 5" />
<c1chart:DataSeries AxisY="ay3" Values="1 2 3 4 5" />
<c1chart:DataSeries AxisY="ay4" Values="1 2 3 4 5" />
</c1chart:ChartData>
</c1chart:C1Chart.Data>
</c1chart:C1Chart>
Axes Annotation
The annotation along each axis is an important part of any chart. The chart annotates the axes with numbers based
on the data/values entered into the BubbleSeries, DataSeries, HighLowOpenCloseSeries, HighLowSeries, or
XYDataSeries objects. Annotation for the Axes will always display basic text without any formatting applied to
them.
The chart automatically produces the most natural annotation possible, even as chart data changes. The following
Annotation properties can be modified to perfect this process:
Property Description
AnnoFormat A set of predefined formats used to format the values displayed next to the
axis.
AnnoAngle Gets or sets the rotation angle of axis annotation. This allows you to rotate
the values so they will take up less space along the axis.
AnnoTemplate Gets or sets the template for the axis annotation. This is useful for building
custom annotations.
61
XAML
<c1chart:C1Chart.View>
<c1chart:ChartView>
<c1chart:ChartView.AxisX>
<c1chart:Axis Min="0" AnnoFormat="c"
AutoMin="false" AutoMax="false" Max="200" />
</c1chart:ChartView.AxisX>
</c1chart:ChartView>
</c1chart:C1Chart.View>
C#
// Financial formatting
c1Chart1.View.AxisX.AnnoFormat = "c";
c1Chart1.View.AxisX.Min = 0;
62
XAML
<c1chart:C1Chart.View>
<c1chart:ChartView>
<c1chart:ChartView.AxisX>
<c1chart:Axis Min="0" MajorUnit="10"
AnnoFormat="c" AutoMin="false" AutoMax="false" Max="200" AnnoAngle="60"
/>
</c1chart:ChartView.AxisX>
</c1chart:ChartView>
</c1chart:C1Chart.View>
C#
// Financial formatting
c1Chart1.View.AxisX.AnnoFormat = "c";
c1Chart1.View.AxisX.Min = 0;
c1Chart1.View.AxisX.AnnoAngle = "60";
c1Chart1.Data.Children.Add(
new DataSeries() { ValuesSource = new double[] { 1, 2, 1, 3, 1,
4 } });
c1Chart1.ChartType = ChartType.LineSymbols;
Here is what the chart appears like after adding the preceding code:
63
When the ItemsSource property is a collection of KeyValuePair<object, double> or KeyValuePair<object,
DateTime> the chart creates axis label based on the provided pairs of values. For example, the following
code uses the KeyValuePair to create the custom axis annotation for the Y axis:
c1Chart1.Reset(true);
c1Chart1.Data.Children.Add(
new DataSeries() { ValuesSource = new double[] { 1, 2, 1, 3, 1,
4 } });
c1Chart1.ChartType = ChartType.LineSymbols;
c1Chart1.View.AxisY.ItemsSource = new
List<KeyValuePair<object,double>>
{ new KeyValuePair<object,double>("Min=1", 1),
new KeyValuePair<object,double>("Average=2.5", 2.5),
new KeyValuePair<object,double>("Max=4", 4)};
Here is what the chart appears like after adding the preceding code:
64
You can use the ItemsValueBinding and ItemsLabelBinding properties to create axis labels using arbitrary
collection as data source, like in the following code:
c1Chart1.Reset(true);
Point[] pts = new Point[] { new Point(1, 1.3), new Point(2, 2.7),
new Point(3, 3.9) };
c1Chart1.DataContext = pts;
c1Chart1.ChartType = ChartType.LineSymbols;
c1Chart1.View.AxisY.ItemsSource = pts;
c1Chart1.View.AxisY.ItemsValueBinding = new Binding("Y");
c1Chart1.View.AxisY.ItemsLabelBinding = new Binding();
Here is what the chart appears like after adding the preceding code:
Data Aggregation
Data aggregation can be used on the entire C1Chart control through the Aggregate property or used on individual
series through the Aggregate property.
Data aggregation is when data is gathered and is reflected in a summary form. Commonly, aggregation is used to
collect more information about specific groups based on certain variables such as geographic location, income, and
age.
C1Chart enables you to use aggregate functions for a grouped data by specifying it when the DataSeries is created.
For each DataSeries you can choose from one of the following functions using the Aggregate enumeration:
65
Minimum Gets the minimum value for each point.
Variance Gets the variance of the values for each point (sample).
VariancePop Gets the variance of the values for each point (population).
StandardDeviation Gets the standard deviation of the values for each point (sample).
StandardDeviationPop Gets the standard deviation of the values for each point (population).
Data Labels
Data labels are labels associated with data points on the chart. They can be useful on some charts by making it
easier to see which series a particular point belongs to, or its exact value.
C1Chart supports data labels. Each data series has a PointLabelTemplate property that specifies the visual element
that should be displayed next to each point. The PointLabelTemplate is usually defined as a XAML resource, and
may be assigned to the chart from XAML or from code.
You can add a DataTemplate to determine both visual aspects of how the data is presented and how data binding
accesses the presented data.
To define the PointLabelTemplate as a XAML resource you can create a Resource Dictionary, add the
DataTemplate resource to your Resource Dictionary and then in your Window.xaml file you can access the
DataTemplate resource.
To add a new resource dictionary:
1. In Solution Explorer, right-click your project, point to Add, and then select Resource Dictionary. The Add
New Item dialog box appears.
2. In the Name text box, name the dictionary Resources.xaml and click the Add button.
3. Resources.xaml is added to the project and opens in the code editor.
To create a label you need to create the label template and assign the PointLabelTemplate to the template.
When rendering the plot for each data point the label is created based on the specified template. The DataContext
property of the label is set to the current DataPoint instance that provides information about the point. When
using data binding it makes it easier to display this information in the label.
Here is the sample of a label template that displays the value of the point.
<DataTemplate x:Key="lbl">
<TextBlock Text="{Binding Path=Value}" />
</DataTemplate>
After you define a resource, you can reference the resource to be used for a property value by using a resource
markup extension syntax that specifies the key name
To assign the template to the data series set the PointLabelTemplate property to the following:
Since it is a standard data template, the complex label can be built, for example, the next sample template defines
the data label for the XY chart which shows both coordinates of the data point.
66
It uses the standard grid with two columns and two rows as a container. The x-value of the point is obtained with
indexer of the DataPoint class. The indexer allows getting the values for the data series classes which support
several data sets, such as XYDataSeries class.
<DataTemplate x:Key="lbl">
<!-- Grid 2x2 with black border -->
<Border BorderBrush="Black">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<!-- x-coordinate -->
<TextBlock Text="X=" />
<TextBlock Grid.Column="1" Text="{Binding Path=[XValues]}" />
<!-- y-coordinate -->
<TextBlock Grid.Row="1" Text="Y=" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding
Path=Value}" />
</Grid>
</Border>
</DataTemplate>
When displaying the numerical data value often it is necessary to format the output value. With the static class
Format you can specify standard .Net format string inside the XAML code. For example, the sample code uses
converter to format percentage value.
<DataTemplate x:Key="lbl1">
<TextBlock Text="{Binding Path=PercentageSeries,
Converter={x:Static c1chart:Converters.Format},
ConverterParameter=#.#%}"/>
</DataTemplate>
Note: The zoom is not applicable for the chart's axis if the MinScale property is equal to 1.0. The MinScale
property specifies the minimum scale that can be set for the axis.
Translate action provides the opportunity to scroll through the plot area. The TranslateAction class
represents the translate action.
67
Note: You will not be available to translate along the axis if the Axis.Scale property is equal to 1.
Zoom action allows the user to select rectangular area for viewing.
The scaling, translation and zooming are available only for chart with Cartesian axes.
The Action object provides a set of properties that help to customize the action's behavior.
The MouseButton and Modifiers properties specify the mouse button and key (ALT, CONTROL or
SHIFT) combination that will invoke the execution of the action.
The following topics provide a visual detail of the Chart Editor interface and explain the functionality of each
element in the Chart Editor.
68
Chart Tab
In the Chart tab you can choose from one of many chart types and then you customize the chart’s appearance by
choosing a theme, palette, foreground color, backround color, and legend.
Data Tab
In the Data tab you can add and remove point labels and point tooltips to C1Chart. To add point labels and/or
point tooltips click the associated Add button. To remove point labels and/or point tooltips click the associated
Remove button.
Once a point label has been added you can change the value of its text, alignment, and offset.
69
Axes Tab
You can select Axes tab to modify or create the format style, scale, and annotation of the axes.
The screen shot below represents the tab name for the selected Axis, in this example it is Axis X.
70
Data-Binding
This section describes data binding.
The steps required to create data bound charts are identical to the ones we mentioned in the earlier topics
1. Choose the chart type (ChartType property).
2. Set up the axes (AxisX and AxisY properties).
3. Add one or more data series (Children collection).
4. Adjust the chart's appearance using the Theme and Palette properties.
The only difference is in step 3. When you create data-bound charts, you need to set the ItemsSource
property to the collection of items that contain the data you want to chart. Then, use the
dataSeries.ValueBinding property to specify which property of the items contains the values to be plotted.
For example, here is the code we used before to generate the Sales Per Region chart (not data-bound):
// Get the data
var data = GetSalesPerRegionData();
71
ds.Label = "Revenue";
ds.ValuesSource = (from r in data select r.Revenue).ToArray();
_c1Chart.Data.Children.Add(ds);
// Add Expense series
ds = new DataSeries();
ds.Label = "Expense";
ds.ValuesSource = (from r in data select r.Expense).ToArray();
_c1Chart.Data.Children.Add(ds);
// Add Profit series
ds = new DataSeries();
ds.Label = "Profit";
ds.ValuesSource = (from r in data select r.Profit).ToArray();
_c1Chart.Data.Children.Add(ds);
Here is the data-bound version of the code (changes are highlighted). The result is identical:
// Get the data
var data = GetSalesPerRegionData();
_c1Chart.Data.ItemsSource = data;
Data-Binding to C1.Silverlight.Data
C1.Silverlight.Data is an assembly that contains a subset of the data objects in ADO.NET built for the Silverlight
platform (DataSet, DataTable, DataView, and so on). It allows you to re-use your ADO.NET data and logic in
Silverlight applications, and integrates with LINQ and modern data-binding mechanisms as shown below.
Creating charts from DataTable objects is easy. The first step is obtaining the data from the server. Loading a
DataSet from a database or file is discussed in detail in the C1.Silverlight.Data documentation. The code below
shows one easy way to load a DataSet from an XML file:
public Page()
{
InitializeComponent();
// Other initialization
// ...
72
}
// Get axes
Axis valueAxis = _c1Chart.View.AxisY;
Axis labelAxis = _c1Chart.View.AxisX;
if (chartType == ChartType.Bar)
{
valueAxis = _c1Chart.View.AxisX;
labelAxis = _c1Chart.View.AxisY;
}
73
_c1Chart.Data.Children.Add(ds);
}
The new code gets the data by retrieving the default view for the products table. It then applies a filter to show only
products with prices over $35 per unit, and sorts the products by unit price.
This is the result:
BuildProductPriceChart( BuildProductPriceChart(
ChartType.Bar) ChartType.LineSymbols)
Alternatively, you could use LINQ to sort and filter the data in the DataTable:
// Get the data
//DataView dv = _dataSet.Tables["Products"].DefaultView;
//dv.RowFilter = "UnitPrice >= 35";
//dv.Sort = "UnitPrice DESC";
//_c1Chart.Data.ItemsSource = dv;
_c1Chart.Data.ItemsSource =
(
from dr
in _dataSet.Tables["Products"].Rows
where (decimal)dr["UnitPrice"] >= 35
orderby dr["UnitPrice"] descending
select dr.GetRowView()
).ToList();
The result is exactly the same as before. The difference between the two approaches is that the DataView object
maintains a live connection to the underlying data. If the unit price of a product changed, the DataView would be
automatically updated to reflect the new value and possibly filter the changed product in or out of view. The LINQ
query, on the other hand, is converted into a static list and does not change.
74
C1Chart supports data labels. Each data series has a PointLabelTemplate property that specifies the visual element
that should be displayed next to each point. The PointLabelTemplate is usually defined as a XAML resource, and
may be assigned to the chart from XAML or from code.
Going back to our previous example, let us add a simple label to each of the three data series. The first step would
be to define the template as a resource in the MainPage.xaml file:
<UserControl x:Class="ChartIntro.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c1chart="clr-
namespace:C1.Silverlight.Chart;assembly=C1.Silverlight.Chart">
75
You are not limited to showing a single value in each data label. C1Chart provides a DataPointConverter class
that you can use to create more sophisticated bindings for your label templates. The converter is declared and used
as a resource, along with the template.
For example, here is a revised version of the resource in the XAML file:
<UserControl x:Class="ChartIntro.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c1chart="clr-
namespace:C1.Silverlight.Chart;assembly=C1.Silverlight.Chart">
ConverterParameter='{#SeriesLabel}{#NewLine}{#Value:$#,##0.00}'}"
Foreground="Black" FontSize="16"/>
</Border>
</DataTemplate>
</UserControl.Resources>
76
label is bound to. The sample uses the #SeriesLabel, #NewLine, and #Value keywords. Other valid keywords are
#YValue, #PointIndex, and #SeriesIndex.
The parameter also supports the usual .NET formatting syntax. The sample formats values as currencies with a
currency symbol, thousand separators, and two decimals.
This is what the chart looks like after changing the template:
Advanced Topics
The following advanced topics detail using animations, zooming and panning, specialized charts, and XAML.
Animation
Each DataSeries in a chart is composed of PlotElement objects that represent each individual symbol, connector,
area, pie slice, and so on in the series. The specific type of PlotElement depends on the chart type.
You can add animations to your charts by attaching Storyboard objects to the plot elements. This is usually done
in response to the DataSeries.Loaded event, which fires after the PlotElement objects have been created and
added to the data series.
OnLoad Animations
For example, the code below creates a 'fade-in' animation that causes each point in the data series to slowly appear,
building the chart gradually:
void AnimateChart()
{
// Build chart as usual
SalesPerRegionAreaStacked_Click(this, null);
77
The code starts by generating a chart as usual, and then loops through the DataSeries setting their Opacity to zero.
This way, the chart will appear blank when it loads.
The code also attaches a handler to the Loaded event. This is where the animations will be added to each
PlotElement. Here is the implementation:
// Animate each PlotElement after it has been loaded
void ds_Loaded(object sender, EventArgs e)
{
PlotElement plotElement = sender as PlotElement;
if (plotElement != null)
{
// Create storyboard to animate PlotElement
Storyboard sb = new Storyboard();
Storyboard.SetTarget(sb, plotElement);
// Start storyboard
sb.Begin();
}
}
This event handler gets called once for each PlotElement that is generated. The code creates a Storyboard object
for each PlotElement and uses it to gradually change the opacity of the element from zero to one (completely
transparent to completely solid).
Notice how the code uses the DataPoint property to determine which series and which data point the plot element
belongs to, and then sets the BeginTime property of the animation to cause each plot element to become visible at
different times. This way, the points appear one at a time, instead of all at once.
Notice also that the code tests the PointIndex property to make sure it is greater than -1. This is because some plot
elements do not correspond to individual points, but rather to the whole series. This is the case for Area elements
for example.
This code can be used for all chart types. You can use it to slowly show plot symbols, lines, pie slices, and so on.
OnMouseOver Animations
You can also create animations that execute when the user moves the mouse over elements. To do this, use the
Loaded event as before, but this time attach event handlers to each PlotElement's mouse event instead of creating
the animations directly.
For example:
void AnimatePoints()
78
{
// Build chart as usual
SalesPerMonthLineAndSymbol_Click(this, null);
79
da.To = scale;
da.Duration = new Duration(TimeSpan.FromSeconds(duration));
da.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath(prop));
sb.Children.Add(da);
}
// Start animation
sb.Begin();
}
<!-- Range slider (selects a range from the zoom chart) -->
<c1:C1RangeSlider x:Name="_slider" Grid.Row="1"
VerticalAlignment="Bottom"
Minimum="0" Maximum="1" ValueChange="0.1"
LowerValueChanged="_slider_ValueChanged"
UpperValueChanged="_slider_ValueChanged" />
</Grid>
</UserControl>
The XAML creates the controls and specifies two event handlers. The first event handler, ZoomChart_Loaded, is
invoked when the page loads, and is responsible for initializing the charts:
// Draw main and zoom charts when the control loads
void ZoomChart_Loaded(object sender, RoutedEventArgs e)
80
{
DrawChart(_c1MainChart);
DrawChart(_c1ZoomChart);
}
81
If you run the application now, you will see that it works correctly, but the range slider is aligned with the chart
edges. We would like to align it with the edges of the plot area instead, so the relationship between the slider and
the x axis is obvious to the user. Here is the code that aligns the range slider to the x axis:
// Set slider size to match the length of the x axis
protected override Size MeasureOverride(Size availableSize)
{
Size sz = base.MeasureOverride(availableSize);
_slider.Width = _c1MainChart.View.PlotRect.Width;
return sz;
}
The code overrides the MeasureOverride method to set the width of the slider to match the width of the chart's
plot rectangle (exposed by the PlotRect property).
If you run the project now, the result should look similar to the image below:
You can use the range slider below the bottom chart to select the range you are interested in. For example, if you
dragged the slider's lower value to 55 and the upper value to 65, the upper chart would show the detail as in the
image below:
82
You could improve this application by changing the template used by the range slider control. This is
demonstrated in the "StockPortfolio" sample included with the ComponentOne Studio for Silverlight.
83
All built-in actions work by automatically setting the Scale property on each axis. You can limit or disable the
actions by setting the MinScale property to one for either axis.
84
for (int i = 0; i < values.Length; i++)
{
if (values[i] > ymax)
{
ymax = values[i];
imax = i;
}
if (values[i] < ymin)
{
ymin = values[i];
imin = i;
}
}
}
The red marker is positioned over the maximum value and the blue over the minimum. The position of the
markers is updated automatically when the chart is resized.
85
Using XAML
In this document, we have created several charts using C# code. But you can also create charts entirely in XAML
and using Blend or Visual Studio. The advantage of doing this is you can create charts interactively and see the
effect of each change immediately.
To show how this works, open a project that contains a reference to the C1.Silverlight.Chart assembly and add
new Silverlight user control named "XamlChart" to the project. Then open the XAML file in Visual Studio or
Blend and copy or type the following content into it:
<UserControl x:Class="ChartIntro.XamlChart"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c1chart="clr-
namespace:C1.Silverlight.Chart;assembly=C1.Silverlight.Chart"
xmlns:c1="clr-namespace:C1.Silverlight;assembly=C1.Silverlight"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
</Grid>
</UserControl>
If you edit this code in Visual Studio's split window, you will be able to see the effect of each change you make as
you type it. This makes it easy to experiment with different settings to get the results you want.
Notice that you can edit most chart elements directly in XAML, including the data series and the axes.
The image below shows the interactive editing process within Visual Studio:
86
This is a convenient way to get the chart set up. At run time, you would use code to provide the actual chart data
by setting the ItemNames and ValuesSource property on each data series as we did in earlier examples. For
example:
public XamlChart()
{
// Initialize control
InitializeComponent();
87
}
Random _rnd = new Random();
double[] GetSeriesData(int count)
{
double[] values = new double[count];
for (int i = 0; i < count; i++)
{
values[i] = _rnd.Next(0, 5);
}
return values;
}
The code replaces the dummy data we used at design time the actual data. The final result is shown below:
Plotting Functions
C1Chart has a built-in engine for plotting functions. To use the built-in engine for plotting functions it is necessary
to add a reference to the C1.Silverlight.Chart.Extended.dll in your project.
There are various types of functions used for different applications. C1Chart provides the various types of
functions needed to create many applications.
There are two types of supported functions:
1. One-variable explicit functions
One-variable explicit functions are written as y=f(x) (see the YFunctionSeries class).
A few examples include: rational, linear, polynomial, quadratic, logarithmic, and exponential
functions.
Commonly used by scientists and engineers, these functions can be used in many different types of
finance, forecasts, performance measurement applications, and so on.
2. Parametric functions
The function is defined by a pair of equations, such as y=f1(t) and x=f2(t) where t is the
variable/coordinate for functions f1 and f2.
Parametric functions are special types of function because the x and y coordinates are defined by
individual functions of a separate variable.
88
They are used to represent various situations in mathematics and engineering, from heat transfer, fluid
mechanics, electromagnetic theory, planetary motion and aspects of the theory of relativity, to name a
few.
For more information about the parametric function (see the ParametricFunctionSeries class).
TrendLines
The trend lines supported by chart with TrendLine objects can be divided into two groups, including regression
and non-regression. In 2D charts, trend lines are typically used in X-Y line, bar, or scatter charts.
Non-regression trendlines are MovingAverage, Average, Minimum, and Maximum. Moving Average trendline is
the average over the specified time.
Regression trend lines are polynomial, exponent, logarithmic, power and Fourier functions that approximate the
data which the functions trend.
To use the trend lines feature, it is necessary to add the reference to the C1.Silverlight.C1Chart.Extended.dll in
your project.
XAML Elements
Several auxiliary XAML elements are installed with ComponentOne Chart for Silverlight. These elements
include templates and themes and are located in the Chart for Silverlight installation directory, by default
C:\Program Files\ComponentOne\Studio for Silverlight\Help\C1.Silverlight.Chart. You can incorporate
these elements into your project, for example, to create your own theme based on the included Office 2007 themes.
For more information about the built-in themes some of these elements represent, see Chart Themes (page 91).
Included Auxiliary XAML Elements
The following auxiliary XAML elements are included with Chart for Silverlight with their location within the
C:\Program Files\ComponentOne\Studio for Silverlight\Help\C1.Silverlight.Chart folder noted:
DuskBlue.xaml ThemesSL Specifies the templates for the Dusk Blue theme.
89
DuskGreen.xaml ThemesSL Specifies the templates for the Dusk Green theme.
generic.xaml Themes Specifies the templates for different styles and the
initial style of the chart.
Office2003Blue.xaml ThemesSL Specifies the templates for the Office 2003 Blue
theme.
Office2003Classic.xaml ThemesSL Specifies the templates for the Office 2003 Classic
theme.
Office2003Olive.xaml ThemesSL Specifies the templates for the Office 2007 Olive
theme.
Office2003Royale.xaml ThemesSL Specifies the templates for the Office 2007 Royal
theme.
Office2003Silver.xaml ThemesSL Specifies the templates for the Office 2007 Silver
theme.
Office2007Black.xaml ThemesSL Specifies the templates for the Office 2007 Black
theme.
Office2007Blue.xaml ThemesSL Specifies the templates for the Office 2007 Blue
theme.
Office2007Silver.xaml ThemesSL Specifies the templates for the Office 2007 Silver
theme.
90
C1Chart_Margin Represents C1Chart's margin.
C1Chart_LegendBorder_Thickness Represents the Legend border's thickness (all 4 edges) for the
C1Chart control.
Axis Keys
Resource Key Description
Chart Themes
ComponentOne Chart for Silverlight incorporates several themes, including Office 2003 Vista, and Office 2007
themes, that allow you to customize the appearance of your chart. The built-in themes are described and pictured
below:
Office2007Black Theme
This is the default theme based on the Office 2007 Black style and it appears as a dark gray-colored chart with
orange highlighting.
91
In XAML
To specifically define the Office2007Black theme in your chart add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="Office2007Black”>
In Code
To specifically define the Office2007Black theme in your chart, add the following code your project:
Visual Basic
C1Chart1.Theme = ChartTheme.Office2007Black
C#
c1Chart1.Theme = ChartTheme.Office2007Black;
Office2007Blue Theme
This theme is based on the Office 2007 Blue style and it appears as a blue-colored chart with orange highlighting.
In XAML
To specifically define the Office2007Blue theme in your chart, add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="Office2007Blue">
In Code
To specifically define the Office2007Blue theme in your chart, add the following code your project:
92
Visual Basic
C1Chart1.Theme = ChartTheme.Office2007Blue
C#
C1Chart1.Theme = ChartTheme.Office2007Blue;
Office2007Silver Theme
This theme is based on the Office 2007 Silver style and it appears as a silver-colored chart with orange highlighting.
In XAML
To specifically define the Office2007Silver theme in your chart, add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="Office2007Silver">
In Code
To specifically define the Office2007Silver theme in your chart, add the following code your project:
Visual Basic
C1Chart1.Theme = ChartTheme.Office2007Silver
C#
c1Chart1.Theme = ChartTheme.Office2007Silver;
Vista Theme
This theme is based on the Vista style and it appears as a teal-colored chart with blue highlighting.
93
In XAML
To specifically define the Vista theme in your chart, add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="Vista">
In Code
To specifically define the Vista theme in your chart, add the following code your project:
Visual Basic
C1Chart1.Theme = ChartTheme.Vista
C#
c1Chart1.Theme = ChartTheme.Visata;
MediaPlayer Theme
This theme is based on the Windows Media Player style and it appears as a black-colored chart with blue
highlighting.
In XAML
To specifically define the MediaPlayer theme in your chart, add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="MediaPlayer">
94
In Code
To specifically define the MediaPlayer theme in your chart, add the following code your project:
Visual Basic
C1Chart1.Theme = ChartTheme.MediaPlayer
C#
c1Chart1.Theme = ChartTheme.MediaPlayer;
DuskBlue Theme
This theme appears as a charcoal-colored chart with electric blue and orange highlighting.
In XAML
To specifically define the DuskBlue theme in your chart, add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="DuskBlue">
In Code
To specifically define the DuskBlue theme in your chart, add the following code your project:
Visual Basic
C1Chart1.Theme = ChartTheme.DuskBlue
C#
c1Chart1.Theme = ChartTheme.DuskBlue;
DuskGreen Theme
This theme appears as a charcoal -colored chart with electric green and purple highlighting.
95
In XAML
To specifically define the DuskGreen theme in your chart, add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="DuskGreen">
In Code
To specifically define the DuskGreen theme in your chart, add the following code your project:
Visual Basic
C1Chart1.Theme = ChartTheme.DuskGreen
C#
c1Chart1.Theme = ChartTheme.DuskGreen;
Office2003Blue Theme
This theme is based on the Office 2003 Blue style and it appears as a neutral-colored chart with blue and orange
highlighting.
In XAML
To specifically define the Office2003Blue theme in your chart, add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="Office2003Blue">
In Code
96
To specifically define the Office2003Blue theme in your chart, add the following code your project:
Visual Basic
C1Chart1.Theme = ChartTheme.Office2003Blue
C#
c1Chart1.Theme = ChartTheme.Office2003Blue;
Office2003Classic Theme
This theme is based on the Office 2003 Classic style and appears as a gray-colored chart with slate-colored
highlighting.
In XAML
To specifically define the Office2003Classic theme in your chart, add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="Office2003Classic">
In Code
To specifically define the Office2003Classic theme in your chart, add the following code your project:
Visual Basic
C1Chart1.Theme = ChartTheme.Office2003Classic
C#
c1Chart1.Theme = ChartTheme.Office2003Classic;
Office2003Olive Theme
This theme is based on the Office 2003 Olive style and it appears as a neutral-colored chart with olive green and
orange highlighting.
97
In XAML
To specifically define the Office2003Olive theme in your chart, add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="Office2003Olive">
In Code
To specifically define the Office2003Olive theme in your chart, add the following code your project:
Visual Basic
C1Chart1.Theme = ChartTheme.Office2003Olive
C#
c1Chart1.Theme = ChartTheme.Office2003Olive;
Office2003Royale Theme
This theme is similar to the Office 2003 Royale style and appears as a silver-colored chart with blue highlighting.
In XAML
To specifically define the Office2003Royale theme in your chart, add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="Office2003Royale">
In Code
98
To specifically define the Office2003Royale theme in your chart add the following code your project:
Visual Basic
C1Chart1.Theme = ChartTheme.Office2003Royale)
C#
c1Chart1.Theme = ChartTheme.Office2003Royale;
Office2003Silver Theme
This theme is based on the Office 2003 Silver style and it appears as a silver-colored chart with gray and orange
highlighting.
In XAML
To specifically define the Office2003Silver theme in your chart, add the following Theme XAML to the
<c1chart:C1Chart> tag so that it appears similar to the following:
<c1chart:C1Chart Name="c1Chart1" Theme="Office2003Silver">
In Code
To specifically define the Office2003Silver theme in your chart, add the following code your project:
Visual Basic
C1Chart1.Theme = ChartTheme.Office2003Silver)
C#
c1Chart1.Theme = ChartTheme.Office2003Silver;
99
Standard
Office
GrayScale
100
Apex
Aspect
Civic
101
Concourse
Equity
Flow
102
Foundry
Median
Metro
103
Module
Opulent
Oriel
104
Origin
Paper
Solstice
105
Technic
Trek
Urban
106
Verve
Visual Effects
Visual Effects is a tool used for visually enhancing the 2D C1Chart control's border effect and shadow effect for
the data series. Any existing project can use the new features provided by this tool. The chart's appearance can
dramatically improve in a few simple steps using visual effects.
Limitation
Visual effects rendering may not work effectively in case of very complex and large data arrays or when highest
performance is required.
C1Chart provides a VisualEffect class which is the base class. The following classes are derived from the
VisualEffect class:
BorderEffect – Defines the border effect for the data series. This class enables you to modify the border
style, light direction, and thickness of the border.
ShadowEffect – Defines the shadow effect for the data series. This class enables you modify the shadow
color, shadow depth, light direction of the shadow, shadow opacity, and softness.
VisualEffectGroup – Defines the visual effect that consists from the several effects.
Border Effects
You can control the light angle, saturation, and transparency of the light source of the data series using the
BorderEffects class. The BorderEffects class includes the follow properties:
Property Description
BorderStyle Property
You can achieve a brightening or darkening effect on the data series using the BorderEffect.BorderStyle property.
The BorderEffect.BorderStyle property provides three options: light, dark, and combo. The Light value will make
the current data series color appear lighter in color. The Dark value produces a dark color effect for the current
data series color. The Combo value produces a combination of the light and dark values for the current data series
color.
The following table illustrates the effects of each value for the BorderEffect.BorderStyle property:
107
Value Result
BorderStyle.Light
BorderStyle.Combo
BorderStyle.Dark
LightAngle Property
You can change the angle of the visual rendering within the data series by setting its LightAngle property to a
different degree. The value of the LightAngle property ranges from -180 to 180 degrees.
The following table illustrates the data series with a LightAngle value of 53 degrees and the data seires with a no
LightAngle applied to it:
Value Result
53 degree angle
108
None
Thickness Property
As you increase the Thickness, the light source within each series gradually decreases. When the Thickness
property is set to a value higher than 25 the gradient light effects are not as noticeable.
The following table illustrates the effects of the various values for the BorderEffect.Thickness property:
10
25
Shadow Effects
You can create shadow effects for the data series using the ShadowEffects class. The ShadowEffects class includes
the following properties:
Property Description
109
LightAngle Gets or sets the light direction.
Opacity Gets or sets the shadow opacity (0-1).
Softness Gets or sets the shadow softness. 0 is sharp shadow and 1
is soft shadow.
Color Property
You can apply any color to the shadow using the Color property.
Depth Property
You can use the Depth property to determine the depth of the shadow. Increasing the Depth value will make the
shadow wider and appear further away from its associated object. Decreasing the Depth value will make the
shadow narrower and appear closer to its associated object.
The following table illustrates the effects of the Depth property when set to different values.
Value Result
10
LightAngle Property
You can change the angle of the visual rendering for the shadow by setting its LightAngle property to a different
degree. The value of the LightAngle property ranges from -180 to 180 degrees.
The following table illustrates the data series with a LightAngle value of 44 degrees and the data seires with a no
LightAngle applied to it:
Value Result
44 degrees
110
None
Opacity Property
The Opacity property controls the opacity level for the shadow. You can darken the shadow around the data series
by increasing value of the Opacity property. The numerical values range from 0.0 to 1.0. A value of 0 produces no
color and a value of 1.0 produces a dark solid color.
The following table illustrates the data series with an Opacity value of 0.3 and the data series with an Opacity
value of 1:
Value Result
0.3
1.0
Softness Property
To make the shadow effects on the dataseries appear softer use the Softness property. A value of 0 will produce a
sharp shadow that will make the shadow appear further from its associated object. A value of 1 will produce a soft
shadow and make the shadow appear closer to its associated object.
The following table illustrates the data series with a Softness value of 0 and the data seires with a Softness value of
1:
Value Result
111
1
C# ChartSamples Samples
Sample Description
Gallery Demonstrates the effect of the 12 different themes and palettes used on the
various chart types.
Labels and tooltips Shows how to use labels and tooltips on Column, Line Symbols, and Pie
charts.
Interactive chart Demonstrates how to use the mouse button to zoom, the ctrl key and mouse
button to scale, and the shift plus the mouse button to translate. It also
shows how to zoom out.
Complex chart Displays a Complex chart that includes a stacked column chart and a line
chart.
Axis features Shows how to use various axis features sucha as Logarithmis axes, Custom
labels, Dependent axes, Axis origin, and Axis ticks.
Visual Effects Demonstrates the effects of the following visual effects properties on any of
the charts: BorderEffect.BorderStyle, BorderEffect.LightAngle,
BorderEffect.Thickness, BorderStyle.Light, BorderStyle.Combo,
BorderStyle.Dark, ShadowEffect.Color, ShadowEffect.Depth,
ShadowEffect.LightAngle, ShadowEffect.Opacity, and ShadowEffect.Softness.
C# ChartEditor Sample
Sample Description
ChartEditor Demonstrates how to use ChartEditor control. Main properties of the chart
can be edited at runtime with ChartEditor. The ChartEditor in this sample is
112
docked at the right of the form.
C# ChartExtended Sample
Sample Description
Functions Plots simple function y=f(x). The code of function can be modified at
runtime.
Parametric Plots parametric function that is defined by two equations x=x(t) and y=y(t).
Live Plots dynamic data with automatic calculation of minimum, maximum and
average.
113
C#
// create some data
int npts = 1000;
double[] x = new double[npts], y = new double[npts];
for (int i = 0; i < npts; i++)
{
x[i] = i; y[i] = 100 * Math.Sin(0.1 * i) * Math.Cos(0.01 * i);
}
// setup axis
double xscale = 0.05; // show only 1/20 of the full data range
chart.View.AxisX.Min = 0; chart.View.AxisX.Max = npts-1;
chart.View.AxisX.Scale = xscale;
sb.Minimum = 0; sb.Maximum = 1;
sb.SmallChange = 0.5*xscale; sb.LargeChange = xscale;
sb.ViewportSize = 1.0 / (1.0 - xscale) - 1.0;
// connect axis with toolbar
sb.ValueChanged += (s, e) => chart.View.AxisX.Value = sb.Value;
Creating a Custom Axis Label to Set the Mark at the Middle of the Year
Use custom axis labels to set the mark at the middle of year like in the following code:
Visual Basic
chart.View.AxisX.ItemsSource = New DateTime() {New DateTime(2006, 1,
1).AddDays(0.5 * 365), New DateTime(2007, 1, 1).AddDays(0.5 * 365)}
C#
chart.View.AxisX.ItemsSource = new DateTime[]
{
new DateTime(2006,1,1).AddDays(0.5*365),
new DateTime(2007,1,1).AddDays(0.5*365),
//...
};
C#
dataSeries.Display = SeriesDisplay.ShowNaNGap;
114
Exporting the Chart Image to the PDF on the Client
To export the chart image to the PDF on the client, use the following code:
Visual Basic
Private Sub Button_Click(ByVal sender As Object, ByVal e As
RoutedEventArgs)
Dim wb As New WriteableBitmap(chart, Nothing)
Dim doc As New C1PdfDocument()
doc.Compression = CompressionLevelEnum.BestSpeed
doc.DrawImage(wb, New Rect(New Point(), doc.PageSize),
ContentAlignment.TopLeft, Stretch.None)
C#
private void Button_Click(object sender, RoutedEventArgs e)
{
WriteableBitmap wb = new WriteableBitmap(chart, null);
C1PdfDocument doc = new C1PdfDocument();
doc.Compression = CompressionLevelEnum.BestSpeed;
doc.DrawImage(wb, new Rect(new Point(),doc.PageSize),
ContentAlignment.TopLeft, Stretch.None);
// Silverlight
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Jpeg files (*.jpg)|*.jpg|Png files (*.png)|*.png";
115
if (sfd.ShowDialog() == true)
{
using (var stream = sfd.OpenFile())
{
if (sfd.SafeFileName.EndsWith(".jpg"))
chart.SaveImage(stream, ImageFormat.Jpeg);
else
chart.SaveImage(stream, ImageFormat.Png);
}
}
chart.Data.ItemNames = names
chart.ChartType = ChartType.Pie
C#
string[] names = new string[] { "Apples", "Oranges", "Peaches"};
double[] values = new double[] { 20.0, 10.0, 7.0 };
chart.Data.ItemNames = names;
chart.ChartType = ChartType.Pie;
Visual Basic
Dim dt As New DataTable()
dt.Columns.Add("Name", GetType(String))
dt.Columns.Add("Value", GetType(Double))
dt.Rows.Add("Apples", 20R)
dt.Rows.Add("Oranges", 10R)
dt.Rows.Add("Peaches", 7R)
116
C#
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Value", typeof(double));
dt.Rows.Add("Apples", 20.0);
dt.Rows.Add("Oranges", 10.0);
dt.Rows.Add("Peaches", 7.0);
chart.Data.Children.Add(ds);
117
}
};
chart.Data.Children.Add(ds);
chart.ChartType = ChartType.LineSymbols;
chart.Data.Children.Add(ds)
C#
chart.ChartType = ChartType.LineSymbols;
if (rp != null)
118
{
int pi = rp.DataPoint.PointIndex;
if (pi > 0)
{
//rotate triangle and change its color
if ( values[pi] > values[pi-1] )
{
rp.RenderTransform = new RotateTransform() { Angle = -90 };
rp.RenderTransformOrigin = new Point(0.5, 0.5);
rp.Fill = new SolidColorBrush(Colors.Green);
}
else if (values[pi] < values[pi - 1])
{
rp.RenderTransform = new RotateTransform() { Angle = 90 };
rp.RenderTransformOrigin = new Point(0.5, 0.5);
rp.Fill = new SolidColorBrush(Colors.Red);
}
}
}
};
chart.Data.Children.Add(ds);
C#
chart.View.AxisX.Position = AxisPosition.Far;
chart.Data.Children.Add(ds);
chart.ChartType = ChartType.Line;
119
Showing the X-Values in the Tooltip
To show the x-values in the tooltip, use the following xaml and then the Visual Basic or C# code that creates the
chart and uses the template:
XAML
<c1chart:C1Chart x:Name="chart">
<c1chart:C1Chart.Resources>
<DataTemplate x:Key="tt">
<StackPanel Orientation="Vertical">
<!-- XAsString returns xvalue that is formatted similar to x-
axis -->
<TextBlock Text="{Binding XAsString}" />
<TextBlock Text="{Binding Y}" />
</StackPanel>
</DataTemplate>
</c1chart:C1Chart.Resources>
</c1chart:C1Chart>
Visual Basic
Dim cnt As Integer = 20
Dim x As DateTime() = New DateTime(cnt - 1) {}
Dim y As Double() = New Double(cnt - 1) {}
Dim rnd As New Random()
For i As Integer = 0 To cnt - 1
x(i) = DateTime.Today.AddDays(-i)
y(i) = rnd.NextDouble() * 100
Next
chart.Data.Children.Add(New XYDataSeries())
chart.View.AxisX.IsTime = True
chart.ChartType = ChartType.LineSymbols
C#
int cnt = 20;
DateTime[] x = new DateTime[cnt];
double[] y = new double[cnt];
Random rnd = new Random();
for (int i = 0; i < cnt; i++)
{
x[i] = DateTime.Today.AddDays(-i);
y[i] = rnd.NextDouble() * 100;
}
chart.Data.Children.Add(new XYDataSeries()
{
XValuesSource = x, ValuesSource = y,
PointTooltipTemplate = (DataTemplate)chart.Resources["tt"]
});
chart.View.AxisX.IsTime = true;
chart.ChartType = ChartType.LineSymbols;
120
Creating Wrap Around Text Blocks for Large Number of Series
To create wrap around text blocks for large number of series use the following XAML and then use the Visual
Basic or C# code:
XAML
<c1chart:C1Chart x:Name="chart">
<c1chart:C1ChartLegend Position="Top">
<c1chart:C1ChartLegend.ItemsPanel>
<ItemsPanelTemplate>
<c1:C1WrapPanel ItemHeight="20" ItemWidth="80"/>
</ItemsPanelTemplate>
</c1chart:C1ChartLegend.ItemsPanel>
</c1chart:C1ChartLegend>
</c1chart:C1Chart>
Visual Basic
For i As Integer = 0 To 19
chart.Data.Children.Add(New DataSeries())
Next
C#
for (int i = 0; i < 20; i++)
chart.Data.Children.Add(new DataSeries() { Label = "s " + i.ToString()
});
121