Search
Tutorial 1: Loading Data into Chart

Chart components render data values from Series objects assigned to chart's Series collection. In this tutorial we'll show how to create several series representing stock prices, and render them as side-by-side bars in a BarChart. The tutorial assumes you have added a BarChart instance as described in Getting Started guide. The complete example project is available under Samples subfolder of library's distribution.

1. Let's start by creating a method that returns (pretend) stock price data. If you have access to a stock market service, you could as well replace this code with a call to the service API as documented by its provider. The StockPrice class returned by this method is defined in MindFusion.Charting namespace for use with some kinds of charts, but any plain data object will work for this example:

C#  Copy Code

async Task<List<StockPrice>> FetchStockPrices(string name)
{
    // pretend we are calling a web service, returning
    // stock price statistics for last 7 days
    return await Task.Run(() =>
    {
        var random = new Random();
        var date = DateTime.Now.AddDays(-8);

        var prices = new List<StockPrice>();
        for (int i = 0; i < 7; i++)
        {
            date = date.AddDays(1);

            double open = 200 + 500 * random.NextDouble();
            double close = open + 50 * (0.5 - random.NextDouble());
            double low = Math.Min(open, close) - 50 * random.NextDouble();
            double high = Math.Max(open, close) + 50 * random.NextDouble();

            prices.Add(
                new StockPrice(open, close, low, high, date));
        }
        return prices;
    });
}

2. Call the FetchStockPrices method from OnAfterRenderAsync override:

C#  Copy Code

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await base.OnAfterRenderAsync(firstRender);

    if (firstRender)
    {
        var stockPrices = await FetchStockPrices("ACME");
        ....

3. Now we'll extract values of the StockPrice object properties and fill SimpleSeries instances with the double values. Each SimpleSeries is drawn as a sequence of bars, by default interlacing the bars to draw side-by-side groups for each index. Other options for grouping bars from multiple series are provided by the BarLayout property. Each bar can also display labels inside or on top of the bar, or at the X axis. Here we'll show axis label for only one of the series. The series' Title property is displayed inside chart's legend box:

C#  Copy Code

// a series of daily opening prices
chart.Series.Add(
    new SimpleSeries(
        stockPrices.Select(sp => sp.Open).ToList(),
        stockPrices.Select(sp => sp.Date.ToShortDateString()).ToList())
    {
        Title = "Open",
        SupportedLabels = LabelKinds.XAxisLabel
    });

// a series of daily closing prices
chart.Series.Add(
    new SimpleSeries(
        stockPrices.Select(sp => sp.Close).ToList(),
        null /* no additional string labels*/)
    {
        Title = "Close"
    });

// a series of daily min prices
chart.Series.Add(
    new SimpleSeries(
        stockPrices.Select(sp => sp.Low).ToList(),
        null /* no additional string labels*/)
    {
        Title = "Low"
    });

// a series of daily max prices
chart.Series.Add(
    new SimpleSeries(
        stockPrices.Select(sp => sp.High).ToList(),
        null /* no additional string labels*/)
    {
        Title = "High"
    });

4. Set the color of each series by modifying the chart's Theme:

C#  Copy Code

// assign different colors to each series
chart.Theme.CommonSeriesFills = new List<Brush>
{
    new SolidBrush(Colors.Yellow),
    new SolidBrush(Colors.LightBlue),
    new SolidBrush(Colors.Red),
    new SolidBrush(Colors.Green)
};

5. Finally, set a few properties to customize chart caption labels and axis appearance:

C#  Copy Code

// customize axis appearance
chart.Title = "ACME stock price weekly";
chart.YAxis.MinValue = 0;
chart.YAxis.Title = "stock price in USD";
chart.XAxis.Title = "";
chart.ShowXCoordinates = false;
chart.ShowXTicks = false;
chart.LegendHorizontalAlignment = LayoutAlignment.Far;

6. If you run the project now, it should render a chart like this: