New Release for the Free JS Chart Library

MindFusion Free JS Chart has a new release with the following new features:

– All Series can accept now simple JavaScript array-s as arguments instead of Collections.List instances
– The ToolTip class is greatly extended with many new properties that allow you to customize the apparance and position of tooltips
– The Color.knownColors field lists all standard CSS color names
– Brush and Pen instances can be created with simple strings that specify the HTML code of the color as argument instead of Color objects.
– The yLabelAlignment property of BiaxialChart specifies horizontal alignment of Y-axis labels.
– Texts are now properly underlined when FontStyle.Underline is set.

Free JS Chart is MindFusion charting library that is offered free of charge for commercial use. No attribution is required.

More about MindFusion Free JS Chart at https://mindfusion.eu/free-js-chart.html

Combination Chart in JavaScript

In this blog post we will use the Charting for JavaScript library to create the chart that you see below:

This is a combination chart has one line series and two bar series drawn in stacks. We will use the Dashboard control to combine the building elements of the chart: data series, legend, axes, title and plot.

I. HTML Setup

We need an HTML Canvas element for the chart to draw itsself onto. It is important that we give it an id. The Canvas element will render the chart and its position and size will determine where and how big the chart will be drawn.

<canvas id="dashboard" style="width: 100%; height: 100%; display: block;"></canvas>

The Dashboard control needs the MindFusion.Charting.js library. We also need the MindFusion.Drawing module for presentation classes like brushes, pens etc. We include reference to these files at the end of the web page, before the closing BODY tag:

<a href="http://Scripts/MindFusion.Common.js">http://Scripts/MindFusion.Common.js</a>
<a href="http://Scripts/MindFusion.Charting.js">http://Scripts/MindFusion.Charting.js</a>

The two library JavaScript files are in a subfolder called Scripts. We prefer to keep the JavaScript code for the combination chart separate from the web page and we include one final JS reference:

<a href="http://CombinationChart.js">http://CombinationChart.js</a>

This is the code-behind file where we will write all code that creates and customizes the combination chart.

II. Creating the Dashboard and General Chart Settings

We add mappings to the chart and drawing namespaces that we want to use. If your IDE supports Intellisense you can also add a reference to the Intellisense file.

/// 
var Charting = MindFusion.Charting;

var Controls = Charting.Controls;
var Collections = Charting.Collections;
var Drawing = Charting.Drawing;
var Components = Charting.Components;

The Dashboard class requires and HTML element in the constructor. We get the Canvas from the web page with the help of its id:

// create the dashboard
var dashboardEl = document.getElementById('dashboard');
dashboardEl.width = dashboardEl.offsetParent.clientWidth;
dashboardEl.height = dashboardEl.offsetParent.clientHeight;
var dashboard = new Controls.Dashboard(dashboardEl);

The Dashboard control is a container for all elements of a dashboard. In order to render a chart, we need a Plot element that can visualize data. We create an instance of the Plot2D class:

var plot = new Charting.Plot2D();
plot.gridType = Charting.GridType.Horizontal;
plot.gridColor1 = plot.gridColor2 = new Drawing.Color.fromArgb(200, 243, 244, 254);

Then we specify that the plot will render a horizontal grid with light gray grid lines. Each Plot2D has a seriesRenderers property that stores all -SeriesRenderer -s that are responsible for drawing correctly the data series according to their type – LineSeries BarSeries PieSeries etc. More about that later.

III. Data Series and Renderers

Each data series is represented by a class that corresponds to its type. MindFusion Charting for JavaScript has a variety of ISeries classes, some of whom can be used in different chart types. We will first use the BarSeries class to create one of the series that render bars:

// data for first bar series
var barSeries1 = new Charting.BarSeries(
		new Collections.List([9, 11, 13, 18, 19, 22, 23, 26, 29, 32, 33, 36, 41, 46, 49, 55, 57, 58, 61, 63]), //y
		null, null,
		new Collections.List(["1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", 
		"2012", "2013", "2014", "2015", "2016", "2017", "2018"]));

The BarSeries constructor requires several arguments. The first one is the data list, the second are lists with the top and inner labels, which we do not use. The last parameter are the labels for the X-axis and we set here the desired labels.

Then we set the title property of the BarSeries – it is important because it will render as a legend item.

barSeries1.title = "Total amount of goods sold";

We create then another series for the top row of bars. We don’t need any labels any more so we use now a simple Series2D instance:

var barSeries2 = new Charting.Series2D(
		new Collections.List([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]),//x
		new Collections.List([3, 4, 5, 5, 7, 8, 7, 6, 8, 15, 17, 21, 19, 18, 17, 16, 17, 19, 20, 22]),//y
		null);

barSeries2.title = "Extra production to meet demand";

The series need a SeriesRenderer that can draw them. There are different SeriesRenderer -s for the different types of series. The different SeriesRenderer instances support different ISeries classes.

In our case we want a stack bar chart and we use the BarStackRenderer . Each SeriesRenderer accepts a list with the Series instances it must render. Here is the code for the stack bars:

// draw bars
var barRenderer = new Charting.BarStackRenderer(new Collections.ObservableCollection([barSeries1, barSeries2]));
barRenderer.seriesStyle = new Charting.PerSeriesStyle (new Collections.List([new Drawing.Brush("#230A59"), new Drawing.Brush("#3E38F2")]));
barRenderer.barSpacingRatio = 0.7;

The different SeriesRenderer instances have different sets of properties that allow you to customize how the data series will be drawn. Here we use the barSpacingRatio to specify the thickness of the stack bars.

As we mentioned earlier, the Plot2D class has a seriesRenderers property where we can add the different SeriesRenderer -s that we want to show. We add the BarStackRenderer add graphics to plot
plot.seriesRenderers.add(barRenderer);

The procedure is the same for the line chart. We create another Series2D instance:

// sample data for line graphics
var lineSeries = new Charting.Series2D(
				new Collections.List([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),//x
				new Collections.List([7, 9, 12, 15, 18, 23, 24, 27, 35, 41, 46, 49, 53, 55, 58,  61, 63, 66, 67, 69 ]),//right-y
				null);
lineSeries.title = "Peak demand";

We give it a title and create a LineRenderer that will render this series:

// draw lines
var lineRenderer = new Charting.LineRenderer(
				new Collections.ObservableCollection([lineSeries]));
lineRenderer.seriesStyle = new Charting.UniformSeriesStyle(new Drawing.Brush("#ffffff"), new Drawing.Brush("#ffffff"), 6);

Finally we add the LineRenderer to the seriesRenderers collection of the Plot2D instance.

plot.seriesRenderers.add(lineRenderer);

You might have noticed that we also set the seriesStyle property in both the BarStackRenderer and the LineRenderer classes. This is the property that specifies how the chart series will be painted. There are different classes that derive from SeriesStyle All of them concern a different pattern of applying brushes and pens to the element of a Series We use here an instance of the PerSeriesStyle class that accepts lists with brushes and strokes and applies one consequtive brush and stroke to all elements in the corresponding Series . The LineRenderer uses the UniformSeriesStyle , which accepts just two Brush instances as arguments and applies them to fill and stroke all elements in all Series instances in the SeriesRenderer .

IV. The Axes

The chart axes are instances of the Axis class. We use their min , max and interval properties to specify the numeric data of each of the two axes that our dashboard will have – X and Y:

// create axes
var xAxis = new Charting.Axis();
xAxis.interval = 0;
xAxis.minValue = -1;
xAxis.maxValue = 20;
xAxis.title = "";

// create axes
var yAxis = new Charting.Axis();
yAxis.interval = 10;
yAxis.minValue = 0;
yAxis.maxValue = 100;
yAxis.title = "Cost of goods in mlns of USD";

Then we specify to the Plot2D that the Axis instances we created are its X and Y axes:

plot.yAxis = yAxis;
plot.xAxis = xAxis;

As you might have guessed, the Axis need Renderer-s to render them. They are called respectively XAxisRenderer and YAxisRenderer .

// create renderers for the two axes
var xAxisRenderer = new Charting.XAxisRenderer(xAxis);
xAxisRenderer.margin = new Charting.Margins(0, 0, 0, 10);
xAxisRenderer.labelsSource = plot;
xAxisRenderer.showCoordinates = false;


var yAxisRenderer = new Charting.YAxisRenderer(yAxis);
yAxisRenderer.margin = new Charting.Margins(10, 0, 0, 0);

The renderers have various properties for specifying how the axes will be rendered. We use margin to add some space around the two axes.

Finally, we use the layoutBuilder property of the Dashboard class to create a GridPanel that will correctly measure and arrange all building blocks of our cobination chart:

dashboard.layoutBuilder.createAndAddPlotAndAxes(
		plot, null,
		[yAxisRenderer],
		[ xAxisRenderer ],
		null);

V. The Legend

As we said, the legend items are taken from the title property of each Series . We use a LegendRenderer to render the legend and set some of its properties:

// add legend
var legendRenderer = new Charting.LegendRenderer();
legendRenderer.content = new Collections.ObservableCollection([barRenderer, lineRenderer]);
legendRenderer.background = new Drawing.Brush("#d0d3fb");
legendRenderer.borderStroke = new Drawing.Brush("#BDBFAA");
legendRenderer.showTitle = false;
legendRenderer.horizontalAlignment = Components.LayoutAlignment.Far;

The content property of LegendRenderer allows us to specify a collection of SeriesRenderer instances. This way we can have one legend for series of different kinds. We don’t need a title for our legend, so we set showTitle to false.

The LegendRenderer requires no special positioning in the dashboard layout, so we simple add it to the rootPanel of the Dashboard and let it handle its easure and placement:

dashboard.rootPanel.children.add(legendRenderer);

VI. The Title and Subtitle

The title is an instance of the TextComponent class:

var tc = new Components.TextComponent();
tc.text = "STEADY GROWTH";
tc.fontSize = 20.4;
tc.horizontalAlignment = Components.LayoutAlignment.Near;
tc.margin = new Charting.Margins(100, 10, 0, 0);
dashboard.layoutPanel.children.add(tc);

It has various appearance properties. Just like the LegendRenderer the TextComponent can be added directly to the children of the layoutPanel.

Now that we’ve made all arrangements for the chart let’s not forget to call the draw method that will render the chart on the screen:

dashboard.draw();

That was everything. You can see an online demo of the chart here.

You can download the full source code of this combination chart in JavaScript together with all used libraries from here:

Combination Chart in JavaScript Full Code

About Charting for JavaScript: MindFusion library for interactive charts and gauges. It supports all common chart types including 3D bar charts. Charts can have a grid, a legend, unlimitd number of axes and series. Scroll, zoom and pan are supported out of the box. You can easily create your own chart series by implementing the Series interface.
The gauges library is part of Charting for JavaScript. It supports oval and linear gauge with several types of labels and ticks. Various samples show you how the implement the gauges to create and customize all popular gauge types: car dashboard, clock, thermometer, compass etc. Learn more about Charting and Gauges for JavaScript at https://mindfusion.eu/javascript-chart.html.

Multi Series Line Chart With Custom ToolTips in JavaScript

In this blog post we will build a line chart with 4 different series and custom labels on both axes. The chart renders tooltips with custom formatting. You can see the chart online here:

I. Initial Setup

We start by creating a blank HTML page and there we initialize the HTML Canvas element that will be needed by the Js Chart library.

<canvas id="chart" style="width: 100%; height: 100%; display: block;">

You can initialize the canvas as you want – there are no special requirements as to the size, position, scroll settings or anything else. What is important is that you add an id for that canvas – it will be used by the chart library. At the bottom of the page, right before the closing BODY tag we add a reference to the charting JavaScript files that represent the chart library:

<script type="text/javascript" src="Scripts/MindFusion.Common.js"></script>
<script type="text/javascript" src="Scripts/MindFusion.Charting.js"></script>

We also add a reference to another JavaScript file called LineChartTooltips.js. We haven’t created it yet, but this will be the file that will hold the JavaScript code for our chart.

<script type="text/javascript" src="LineChartTooltips.js">

II. Initializing the Line Chart In the LineChartTooltips JavaScript file we first include a reference to the Intellisense file so we can use code completion.

/// <reference path="Scripts/jspack-vsdoc.js"></reference>

Then we add mappings to the namespaces that we want to use:

var Controls = Charting.Controls;
var Collections = Charting.Collections;
var DateTimeSeries = Charting.DateTimeSeries;
var Drawing = Charting.Drawing;
var ToolTip = Charting.ToolTip;

Now we create the JavaScript chart object. We need a reference to the HTML canvas element, which we get using its id:

var chartEl = document.getElementById('chart');
chartEl.width = chartEl.offsetParent.clientWidth;
chartEl.height = chartEl.offsetParent.clientHeight;

We use the clientWidth and clientHeight properties of the offsetElement for the chart to give the chart its size.

Next we create the LineChart control and set its title and subtitle.

// create the chart
var lineChart = new Controls.LineChart(chartEl);
lineChart.title = "Women as a percentage in all S&E occupations";
lineChart.subtitle = "1993-2010";

III. Labels

The labels for the X and Y axes are set with two lists:

var xlabels = new Collections.List([
    "1993", "1995", "1997", "1999", "2003", "2006",
    "2008", "2010"]);

var ylabels = new Collections.List([
    "0%", "10%", "20%", "30%", "40%", "50%",
    "60%", "70%"]);

By default the labels at the axes are the intervals. We can replace them with the labels of a given chart series by using the supportedLabels property. This property tells the control at which chart element the labels of the series should be rendered – X or Y axis, tooltip, data labels etc. The members are from the LabelKinds enumeration.

The LineChart control uses series that support X and Y values. The best match is the Series2D class. This class supports one list with labels, which are always drawn at the data points. The easiest thing for us to do is to customize the Series2D and make it accept two lists with labels, which we will show them on both axes. Here is how we create the custom class by inheriting from Series2D

SeriesWithAxisLabels = function (xValues, yValues, xLabels, yLabels) {
    this.yLabels = yLabels;
    Charting.Series2D.apply(this, [xValues, yValues, xLabels]);
};

SeriesWithAxisLabels.prototype = Object.create(Charting.Series2D.prototype);

Our custom class is called SeriesWithAxisLabels. It accepts two lists with labels in the constructor. With one of them we call the constructor of the base class. The other we assign to a new property called yLabels.

Now we need to override the getLabel method and return the right label for the X and Y axis.

SeriesWithAxisLabels.prototype.getLabel = function (index, kind) {
    if ((kind & Charting.LabelKinds.XAxisLabel) != 0 && this.labels)
        return this.labels.items()[index];

    if ((kind & Charting.LabelKinds.YAxisLabel) != 0 && this.yLabels)
        return this.yLabels.items()[index];
   
    return "";
};

The getLabel method is responsible for providing the correct label according to the kind of labels that is requested. Here we check if we are asked for a label at the X or Y axis and return the label with the correct index from the xLabels or yLabels arrays. Here is how we create that series, which serves only to provide labels for the axes:

var series0 = new SeriesWithAxisLabels(
    new Collections.List([1, 2, 3, 4, 5, 6, 7, 8]),
    new Collections.List([0, 10, 20, 30, 40, 50, 60, 70]),
    xlabels, ylabels
);
series0.supportedLabels = Charting.LabelKinds.XAxisLabel | Charting.LabelKinds.YAxisLabel;
lineChart.series.add(series0);

Note that the data for the X and Y values of series0 corresponds to the positions on the axes where the labels should be rendered.

IV. Data

The data for the chart is provided by two series. They are also of type Series2D However, we do not want them to render the labels at the data points, which is their default behaviour. We would customize once again the Series2D class and make the labels be used for tooltips and not the data points.

We define a new SeriesWithToolTip class that overrides Series2D

SeriesWithToolTip = function (xValues, yValues, labels) { 
    Charting.Series2D.apply(this, [xValues, yValues, labels]);
};

SeriesWithToolTip.prototype = Object.create(Charting.Series2D.prototype);

The difference is the getLabel method. When asked for a label for the tooltip it returns the label at the given position from the series’ labels list:

SeriesWithToolTip.prototype.getLabel = function (index, kind) {
    if ((kind & Charting.LabelKinds.ToolTip) != 0 && this.labels)
        return this.labels.items()[index];   

    return Charting.Series2D.prototype.getLabel.apply(this, [index, kind]);
};

We create a data series from the SeriesWithToolTip kind this way:

//first series
var series1 = new SeriesWithToolTip(
    new Collections.List([1, 2, 3, 4, 5, 6, 7, 8]),
    new Collections.List([21.3, 21.5, 21.7, 23, 26.3, 26.1, 26.3, 27.5])
);

series1.title = "All S&E occupations";
var tooltips = new Collections.List();

for (let step = 0; step < series1.yData.count(); step++) {
    tooltips.add(series1.title + " for " + xlabels.items()[step] + ": " +
        series1.yData.items()[step] + "%");
}
series1.labels = tooltips;
series1.supportedLabels = Charting.LabelKinds.ToolTip;
lineChart.series.add(series1);

We generate the tooltip in a list, because we want the text to combine data from the xLabels and its yData list.

V. Styling the Chart

the JavaScript Chart library supports several styles to be applied on the chart depending on what you want to achieve. In our case the best choice is the PerSeriesStyle class, which colours all the elements of a Series with the subsequent brush from its strokes and fills collections.

// create line brushes
var firstBrush = new Drawing.Brush("transparent");
var secondBrush = new Drawing.Brush("#EA3F36");
var thirdBrush = new Drawing.Brush("#1A3D95"); 
var fourthBrush = new Drawing.Brush("#717173");
var fifthBrush = new Drawing.Brush("#407D39");

var style = new Charting.PerSeriesStyle();
style.fills = style.strokes = new Collections.List([firstBrush, secondBrush, thirdBrush, fourthBrush, fifthBrush]);
style.strokeDashStyles = new Collections.List([Drawing.DashStyle.Dash, Drawing.DashStyle.Dash,
Drawing.DashStyle.Dash, Drawing.DashStyle.Dash, Drawing.DashStyle.Dash]);
style.strokeThicknesses = new Collections.List([2, 2, 2, 2, 2]);
lineChart.plot.seriesStyle = style;

The PerSeriesStyle class also provides us with properties to specify the DashStyle and the strokeThickness of the brushes.

The styling of the axes and the fonts is done via the properties of the Theme class. Each chart has a theme property of type Theme. You can use it to customize many properties of the chart:

lineChart.legendTitle = "";
lineChart.gridType = Charting.GridType.Horizontal;
lineChart.theme.axisTitleFontSize = 14;
lineChart.theme.axisLabelsFontSize = 12;
lineChart.theme.subtitleFontStyle = Charting.Drawing.FontStyle.Bold;
lineChart.theme.titleFontStyle = Charting.Drawing.FontStyle.Bold;
lineChart.theme.subtitleFontSize = 16;
lineChart.theme.dataLabelsFontSize = 12;

Note the dataLabelsFontSize property here. It regulates the font not only for the data labels but for the labels of the legend. That is why we set it, though we do not render data labels. There are several dataLabels properties like dataLabelsFontName, which customize different aspects of the labels at chart series and legend.

VI. Legend

You can show the legend with showLegend property, which is true by default. The legendTitle property sets the title of the legend, which we set to an epty string. The labels for each series are taken from the series’ title property:

lineChart.legendTitle = "";

series1.title = "All S&E occupations";
.................
series2.title = "Computer/mathematical scientists";
..................
series3.title = "Engineers";

We can customize the background and border of the legend through properties of the theme or the LegendRenderer:

lineChart.legendRenderer.background = new Drawing.Brush("#f2f2f2");
lineChart.legendRenderer.borderStroke = new Drawing.Brush("#c0c0c0");

VII. ToolTips

The tooltips are automatically rendered when the user hovers over a data point. We make the data points visible by setting showScatter to true:

lineChart.showScatter = true;

Then we set different properties of the TooltTip class to achieve the desired look of the tooltips:

ToolTip.brush = new Drawing.Brush("#fafafa");
ToolTip.pen = new Drawing.Pen("#9caac6");
ToolTip.textBrush = new Drawing.Brush("#717173");
ToolTip.horizontalPadding = 6;
ToolTip.verticalPadding = 4;
ToolTip.horizontalOffset = -6;
ToolTip.verticalOffset = -4;
ToolTip.font = new Charting.Drawing.Font("Arial", 12, Charting.Drawing.FontStyle.Bold);

The ToolTip class is a static class and we can set the properties directly.

At the end, we should always call draw() to see the chart correctly rendered on the screen:

lineChart.draw();

You can download the sample with the JavaScript chart libraries and the Intellisense file from this link:

https://mindfusion.eu/samples/javascript/chart/JsLineChartTooltips.zip

About Charting for JavaScript: MindFusion library for interactive charts and gauges. It supports all common chart types including 3D bar charts. Charts can have a grid, a legend, unlimitd number of axes and series. Scroll, zoom and pan are supported out of the box. You can easily create your own chart series by implementing the Series interface.
The gauges library is part of Charting for JavaScript. It supports oval and linear gauge with several types of labels and ticks. Various samples show you how the implement the gauges to create and customize all popular gauge types: car dashboard, clock, thermometer, compass etc. Learn more about Charting and Gauges for JavaScript at https://mindfusion.eu/javascript-chart.html.

Negative Bar Stack in WinForms

Thia post will demonstrate how to create a horizontal stacked bar chart with negative values. We will use the Charting for WinForms component and the final chart looks like this:

Negative Stacked Bar Chart in WinForms with the Chart Control

Negative Stacked Bar Chart in WinForms with the Chart Control

I. Data

The chart will use four series. The first two series are the ones that you clearly see – the red and blue one. We initialize two data arrays with random values that represent the data:

var firstBarX = new List(11);
var secondBarX = new List(11);

Random r = new Random();
            
for(int i = 0; i < 11; i++)
   {
       firstBarX.Add(2.2 + r.NextDouble());
       secondBarX.Add(2.4 + r.NextDouble());
    }

We need a list with data values that are exactly the same as the first series, but are negative. They will provide a transparent initial series, whose bars will offset the first, red, series as much as the value of the red bar should be:

//generate data for the transparent series
var transparentBarX = new List(firstBarX.Count);

for (var i = 0; i < firstBarX.Count; i++)			
    transparentBarX.Add(0 - firstBarX[i]);

The data for the Y-axis is very simple. We just need a list with the numbers from 1 to 12:

//data for the Y-axis
var barY = new List();
for (int i = 1; i < 12; i++)			
	barY.Add(i);

II. Labels
We will create two lists with the labels that we will show – for the two axis. The labels for the Y-axis will be used as tooltips as well. We just initialize two string lists:

//initialize labels for the X axis
var ageLabels = new List() { "0-5", "6-11", "12-17", "18-23", "24-29", "30-35",
		   "36-41", "42-47", "48-53", "54-59", "60-65" };

//initialize labels for the Y axis.
var percentageLabels = new List { "5%", "4%", "3%", "2%", "1%", "0%", 				"1%", "2%", "3%", "4%", "5%", };

We will use this label lists in the next section, when we create the series.

III. Series

We will use 4 series, of type Series2D. This series is useful for its SupportedLabels property – it allows us to specify what the labels of the series would be used for. We start with the transparent series. Its labels will be used for custom labels at the Y-axis:

var seriesTransparent = new MindFusion.Charting.Series2D(transparentBarX, barY, ageLabels);
seriesTransparent.SupportedLabels = MindFusion.Charting.LabelKinds.YAxisLabel;
seriesTransparent.Title = "";

We use for X-data the negative values you remember from the previous paragraph. The age labels are those that provide the data for the axis.

Then we initialize the two series for the chart data:

var seriesFirst = new MindFusion.Charting.Series2D(firstBarX, barY, ageLabels);
seriesFirst.SupportedLabels = MindFusion.Charting.LabelKinds.ToolTip;
seriesFirst.Title = "Female";

var seriesSecond = new MindFusion.Charting.Series2D(secondBarX, barY, ageLabels);
seriesSecond.SupportedLabels = MindFusion.Charting.LabelKinds.ToolTip;
seriesSecond.Title = "Male";

The last series that we create is just to provide data for the X-axis and we set its SupportedLabels property to MindFusion.Charting.LabelKinds.XAxisLabel. The X-data for this series corresponds to the coordinates of the X-labels, that’s why set the numbers from -5 to 5 as X-data:

var firstParamList = new List();
      for (int i = -5; i < 6; i++)			
	 firstParamList.Add(i);

The Y-data could be all zeros, we won’t use them anyway.

var secondParamList = new List();
    for (int i = 0; i < 12; i++)			
	secondParamList.Add(0);

And we create the series this way:

//the purpose of this series is to only supply the Xaxis labels, it is transparent.	
var seriesThird = new MindFusion.Charting.Series2D(firstParamList, secondParamList, percentageLabels);           	
seriesThird.SupportedLabels = MindFusion.Charting.LabelKinds.XAxisLabel;
seriesThird.Title = "";

After you have created all series, you should add them to the Series collection of the BarChart:

barChart.Series = new ObservableCollection
	{ seriesTransparent, seriesFirst, seriesSecond, seriesThird };
           	

IV. Axes and Grid

We need to fix the divisions of the X-axis if we want to show a grid and the grid to be neatly aligned with the axes. We will set the min value to be -6, the interval 1 and the max value to be 6:

barChart.XAxis.Interval = 1;
barChart.XAxis.MinValue = -6;
barChart.XAxis.MaxValue = 6;		

We will use three more properties to hide the interval labels at both axes, show ticks on them and set a title for each axis:

barChart.XAxis.Title = "Percentage of the Population";
barChart.YAxis.Title = "Ages";
			
barChart.ShowYCoordinates = false;
barChart.ShowXCoordinates = false;

barChart.ShowXTicks = true;
barChart.ShowYTicks = true;

Finally, we have to set the grid and specify that the bars are horizontal:

barChart.GridType = GridType.Vertical;
barChart.HorizontalBars = true;

V. Styling

Styling the chart is done though the SeriesSyle property of the Plot. You can assign to it different series types, you can check the list at the ISeriesStyle interface page in the documentation:

barChart.Plot.SeriesStyle = new PerSeriesStyle()
{
	Strokes = new List {
		firstBrush, new SolidBrush(Color.FromArgb(179, 0, 0)), 
                new SolidBrush(Color.FromArgb(0, 0, 102)), firstBrush
		},
		StrokeThicknesses = new List {
			 0,2,2,0
		},
		Fills = new List()
		{
			firstBrush, secondBrush, thirdBrush, firstBrush
	}
};

This style indicates that each brush from its collection will be used for one series in the chart. We assign to it 4 brushes and 4 strokes. The first brush is transparent, the second one is red, the other is blue and the last one is black – we won’t draw with it anyway.

The Theme property of the chart holds a lot of options for customizing the appearance. Here are just a few of them:

barChart.Theme.LegendBorderStrokeThickness = 1;
barChart.Theme.LegendBorderStroke = new SolidBrush(Color.Black);
barChart.Theme.GridColor2 = Color.White;
barChart.Theme.GridColor1 = Color.FromArgb(250, 250, 250);
barChart.Theme.GridLineColor = Color.FromArgb(153, 153, 153);
barChart.Theme.PlotBackground = new SolidBrush(Color.FloralWhite);
...........
..........

And that’s the end of this step-by-step guide. You can download the sample together will all necessary libraries from this link:

Download Negative Stack Bar Chart in CS Sample

About MindFusion Charting for WinForms: A versatile dashboard component that provides your WinForms application with the ability to create fascinating charts, interactive dashboards and practical gauges. The component combines a flexible API that allows custom combination of chart components to build any type of chart you want. You can add as many axes of any type you want, combine various chart series into a single chart with different data providers each. The control also supports pan and zoom, scroll, unlimited number of legends, grid and a dashboard panel. Linear and oval gauges complete the tool set and guarantee every feature you might need to build the perfect gauge, chart of any type or dashboard in WinForms is right at your fingertips. Learn more at https://mindfusion.eu/winforms-chart.html

Real-Time Chart in WinForms

In this sample we will build a line chart that reads its data in real time and gets updated each second.

Real-time WinForms Chart

We start by creating an empty WinForms project. We assume you have installed the Charting for WinForms component and you can see a list with chart components in the VisualStudio toolbox.

Drag the LineChart control and drop it on the form. You should now see references to the three libraries that you need automatically added to your project:

  • MindFusion.Charting;
  • MindFusion.Charting.WinForms;
  • MindFusion.Common;

1. Series and Data

Our chart will render time stamps at the X-axis. That’s why we choose the DateTimeSeries class to create the series for the chart. The constructor requires two lists – one with DateTime values and one with double values. They provide data for the X and Y axes respectively. We must also provide two more parameters: one for the start and one for the end of the time period.

List dates = new List();
List values = new List();

In order to mimic the real-time functionality we will use a timer. Our timer will generate a random number each second. At the beginning we will have a list with no values. Gradually, we will fill the values and once we reach the count of 100 we will start to delete the first value and add a new value at the end of the arrays.

That’s how we initialize the timer:

Random ran;
ran = new Random();         
        
Timer dataTimer = new Timer();
dataTimer.Tick += new EventHandler(GenerateData);
dataTimer.Interval = 1000;
dataTimer.Start();

Let’s look at the GenerateData method:

private void GenerateData(object sender, EventArgs e)
    {
         dates.Add(DateTime.Now);
         values.Add(2 + ran.NextDouble() * 8.0);

         if (dates.Count > 100)
         {
             dates.RemoveAt(0);
             values.RemoveAt(0);
         }
...
}

There we always add the current DateTime. Since the timer ticks every second that’s exactly what we want. Once the values are 100, we start to remove values at the beginning of the list.

Now let’s create the DateTime series. It requires parameters for the start and end of the period. We always allocate the first and last DateTime values as the bounds of the DateTime data for this series:

DateTimeSeries series = new DateTimeSeries(dates, values, dates[0], dates[dates.Count-1]);

Then we see if we have already added a Series and if so – replace it. If no Series has been added – add the new one:

if (lineChart1.Series.Count > 0)
       lineChart1.Series[0] = series;
else
       lineChart1.Series.Add(series);

By default the DateTimeSeries renders its values from the X-axis – the DateTime instances as labels at the X-axis. We can customize how they look with the DateTimeFormat property. The predefined DateTimeFormat members don’t have an option where the values are rendered as “14:23:34” as a time stamp. So, we choose as DateTimeFormat “CustomDateTime” and use the CustomDateTime to specify the format:

series.DateTimeFormat = DateTimeFormat.CustomDateTime;
series.CustomDateTimeFormat = "H:mm:ss"; 

2. The X-Axis

We want at each moment only the last 10 values to be visible. The other 90 or however they are should be rendered but the user must scroll to see them. We achieve with the MinValue and MaxValue properties of the DateTimeSeries:

series.MinValue = 0;
series.MaxValue = 0.1 * dates.Count;

In order to render only the last 10 series, we use the XAxis properties – MaxValue and MinValue Once the MaxValue of the DateTimeSeries is more than 1, which means that at least 10 values have been added, we adjust the visible range of values at the X-axis so that only the last 10 are visible:

if (series.MaxValue > 1)
  {
      lineChart1.XAxis.MaxValue = series.MaxValue;
      lineChart1.XAxis.MinValue = series.MaxValue - 1.0;
  }

We also set the Title for this axis:

lineChart1.XAxis.Title = "Time";

Let’s hide the numeric values from rendering at the top of the DateTime stamps with the ShowXCoordinates property:

lineChart1.ShowXCoordinates = false; 

3. The Y-Axis

By default the range of an axis is calculated based on the data. Let’s make our chart render the line graphics more to the beginning of the axis by increasing the MaxValue of the Y-axis while we fix the MinValue at 0:

lineChart1.YAxis.MinValue = 0;
lineChart1.YAxis.MaxValue = 20;
lineChart1.YAxis.Interval = 2;

We also change the axis Title and we use NumberFormat property to render the intervals with floating points:

lineChart1.YAxis.Title = "Visitors (in thousands)";
lineChart1.YAxis.NumberFormat = "N";

4. Grid

Let’s render vertical grid stripes. We want them to be dashed and light gray. We use GridType GridColor and GridLineStyle to customize the grid:

lineChart1.GridType = GridType.Vertical;
lineChart1.Theme.GridLineStyle = System.Drawing.Drawing2D.DashStyle.Dash;
lineChart1.Theme.GridLineColor = Color.FromArgb(192, 192, 192);

Note that GridColor and GridLineStyle are properties of the Theme property of LineChart add one extra – stop the grid stripes from moving around when the user scrolls the chart along the axis:

lineChart1.PinGrid = true;

5. Legend

The legend gets its labels from the Title property of a Series. In our case we set:

series.Title = "Server Requests";

We would like to change the legend background to make the legend easier to spot:

lineChart1.Theme.LegendBackground = new MindFusion.Drawing.SolidBrush(Color.FromArgb(120, 230, 230, 230));

We use a semi-transparent brush that let’s chart details be visible when the user moves the legend onto another chart element.

6. Line Colors

We want to render the line in red. We choose the MixedSeriesStyle class as the styling class for our application. You can use any other *SeriesStyle class that is appropriate in your case:

// assign a reb brush for the series
lineChart1.Plot.SeriesStyle = new MixedSeriesStyle()
    {  
         UniformStrokeThickness = 5,
         UniformStroke = new MindFusion.Drawing.SolidBrush(Color.Red),
         UniformFill = new MindFusion.Drawing.SolidBrush(Color.Red)
     };

With that our sample is complete. You can download the full code with the necessary charting dll-s from this link:

Download the WinForms Real-TimeChart Sample

About MindFusion Charting for WinForms: A versatile dashboard component that provides your WinForms application with the ability to create fascinating charts, interactive dashboards and practical gauges. The component combines a flexible API that allows custom combination of chart components to build any type of chart you want. You can add as many axes of any type you want, combine various chart series into a single chart with different data providers each. The control also supports pan and zoom, scroll, unlimited number of legends, grid and a dashboard panel. Linear and oval gauges complete the tool set and guarantee every feature you might need to build the perfect gauge, chart of any type or dashboard in WinForms is right at your fingertips. Learn more at https://mindfusion.eu/winforms-chart.html