Horizontal Full Bar Chart in JavaScript

We use here MindFusion JavaScript library for Charts and Gauges to build this horizontal stacked bar chart that renders custom tooltips:

Run the sample from this link.

You can download the source code together with the libraries used from the link at the bottom of the post.

I. General Setup

We split our chart in two files – one is the web page that hosts an HTML Canvas element that will render the chart. The other file is a JavaScript code-behind file that contains the code for the chart.

We need to add reference to two JavaScript library files that provide the charting and drawing functionality that we need:

MindFusion.Common.js
MindFusion.Charting.js

We place them in a Scripts folder at the same level as our web page and JavaScript code behind file.

<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 the code-behind file that we call StackedBarChart.js:

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

Now we need to create an HTML Canvas element and we must provide it with an id so we can reference it in our JS code:

<canvas id="barChart" width="600px" height="400px"></canvas>

The size of the Canvas determines the size of the chart.

II. Chart Instance and General Settings

We add some namespace mappings that allow us to reference classes from the Chart library in a more consice manner:

var Charting = MindFusion.Charting;
var Controls = MindFusion.Charting.Controls;
var Collections = MindFusion.Charting.Collections;
var Drawing = MindFusion.Charting.Drawing;
var GridType = MindFusion.Charting.GridType;
var ToolTip = Charting.ToolTip;

Then we create an instance of the BarChart control. We need to get the Dom Element that corresponds to the Canvas that we’ve prepared for the chart:

var chartEl = document.getElementById('barChart');
chartEl.width = chartEl.offsetParent.clientWidth;
chartEl.height = chartEl.offsetParent.clientHeight;
var chart = new Controls.BarChart(chartEl, Charting.BarLayout.Stack);

The BarChart constructor supports a second argument that indicates the type of the bar chart to render.

We set the bar chart to horizontal with the horizontalBars property. We also make the bars thicker than normal – the property for this is barSpacingRatio It measures the thickness of the bars as a percente of the bar width.

chart.horizontalBars = true;
chart.barSpacingRatio = 0.2;

III. The Data Series

We want our chart to render labels as tooltips, inside the bars and also we want custom labels at the Y-axis. The predefined BarSeries class accepts 4 lists with data: one for bar data and three with labels inside the bars, at the top of the bars and at the X-axis. So, it is not an exact match for what we want to do and we need to customize it.

We will create our own custom BarSeries that we will call SeriesWithLabels. We will inherit the BarSeries class and override its constructor and getLabel members to provide the desired data for the desired type of labels.

We override the constructor by creating three new variables, which receive the data for the bars and the labels:

var SeriesWithLabels = function (barValues, innerLabels, yLabels) {
    Charting.BarSeries.apply(this, [barValues, innerLabels, yLabels]);
	
	this.yLabels = yLabels;
	this.innerLabels = innerLabels;
	this.values = barValues;
    
};

SeriesWithLabels.prototype = Object.create(Charting.BarSeries.prototype);

Note that before we do anything else in the new constructor we need to call the apply method of the BarSeries class to transfer the provided data to the base class. We also need to create a prototype of the new series and also define its constructor:

 Object.defineProperty(SeriesWithLabels.prototype, 'constructor', {
   	value: SeriesWithLabels,
   	enumerable: false,
   	writable: true
   });

Next we will override the getLabel method. This is the method that returns the correct label according to the requested label kind and the index of the label. We said we want to support inner labels, tooltips and Y-axis labels. So, we make sure our implementation of getLabel returns exactly those labels:

SeriesWithLabels.prototype.getLabel = function (index, kind) {
    if ((kind & Charting.LabelKinds.YAxisLabel) != 0 && this.yLabels)
        return this.yLabels.items()[index];

    if ((kind & Charting.LabelKinds.InnerLabel) != 0 && this.innerLabels)
        return this.innerLabels.items()[index];
	
	if ((kind & Charting.LabelKinds.ToolTip) != 0)
        return getPercentLabel(index, this);
   
    return "";
};

Getting the correct inner and top label is easy – we just return the label at the requested position. What is more work is building the tooltip. We want our tooltip to calculate the portion of the part in the stacked bar the mouse currently is over, to the entire bar. This means we need to calculate the data of all bar portions, which is a combination of the values at the requested position in all three bar series. We do this calculation in a separate method called getPercentLabel.

Before we get to the getPercentLabel method let’s create 3 instances of our custom SeriesWithLabels class:

var labels = new Collections.List([
	"POSITION", "SALARY", "LOCATION", "COLLEAGUES", "WORKTIME"
]);

// create sample data series
var series1 = new SeriesWithLabels(new Collections.List([123, 212, 220, 115, 0.01]), new Collections.List([123, 212, 220, 115, 0]), labels);
var series2 = new SeriesWithLabels(new Collections.List([53, 132, 42, 105, 80]), new Collections.List([53, 132, 42, 105, 80]), null);
var series3 = new SeriesWithLabels(new Collections.List([224, 56, 138, 180, 320]), new Collections.List([224, 56, 138, 180, 320]), null);

The third argument in the SeriesWithLabels constructor is the lists with labels at the Y-axis. We need just one list with labels and we set it with the first series. The other series take null as their third argument.

We need to create a collection with the series and assign it to the series property of the chart:

var series = new Collections.ObservableCollection(new Array(series1, series2, series3));
chart.series = series;

There is a special property called supportedLabels that is member of Series and tells the chart, what type of labels this Series needs to draw. In our case we need to indicate that the first series renders labels at the Y-axis, the inner labels and tooltips. The other two series render inner labels and tooltips:

series1.supportedLabels = Charting.LabelKinds.YAxisLabel | Charting.LabelKinds.InnerLabel | Charting.LabelKinds.ToolTip;
series2.supportedLabels = Charting.LabelKinds.InnerLabel | Charting.LabelKinds.ToolTip;
series3.supportedLabels = Charting.LabelKinds.InnerLabel | Charting.LabelKinds.ToolTip;

Now let’s get back to the method that calculates the tooltip:

function getPercentLabel(index, series)
{
	var value1 = series1.values.items()[index];
	var value2 = series2.values.items()[index];
	var value3 = series3.values.items()[index];
	
	var theValue = series.values.items()[index];	
	var result = theValue/(value1+value2+value3) * 100;
	
	return Number(result).toFixed(0) + "%";	
};

In it we calculate the sum of all data that is rendered by the stacked bar at the specified index. Then we convert the data to percent and format it to have no numbers after the decimal point. That gives us a little inacurracy sometimes, when the value gets rounded to the next number and the sum of all percents actually is 101. You might want to change the formatting to toFixed(2) if you want to see the exact number rendered.

IV. Axes and Tooltip

By default the X-axis shows a title and both axes render the auto scale for the data of the chart. We need to hide the scale and we also hide the ticks that are rendered at the interval values:

chart.xAxis.title = "";
chart.yAxis.title = "";
chart.showXCoordinates = false;
chart.showYCoordinates = false;
chart.showXTicks = false;
chart.showYTicks = false;

We don’t want our chart to render axes at all, so we will draw them with the color of the chart background. You can also draw them with a transparent brush:

chart.theme.axisStroke = new Drawing.Brush(Drawing.Color.knownColors.White);

The tooltip renders automatically when the user hovers a bar. We can customize it with the properties of the static Tooltip class:

ToolTip.brush = new Drawing.Brush("#fafafa");
ToolTip.pen = new Drawing.Pen("#9caac6");
ToolTip.textBrush = new Drawing.Brush("#5050c0");
ToolTip.horizontalPadding = 6;
ToolTip.verticalPadding = 4;
ToolTip.horizontalOffset = 76;
ToolTip.verticalOffset = 34;
ToolTip.font = new Charting.Drawing.Font("Verdana", 12);

We add some padding to the tooltip text and increase its font size. We also render the tooltip with a little offset that will place it inside the bar, ater the inner label.

V. Styling and Legend

Styling o the charts is done through instances of SeriesStyle derived classes. The instance is assigned to the seriesStyle property of the Chart In our case we want to color each bar in three sections. That means the portion of the bar that corresponds to the same series is colored in the same color for all its members. That kind of styling is supported by the PerSeriesStyle class. It accepts a list with brushes and strokes and paints all elements of the series corresponding to the index of the brush in the list with this brush:

// create bar brushes
var thirdBrush = new Drawing.Brush("#97b5b5");
var secondBrush = new Drawing.Brush("#5a79a5");
var firstBrush = new Drawing.Brush("#003466");

// assign one brush per series
var brushes = new Collections.List([firstBrush, secondBrush, thirdBrush]);
chart.plot.seriesStyle = new Charting.PerSeriesStyle(brushes, brushes);

The theme property is the main property for styling the chart. The Theme class exposes fields for customizing the appearance of all chart elements. We first adjust the font and size of the axis labels – remember we have labels only at the Y-axis:

chart.theme.axisTitleFontSize = 14;
chart.theme.axisLabelsFontSize = 11;
chart.theme.axisTitleFontName = "Verdana";
chart.theme.axisLabelsFontName = "Verdana";
chart.theme.axisLabelsFontSize = 14;
chart.theme.axisStroke = new Drawing.Brush(Drawing.Color.knownColors.White);

The labels inside the bars are called data labels and there are dataLabels*** properties that regulate their appearance:

chart.theme.dataLabelsFontName = "Verdana";
chart.theme.dataLabelsFontSize = 14;
chart.theme.dataLabelsBrush = new Drawing.Brush("#ffffff");

The dataLabelsBrush is also used when the legend labels are rendered. In order to make them visible we need to set a darker background for the legend:

chart.theme.legendBackground = new Drawing.Brush("#cccccc");
chart.theme.legendBorderStroke = new Drawing.Brush("#cecece");

The labels inside the legend are taken from the title property of the Series instances:

series.item(0).title = "CAREER START";
series.item(1).title = "MIDDLE OF CAREER";
series.item(2).title = "CAREER END";

Finally we should not forget to call the draw method that actually renders the chart:

chart.draw();

With this our costimization of the chart is done. You can download the source code of the sample and the MindFusion JavaScript libraries used from this link:

Download the Horizontal Stacked Bar Chart Sample: Source Code and Libraries

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.

A Poll Chart: A Stacked Bar Chart in Java Swing that Represents Results of a Survey – II

Here is a link to Part I: Overview of chart elements, the dashboard, plot and axes.

I. Bars Rendering

The bar graphics is rendered by a BarStackRenderer. It requires a collection of Series and we add four:

private ObservableList createSeries()
   {
      // Important series
	BarSeries series1 = new BarSeries(
	Arrays.asList(40.0, 30.0, 52.0, 62.0),
	Arrays.asList("20%", "15%", "26%", "31%"),
	null /* no top labels */);
        
        ............

  }

Each BarSeries has a list with the data, a list with the inner labels and no top labels. The BarStackRenderer renders in a single bar the values from the same index in each BarSeries e.g. the first bar renders the first double value in all BarSeries, the second bar renders the values on the second position in the series and so on. The BarRenderer itself has a few customizations:

barRenderer = new BarStackRenderer (createSeries());
barRenderer.setHorizontalBars(true);
barRenderer.setBarSpacingRatio(0.3);
barRenderer.setYAxis(yAxis);
barRenderer.setXAxis(xAxis);
barRenderer.setShowDataLabels(EnumSet.of(LabelKinds.InnerLabel));
barRenderer.setLabelFontSize(12.0);

Let’s not forget to add it to the Plot2D:

plot.getSeriesRenderers().add(barRenderer);

II. The Annotations

The labels at the X and Y axis are actually annotations – they are created by AnnotationRenderer instances. An AnnotationRenderer needs a collection of Series. For the Y-axis we use a SimpleSeries instance, which is created and used for the annotations and does not provide data for the bars:

private ObservableList createAxisLabels()
{
   return FXCollections.observableList(Arrays.asList(
	new SimpleSeries(null, null)
	{
        	public String getLabel(int index, LabelKinds kind)
		{
			return axisLabels[index];
		}
	
		public double getValue(int index, int dimension) { return index; }
			
		public int getSize() { return axisLabels.length; }

		public int getDimensions() { return 1; }

		public EnumSet getSupportedLabels() {
	        	return EnumSet.of(LabelKinds.YAxisLabel);
		}
				
		final String[] axisLabels = {
			"Accomodation", "University\nLocation", "Tuition\nPrice", "Quality of\nEducation" };
		}
	));
}

Here we indicate that this SimpleSeries provides labels for the YAxis with the getSupportedLabels override, which in our case returns LabelKinds.YAxisLabel. The label is returned by the getLabel method.

The annotations on the X-axis are rendered by a special class called CustomBarSeries. We implement the Series interface to return a set of predefined labels for each data value in this series:

public CustomBarSeries(List values, List innerLabels, List topLabels) {
	super(values, innerLabels, topLabels);
		
	this._values = values;
	double sum = 0;
	_stackedValues = new ArrayList(values.size());
		
	for(double val : values)
	{
	   sum += val;
	  _stackedValues.add(sum);
	}
	this._innerLabels = innerLabels;
	
}

We also take into consideration that the values rendered by the bar chart where this class is used are stacked – so we sum them and return the summed value when asked:

public double getValue(int index, int dimension) { 
		
	if( dimension == 0)
	  return _stackedValues.get(index);
	
        return _values.get(index);			
}

Then we return the predefined label at the given position and :

public String getLabel(int index, LabelKinds kind)
  {
	if(kind.equals(LabelKinds.InnerLabel))
	{
		return _innerLabels.get(index);
	}

	//else return the labels
	return axisLabels[index];
}
	
       final String[] axisLabels = {
		"Very Important", 
		"Somewhat\nImportant", "Slightly\nImportant", 
		"Not\nImportant" };

We create an instance of this CustomBarSeries and we assign it to the new AnnotationRenderer, that is responsible for the labels at the X-axis:

List sl = new ArrayList();
	sl.add(new CustomBarSeries(
	        Arrays.asList(25.0, 50.0, 50.0, 50.0),
		null,
		null));
	javafx.collections.ObservableList olss = FXCollections.observableList(sl);
	annotationRenderer1 = new AnnotationRenderer(olss);
	annotationRenderer1.setSeries(olss);

Let’s not forget to bind the AnnotationRenderer to the X-axis:

annotationRenderer1.setXAxis(xAxis);
annotationRenderer1.setShowDataLabels(EnumSet.of(LabelKinds.XAxisLabel));

Here is the final chart:

A stacked bar chart in Java Swing

Poll chart in Java Swing

That’s the end of this tutorial. Here is the link to download the full sample.

Download The Stacked Bar Chart in Java Sample

About Charting for Java: MindFusion.Charting for Java Swing is a multipurpose graphics library that lets you create and customize a large variety of chart types: bar, column, pie, doughnut, radar, polar etc., candlestick financial charts, gauges and dashboards with dynamic layout of their components. The library boasts a smart API which lets you combine and arrange multiple lots, axes, legends, images and other chart components. The chart appearance can be customized on multiple levels – from properties applied on a single element to global themes reused by all charts and series. Charts use a uniform Series interface for reading data and labels. You can implement the interface and create custom Series that matches your data source. Written in pure Java, this tool provides every type of Java Swing application with powerful charting capabilities. Read more about the component from here.

A Poll Chart: A Stacked Bar Chart in Java Swing that Represents Results of a Survey

Part I: Overview of chart elements, the dashboard, plot and axes.

Part II : Bar series and their drawing, rendering of custom labels with AnnotationRenderer-s.

In this blog post we will build a horizontal stacked bar chart in Java. To build the chart we use the Java chart library. We want to add a few custom elements to the chart and that’s why we will use the Dashboard control that gives us complete control over the chart elements that we use and how to arrange them.

I. Chart Elements

We use the following chart elements:

The image below gives you a visual presentation on how the components used are arranged:

The chart elements that build this stacked bar chart

The chart elements that build this stacked bar chart

The GridPanel has two rows and two columns. On the first row is the XAxisRenderer , that renders the X-axis, on the second row is the YAxisRenderer and the Plot with the BarStackRenderer .

II. The Dashboard

First, we create the Dashboard and add some styling to it with a Theme . The Theme class allows us to specify all appearance settings of a chart. We set only those that we want to use: the grid, the font:

Dashboard board = new Dashboard();
						
// set up appearance
Theme theme = board.getTheme();
theme.setPlotBorderStrokeThickness(0);
theme.setTitleBrush(new SolidBrush(Color.black));
theme.setGridColor1(Color.white);
theme.setGridColor2(new Color(240, 240, 240));
theme.setGridLineColor(new Color(255, 255, 255));

We add the TextComponent for the title and the GridPanel to the LayoutPanel of the Dashboard . The LayoutPanel is a vertical StackPanel and it arranges the elements exactly as we want them to appear:

board.getLayoutPanel().getChildren().add(title);
board.getLayoutPanel().getChildren().add(panel);

getContentPane().setLayout(new BorderLayout());
getContentPane().add(board, BorderLayout.CENTER);

We make sure the ContentPane of the JFrame that our Swing application uses applies the BorderLayout on the Dashboard and places it in the center which means it will stretch automatically when the user changes the size of the JFrame.

III. The Plot

The plot for the Chart is a Plot2D control. It will hold the BarRenderer and the two AnnotationRenderer -s. First, we set some general options: that the plot allows span, that it stretches in both directions and it will render a vertical grid.

//create the Plot2D
Plot2D out = new Plot2D();	
out.setAllowPan(true);
out.setHighlightStrokeDashStyle(DashStyle.Dash);
out.setHorizontalAlignment(LayoutAlignment.Stretch);
out.setVerticalAlignment(LayoutAlignment.Stretch);
out.setGridType(GridType.Vertical);

Then we go on with the styling options. The colors for the bars are set by a SeriesStyle class. We use an instance of the PerSeriesStyle which assings one brush and one fill for all elements in a single Series. We also set the HighlightStroke, which is the Brush that is used to highlight the bar that is selected:

List fills = fill();
List strokes = stroke();
out.setBackground(new SolidBrush(Color.white));
out.setVerticalScroll(true);
out.setSeriesStyle(new PerSeriesStyle(fills, strokes, Arrays.asList(5.0), null));		
out.setHighlightStroke(new SolidBrush(new Color(0, 0, 99)));

Finally we indicate the location of the plot in the GridPanel (more about the grid later):

//position in the grid
out.setGridColumn(1);
out.setGridRow(1);

IV. Axes

The axes are two – X and Y. The Y axis is present, but not visible. The X-axis is visible, aligned to the top and does not draw labels. The Axis are instances of the Axis class. They both use AxisRenderer instances to be drawn:

xAxis = new Axis();
xAxis.setMinValue(0.0);
xAxis.setMaxValue(300.0);
xAxis.setInterval(50);		
xAxis.setTitle("");		

The intervals of the axis are important because they determine the location of the grid stripes. The Axis sets some apperance properties like brush and font for the labels.

//the xAxisRenderer is bound to the xAxis
xAxisRenderer = new XAxisRenderer(xAxis);			
xAxisRenderer.setAxisStroke(new SolidBrush(Colors.Black));
xAxisRenderer.setAxisStrokeThickness(1.0);
xAxisRenderer.setLabelFontSize(12.0);
xAxisRenderer.setLabelBrush(new SolidBrush(Colors.Black));

Then comes the importnat part: we must tell this Axis that its labels come from an AnnotationRenderer , that it must not draw its intervals and that the labels are drawn above, rather than below the axis line:

//axis labels will be rendered by an AnnotationRenderer
xAxisRenderer.setLabelsSource(annotationRenderer1);
xAxisRenderer.setShowCoordinates(false);		
xAxisRenderer.setPlotBottomSide(false);

Finally, we specify its location and stretch settings:

//stretch this horizontal axis
xAxisRenderer.setHorizontalAlignment(LayoutAlignment.Stretch);
   	
//position in the Grid
xAxisRenderer.setGridColumn(1);
xAxisRenderer.setGridRow(0); 

The Y-axis is similar to the X-axis, so we won’t describe its settings here. Here is the final chart:

A stacked bar chart in Java Swing

Poll chart in Java Swing

This is the end of the Part I of this tutorial. In part II we’ll cover the BarRenderer with the BarSeries and the AnnotationRenderer-s. We will also briefly discuss the GridPanel.

You can download the complete source code of the sample from here:

Download The Stacked Bar Chart in Java Sample

About Charting for Java: MindFusion.Charting for Java Swing is a multipurpose graphics library that lets you create and customize a large variety of chart types: bar, column, pie, doughnut, radar, polar etc., candlestick financial charts, gauges and dashboards with dynamic layout of their components. The library boasts a smart API which lets you combine and arrange multiple lots, axes, legends, images and other chart components. The chart appearance can be customized on multiple levels – from properties applied on a single element to global themes reused by all charts and series. Charts use a uniform Series interface for reading data and labels. You can implement the interface and create custom Series that matches your data source. Written in pure Java, this tool provides every type of Java Swing application with powerful charting capabilities. Read more about the component from here.