Highcharts make percentage column chart - javascript

How can i make percentage column chart ?
Like this
http://www.highcharts.com/demo/column-basic
Not like this! http://www.highcharts.com/demo/column-stacked-percent
Thanks a lot for your help.

jsfiddle demo
var data = [{
name: 'A',
data: [72, 50, 52]
}, {
name: 'B',
data: [23, 41, 12]
}, {
name: 'C',
data: [18, 9, 11]
}, {
name: 'D',
data: [89, 46, 54]
}];
$('#container').highcharts({
chart: {
type: 'column'
},
xAxis: {
categories: ['Group 1', 'Group 2', 'Group 3']
},
yAxis: {
title: {
text: null
}
},
tooltip: {
shared: true
},
plotOptions: {
column: {
dataLabels: {
enabled: true
}
},
series: {
dataLabels: {
enabled: true,
formatter: function () {
var mychart = $('#container').highcharts();
var mytotal = 0;
for (i = 0; i < mychart.series.length; i++) {
if (mychart.series[i].visible) {
mytotal += parseInt(mychart.series[i].yData[0]);
}
}
var pcnt = (this.y / mytotal) * 100;
return Highcharts.numberFormat(pcnt) + '%';
}
}
}
},
title: {
text: 'Example'
},
series: data
});

Use this one:
chart.series[0].update({
dataLabels:{
enabled:true,
formatter:function() {
var mytotal = 0;
for (i = 0; i < chart.series.length; i++) {
if (chart.series[i].visible) {
for (j = 0; j < chart.series[i].yData.length; j++) {
mytotal += parseInt(chart.series[i].yData[j]);
}
console.log("Total : "+ i + " Total : "+ mytotal + " length" + chart.series[i].yData.length);
}
}
var pcnt = (this.y / mytotal) * 100;
return Highcharts.numberFormat(pcnt) + '%';
}
}
});

Related

HighCharts Stacked Column Adding Onclick Event to the chart

I am working on a Highchart column chart.
I need to add an onclick event to it so I can get data back when I click on the different columns.
Here is my current full code.
var chart;
$(function () {
$.ajax({
url: 'url here',
method: 'GET',
async: false,
success: function(result) {
themainData = result;
}
});
var mainData = [themainData];
var chList=[];
var voList=[];
var coList=[];
for (var i = 0; i < mainData[0].ch.length; i++) {
var obj = mainData[0].ch[i];
var chlst = obj.name;
var vl = obj.st.vo;
var cl = obj.st.co;
chList.push(chlst);
voList.push(vl);
coList.push(cl);
}
var chart = {
type: 'column',
};
var title = {
text: 'Vo and Co'
};
var xAxis = {
categories: chList
};
var yAxis ={
min: 0,
title: {
text: 'Ch'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
};
var legend = {
align: 'right',
x: -30,
verticalAlign: 'top',
y: 25,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
};
var tooltip = {
formatter: function () {
return '<b>' + this.x + '</b><br/>' +
this.series.name + ': ' + this.y + '<br/>' +
'Total: ' + this.point.stackTotal;
}
};
var plotOptions = {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black'
}
}
}
};
var credits = {
enabled: false
};
var series= [{
name: 'Vo',
data: voList
}, {
name: 'Co',
data: coList
}];
var json = {};
json.chart = chart;
json.title = title;
json.xAxis = xAxis;
json.yAxis = yAxis;
json.legend = legend;
json.tooltip = tooltip;
json.plotOptions = plotOptions;
json.credits = credits;
json.series = series;
$('#container').highcharts(json);
});
Where do I add the onclick event here?
You can add the click event on the chart, series, or point. I think it makes sense in your case to add the click event to the series.
var series= [{
name: 'Vo',
data: voList
events: {
click: function (event) {}
}
}, {
name: 'Co',
data: coList
}];
event.point is the point that is clicked on. See http://api.highcharts.com/highcharts/series%3Cbar%3E.events.click
This works for me,
chart: {
type: "bar",
},
title: {
text: "Stacked bar chart",
},
xAxis: {
categories: ["Apples", "Oranges", "Pears", "Grapes", "Bananas"],
},
yAxis: {
min: 0,
title: {
text: "Total fruit consumption",
},
},
legend: {
reversed: true,
},
plotOptions: {
series: {
cursor: 'pointer',
stacking: "normal",
events: {
click: function(event) {
alert(
this.name + ' clicked\n' +
'Alt: ' + event.altKey + '\n' +
'Control: ' + event.ctrlKey + '\n' +
'Meta: ' + event.metaKey + '\n' +
'Shift: ' + event.shiftKey
);
}
}
},
},
series: [{
name: "John",
data: [5, 3, 4, 7, 2],
},
{
name: "Jane",
data: [2, 2, 3, 2, 1],
},
{
name: "Joe",
data: [3, 4, 4, 2, 5],
},
],
});```

Highcharts donut percentage issue

I'm trying a visualization using Highcharts. I want to change outer donut's values. The values should be in percentage. For example, if y value is 23, data values are 11 and 12, but I want to display them as pecentage of y (11*100/23)...Is it possible?
Code
$(function () {
var a = [];
var colors = Highcharts.getOptions().colors,
categories = ['pool_ipv4_02','pool_ipv4_03','pool_ipv6_02','pool_ipv6_03','pool_ipv4_01','pool_ipv6_01'],
data = [{
y: 13.45,
color: colors[0],
drilldown: {
name: 'Pool1 Info',
categories: ['Used', 'Free'],
data: [12.73,0.72],
color: colors[0]
}
}, {
y: 20.38,
color: colors[1],
drilldown: {
name: 'Pool2 Info',
categories: ['Used', 'Free'],
data: [14.03,6.35],
color: colors[1]
}
}, {
y: 24.03,
color: colors[2],
drilldown: {
name: 'Pool3 Info',
categories: ['Used', 'Free'],
data: [12.73,11.3],
color: colors[2]
}
}, {
y: 11.77,
color: colors[3],
drilldown: {
name: 'Pool4 Info',
categories: ['Used', 'Free'],
data: [7.43,4.34],
color: colors[3]
}
},{
y: 19.33,
color: colors[4],
drilldown: {
name: 'Pool5 Info',
categories: ['Used', 'Free'],
data: [4.73,14.6],
color: colors[4]
}
},{
y: 11.04,
color: colors[5],
drilldown: {
name: 'Pool6 Info',
categories: ['Used', 'Free'],
data: [4.73,6.31],
color: colors[5]
}
}],
browserData = [],
versionsData = [],
i,
j,
dataLen = data.length,
drillDataLen,
brightness;
a[0] = data[0].drilldown.data[0]*100/(data[0].drilldown.data[0]+data[0].drilldown.data[1]);
a[1] = data[0].drilldown.data[1]*100/(data[0].drilldown.data[0]+data[0].drilldown.data[1]);
console.log(a[0]);
console.log(a[1]);
// Build the data arrays
for (i = 0; i < dataLen; i += 1) {
console.log(data[i]);
// add browser data
browserData.push({
name: categories[i],
y: data[i].y,
color: data[i].color
});
console.log(data[i].drilldown.data[0]);
console.log(data[i].drilldown.data[1]);
// add version data
drillDataLen = data[i].drilldown.data.length;
for (j = 0; j < drillDataLen; j += 1) {
brightness = 0.2 - (j / drillDataLen) / 5;
versionsData.push({
name: data[i].drilldown.categories[j],
y: data[i].drilldown.data[j],
color: Highcharts.Color(data[i].color).brighten(brightness).get()
});
}
}
// Create the chart
$('#container2').highcharts({
chart: {
type: 'pie'
},
title: {
text: 'BNG3 Pool Information'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
plotOptions: {
pie: {
shadow: false,
center: ['50%', '50%']
}
},
tooltip: {
valueSuffix: '%'
},
credits: {
enabled: false
},
series: [{
name: 'Pool',
data: browserData,
size: '60%',
dataLabels: {
formatter: function () {
return this.y > 5 ? this.point.name : null;
},
color: '#ffffff',
distance: -30
}
}, {
name: 'Utilization',
data: versionsData,
size: '80%',
innerSize: '60%',
dataLabels: {
formatter: function () {
// display only if larger than 1
return this.y > 1 ? '<b>' + this.point.name + ':</b> ' + this.y + '%' : null;
}
}
}]
});
});

HighChart isn't plotting data correctly

Hi I'm using high chart and the data is coming through okay however the date is not coming through on the x axis, I have a parameter in Data with the correctly formatted date and I'd like to use that on the x axis and popup, however I understand I need to use UTC datetime for it to order properly
https://imgur.com/32TyzvH
function buildAndUpdateTempChart() {
$.getJSON('server/getReadings.php', function (data) {
$('#chartContainer').highcharts('StockChart', {
chart:{
events: {
load: function(){
// set up the updating of the chart each second
//debugger;
// var series = this.series[0];
// //console.log('data is: ' + data);
// for(var i = 0; i < data.length - 1; i++){
// this.series[0].addPoint(data[i].temp, data[i].timestamp, true, true);
// this.series[1].addPoint(data[i].aTemp, data[i].timestamp, true, true);
// }
// setInterval(function () {
// //get tick
// var x = (new Date()).getTime(), // current time
// y = Math.round(Math.random() * 100);
// series.addPoint([x, y], true, true);
// }, 1000);
}
}
},
title: {
text: 'Temperature Sensor Readings'
},
yAxis: {
title: {
text: 'Degrees Celcius'
},
plotLines: [{
value: -10,
color: 'green',
dashStyle: 'shortdash',
width: 2,
label: {
text: 'Minimum tolerated.'
}
}, {
value: 20,
color: 'red',
dashStyle: 'shortdash',
width: 2,
label: {
text: 'Maximum tolerated.'
}
}]},
plotOptions: {
series: {
compare: 'percent'
}
},
series: [{
name: 'Temp',
data: (function () {
var temp = [];
for (var i = 0; i < data.length; i++) {
temp.push([
data[i].timestamp,
parseFloat(data[i].temp)
]);
}
return temp;
}()),
tooltip: {
valueDecimals: 2
}},
{
name: 'Ambient Temp',
data: (function () {
var aTemp = [];
for (var i = 0; i < data.length; i++) {
aTemp.push([
data[i].timestamp,
parseFloat(data[i].aTemp)
]);
}
return aTemp;
}()),
tooltip: {
valueDecimals: 2
},
}]
});
})
}
$(document).ready(function(){
buildAndUpdateTempChart(); //this is async so there rest of the app can continue to work
});
My guess is you need
xAxis: {
type: 'datetime'
},
in your code. Hope this helps.
this could help you, you have to specify xAxis a datetime
function buildAndUpdateTempChart() {
$.getJSON('server/getReadings.php', function (data) {
$('#chartContainer').highcharts('StockChart', {
chart:{
events: {
load: function(){
// set up the updating of the chart each second
//debugger;
// var series = this.series[0];
// //console.log('data is: ' + data);
// for(var i = 0; i < data.length - 1; i++){
// this.series[0].addPoint(data[i].temp, data[i].timestamp, true, true);
// this.series[1].addPoint(data[i].aTemp, data[i].timestamp, true, true);
// }
// setInterval(function () {
// //get tick
// var x = (new Date()).getTime(), // current time
// y = Math.round(Math.random() * 100);
// series.addPoint([x, y], true, true);
// }, 1000);
}
}
},
title: {
text: 'Temperature Sensor Readings'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Degrees Celcius'
},
plotLines: [{
value: -10,
color: 'green',
dashStyle: 'shortdash',
width: 2,
label: {
text: 'Minimum tolerated.'
}
}, {
value: 20,
color: 'red',
dashStyle: 'shortdash',
width: 2,
label: {
text: 'Maximum tolerated.'
}
}]},
plotOptions: {
series: {
compare: 'percent'
}
},
series: [{
name: 'Temp',
data: (function () {
var temp = [];
for (var i = 0; i < data.length; i++) {
temp.push([
data[i].timestamp,
parseFloat(data[i].temp)
]);
}
return temp;
}()),
tooltip: {
valueDecimals: 2
}},
{
name: 'Ambient Temp',
data: (function () {
var aTemp = [];
for (var i = 0; i < data.length; i++) {
aTemp.push([
data[i].timestamp,
parseFloat(data[i].aTemp)
]);
}
return aTemp;
}()),
tooltip: {
valueDecimals: 2
},
}]
});
})
}
$(document).ready(function(){
buildAndUpdateTempChart(); //this is async so there rest of the app can continue to work
});

Counting json data to create dynamic series in highchart line charts

I've got Json data like this :
q_table.php
[{"data":["2012-12-16; 0","2012-12-16; 23"]},{"name":"MSMDN1","data":[98.9914,99.5429]},{"name":"MSMDN2","data":[99.4577,99.5078]},{"name":"MSMDN3","data":[99.1454,99.4605]},{"name":"MSMDN4","data":[98.9663,99.3663,]},{"name":"MSMDN5","data":[104.97,91.4251]}]
I want to count the array data so the data look like this:
json_data = [0]; //data":["2012-12-16; 0","2012-12-16; 23"]
json_data = [1]; //"name":"MSMDN1","data":[98.9914,99.5429]
json_data = [2]; //"name":"MSMDN2","data":[99.4577,99.5078]
json_data = [3]; //"name":"MSMDN3","data":[99.1454,99.4605]
json_data = [4]; //"name":"MSMDN4","data":[98.9663,99.3663,]
json_data = [5]; //"name":"MSMDN5","data":[104.97,91.4251]}
How to counting those array from javascript?
This code below was worked, but as you see at the script part that get json data, i must declare series and categories manually
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 155
},
title: {
text: 'Revenue vs. Overhead',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: [''],
labels:
{
rotation: -90
}
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("q_table.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
options.series[3] = json[4];
options.series[4] = json[5];
//options.series[5] = json[6];
chart = new Highcharts.Chart(options);
});
});
Here is the script part that i change according to #SebastianBochan answer
$.getJSON("q_table.php", function(json)
{
var len = json.length
for(i=0;i<len;i++){
if(i===0){
options.xAxis.categories = json[i]['data'];
}else{
j = i-1;
options.series[j] = json[i];
}
}
chart = new Highcharts.Chart(options);
});
or any other way, very pleased..
Worked Script
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 155
},
title: {
text: 'Revenue vs. Overhead',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: [''],
labels:
{
rotation: -90
}
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("q_table.php", function(json)
{
var len = json.length
for(i=0;i<len;i++){
if(i===0){
options.xAxis.categories = json[i]['data'];
}else{
j = i-1;
options.series[j] = json[i];
}
}
chart = new Highcharts.Chart(options);
});
});
You need to parse check which line should be categories and which series. I simulated json as variable Take look:
var json = [{
"data": ["2012-12-16; 0", "2012-12-16; 23"]
}, {
"name": "MSMDN1",
"data": [98.9914, 99.5429]
}, {
"name": "MSMDN2",
"data": [99.4577, 99.5078]
}, {
"name": "MSMDN3",
"data": [99.1454, 99.4605]
}, {
"name": "MSMDN4",
"data": [98.9663, 99.3663]
}, {
"name": "MSMDN5",
"data": [104.97, 91.4251]
}];
var len = json.length
i = 0;
var options = {
xAxis: {
categories: []
},
series: []
}
for (i; i < len; i++) {
if (i === 0) {
var dat = json[i].data,
lenJ = dat.length,
j = 0,
tmp;
for (j; j < lenJ; j++) {
tmp = dat[j].split(';');
options.xAxis.categories.push(tmp[0]);
}
} else {
options.series.push(json[i]);
}
}
http://jsfiddle.net/UKfPm/
$.getJSON("q_table.php", function(json)
var options = {}; // whatever options you want to set, at least the container
options.series = new Array();
for(i=0;i< json.length;i++) {
options.series.push(json[i]);
}
chart = new Highcharts.Chart(options);
});

Highcharts: how to loop through array to add series

I am using Highcharts and need to loop though an array to display the different series so it displays as you can see here: http://jsfiddle.net/afnguyen/RUZb2/
Here is the code:
$(function () {
$('#container').highcharts({
title: {
text: 'Retaielr Clicks',
x: -20 //center
},
subtitle: {
text: 'Date',
x: -20
},
xAxis: {
categories: [32,33,24]
},
yAxis: {
title: {
text: 'Clicks'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Tesco',
data: [43, 27, 47]
}, {
name: 'Asda',
data: [48, 30, 45]
}, {
name: 'Boots',
data: [62, 43, 59]
}, {
name: 'Superdrug',
data: [63, 49, 64]
}, {
name: 'Ocado',
data: [43, 34, 48]
}, {
name: 'Waitrose',
data: [39, 24, 47]
}]
});
});
The data comes from 3 arrays:
weekNoArray[32,32,32,32,32,32,33,33,33,33,33,33,34,34,34,34,34,34] //this is used in the xAxis categories
retailerNameArray[Tesco,Asda,Boots,Superdrug,Ocado,Waitrose,Tesco,Asda,Boots,Superdrug,Ocado,Waitrose,Tesco,Asda,Boots,Superdrug,Ocado,Waitrose] //this needs to be each series name (but only one of each)
clicksArray[43,48,62,63,43,39,27,30,43,49,34,24,47,45,59,64,48,47] //i need to loop through each of these putting them in the data
Can anyone help in the best way to do this?
So what i m struggling with is how to loop in the series i.e. the following won t work:
for (var i = 0; i < data.length; i++)
{
var leadrow = data[i];
series: [{
name: retailerNameArray[i],
data: clicksArray[i]
}]
}
Edit
Below is the actual code that i am using
$.ajax({
type: "POST",
url: theUrl,
data: { 'manufacturer': manufacturer, 'country': country, 'category': category, 'startDate': startDate, 'endDate': endDate, 'chartType': chartType },
dataType: "json",
success: function (data) {
var retailerNameArray = [];
var clicksArray = [];
var weekNoArray = [];
var rowTotalArray = [];
var weekArray = [];
var columnTotalArray = [];
var cumTotalArray = [];
var weekCounterArray = [];
var overallClickCountArray = [];
var resellerShareArray = [];
var retailerCount = 0;
for (var i = 0; i < data.length; i++) {
var cumLeadrow = data[i];
//Only display on graph if not 0
if (cumLeadrow.RetailerClickCount > 0) {
// assign to array
retailerCount = cumLeadrow.RetailerCount;
var clicks = cumLeadrow.RetailerClickCount;
clicksArray.push(clicks);
var weekNum = cumLeadrow.WeekNo;
weekNoArray.push(weekNum);
var rowTotal = cumLeadrow.RowTotal;
rowTotalArray.push(rowTotal);
var date = cumLeadrow.WeeklyDate;
weekArray.push(date);
var columnTotal = cumLeadrow.ColumnTotal;
var retailer = cumLeadrow.RetailerDescription;
retailerNameArray.push(retailer);
var resellerShare = cumLeadrow.ResellerShare;
if (i < retailerCount) {
columnTotalArray.push(columnTotal);
resellerShareArray.push(resellerShare);
}
var cumTotal = cumLeadrow.CummulativeTotal;
cumTotalArray.push(cumTotal);
var weekCounter = cumLeadrow.WeeklyCounter;
weekCounterArray.push(weekCounter);
var overallClickCount = cumLeadrow.OverallClickCount;
overallClickCountArray.push(overallClickCount);
}
}
alert(clicksArray);
alert(weekNoArray);
alert(retailerNameArray);
var lowerChart = chartType.toLowerCase();
// Create the chart
$('#chartContainer').highcharts({
chart: {
type: lowerChart
},
title: {
text: manufacturer + ' Cumulative Leads in ' + country + "/" + category + '<br/> from ' + startDate + ' to ' + endDate
},
xAxis: {
categories: weekNoArray,
labels: {
rotation: -45,
align: 'right',
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Retailer Clicks'
},
stackLabels: {
enabled: false,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
legend: {
align: 'right',
x: -50,
verticalAlign: 'top',
y: 0,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColorSolid) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
},
credits: {
enabled: false
},
tooltip: {
formatter: function () {
return '<b>' + this.x + '</b><br/>' +
this.series.name + ': ' + this.y + '<br/>';
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
series: [{
name: retailerNameArray,
data: clicksArray
}]
});
The arrays have the values which I have detailed above. But currently they are in one series the fiddler example and the code below it is the outcome that i want so i need to loop through the arrays to add the series but i m not sure how to do this - i hope that makes sense
Many thanks
Example for you: http://jsfiddle.net/RUZb2/1/
This code will generate series from your arrays:
var weekNoArray = [32, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 33, 34, 34, 34, 34, 34, 34],
retailerNameArray = ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f'],
clicksArray = [43, 48, 62, 63, 43, 39, 27, 30, 43, 49, 34, 24, 47, 45, 59, 64, 48, 47],
series = [];
series = generateData(weekNoArray, retailerNameArray, clicksArray);
function generateData(cats, names, points) {
var ret = {},
ps = [],
series = [],
len = cats.length;
//concat to get points
for (var i = 0; i < len; i++) {
ps[i] = {
x: cats[i],
y: points[i],
n: names[i]
};
}
names = [];
//generate series and split points
for (i = 0; i < len; i++) {
var p = ps[i],
sIndex = $.inArray(p.n, names);
if (sIndex < 0) {
sIndex = names.push(p.n) - 1;
series.push({
name: p.n,
data: []
});
}
series[sIndex].data.push(p);
}
return series;
}

Categories