highcharts - render bar graph with table data
JQuery highcharts - render bar graph with table data
HTML
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
<table class="table" id="datatable">
<thead>
<tr>
<th></th>
<th>Travellers</th>
</tr>
</thead>
<tbody>
<tr>
<th>jan</th>
<td>3</td>
</tr>
<tr>
<th>Feb</th>
<td>2</td>
</tr>
<tr>
<th>Mar</th>
<td>5</td>
</tr>
<tr>
<th>Apr</th>
<td>1</td>
</tr>
<tr>
<th>May</th>
<td>2</td>
</tr>
</tbody>
</table>
CSS
#datatable{display:block;}
JavaScript
$(function () {
$(document).ready(function() {
Highcharts.visualize = function(table, options) {
// the categories
options.xAxis.categories = [];
$('tbody th', table).each( function(i) {
options.xAxis.categories.push(this.innerHTML);
});
// the data series
options.series = [];
$('tr', table).each( function(i) {
var tr = this;
$('th, td', tr).each( function(j) {
if (j > 0) { // skip first column
if (i == 0) { // get the name and init the series
options.series[j - 1] = {
name: this.innerHTML,
data: []
};
} else { // add values
options.series[j - 1].data.push(parseFloat(this.innerHTML));
}
}
});
});
var chart = new Highcharts.Chart(options);
}
var table = document.getElementById('datatable'),
options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Title of Graph'
},
xAxis: {
},
yAxis: {
title: {
text: 'People departing'
}
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.y +' '+ this.x.toLowerCase();
}
}
};
Highcharts.visualize(table, options);
});
});