Easy gauge chart with C3JS

When you produce data (in the field of industrial automation or IoT) you need to be able to visualize your data. I started out with the google charts library. It is really easy to use, but then I found out that you can only use this when connected to the internet. This could cause a potential problem when my customers are experiencing problems with their internet connection and you cannot show their data.

I was always charmed by D3 but compared to google charts it has a bigger learning curve. Then I found C3. C3 makes it easy to generate D3-based charts by wrapping the code required to construct the entire chart. We don’t need to write D3 code any more :-).

Below shows a gauge chart which displays values instead of the ratio (%). The default example is working with %, this actually does the trick to convert to values: format: function(value) { return value; }

<!DOCTYPE html>
<html>
<head>
	<link href="/static/c3.css" rel="stylesheet" type="text/css">
	<script charset="utf-8" src="static/d3.v3.min.js">
	</script>
	<script src="/static/c3.min.js">
	</script>
	<title></title>
</head>
<body>
	<div id="chart"></div>
	<script>
	   var chart = c3.generate({
	   data: {
	       columns: [
	           ['data', 91.4]
	       ],
	       type: 'gauge',
	       onclick: function (d, i) { console.log("onclick", d, i); },
	       onmouseover: function (d, i) { console.log("onmouseover", d, i); },
	       onmouseout: function (d, i) { console.log("onmouseout", d, i); }
	   },
	   gauge: {
	       label: {
	           format: function(value) { return value; },
	//            show: false // to turn off the min/max labels.
	       },
	//    min: 0, // 0 is default, //can handle negative min e.g. vacuum / voltage / current flow / rate of change
	   max: 300, // 100 is default
	   units: ' V',
	//    width: 39 // for adjusting arc thickness
	   },
	   color: {
	       pattern: ['#FF0000', '#F97600', '#F6C600', '#60B044'], // the three color levels for the percentage values.
	       threshold: {
	           unit: 'value', // percentage is default
	//            max: 200, // 100 is default
	           values: [30, 60, 200, 199]
	       }
	   },
	   size: {
	       height: 90
	   }
	});

	setTimeout(function () {
	   chart.load({
	       columns: [['data', 10]]
	   });
	}, 1000);

	setTimeout(function () {
	   chart.load({
	       columns: [['data', 50]]
	   });
	}, 2000);

	setTimeout(function () {
	   chart.load({
	       columns: [['data', 70]]
	   });
	}, 3000);

	setTimeout(function () {
	   chart.load({
	       columns: [['data', 299]]
	   });
	}, 4000);


	</script> 
</body>
</html>

Leave a Reply

Your email address will not be published.