Draw piechart with highcharts using php array of data - javascript

I want to replace PHP array $os_array with JavaScript variable to send with different values. Like as var x =<?php echo $os_array; ?>; drawcharts($x); when alert var x result will be ['Internet Explorer 7',1],['Internet Explorer 8',1],['Outlook 2007',2]
var x="<?php echo $os_array;?>";
drawcharts(x);
function drawcharts(x){
$('#_shared_graphs').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
backgroundColor: '#f1f1f1'
},
title: {
text: 'OS'
},
tooltip: {
pointFormat: '{point.y} Using <b>{point.name}'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Sent Messag stat',
data: [x]
}]
});
}

well just define your js fkt:
function drawcharts(x) {
$('#_shared_graphs').highcharts({
...
series: [{
...
data: x
}]
});
}
then
var x =<?php echo json_encode($os_array); ?>;
drawcharts(x);
// reassign x
x = [ .... ];
drawcharts(x);

Related

Issue to add dynamic value in Highcharts jquery

I am facing an issue to add the dynamic value in Highcharts Jquery. I have two arrays like name and value
name/categoryname - ["ZYG", "BLA", "GAS", "LBE", "LIM", "EMB", "NAU"]
value/basevalue - [483.7932253,601.125844,680.2910403,886.7269613,548.3400347,630.8979143,0]
face the issue in passing the base value in. I tried to pass the value in the array and string type. The issue is not solved yet.
I used the bar chart to display. The coding is here. Normally coding works fine. The issue faced when I use dynamic value.
function displaychart(obj)
{
var categoryname = [];
$.each(obj['name'], function( key, value ) {
categoryname.push(value);
});
var ybasevalue = "[";
$.each(obj['basevalue'], function( key, value ) {
ybasevalue += value + ",";
});
ybasevalue += "]";
Highcharts.chart('container'+i, {
chart: {
type: 'bar'
},
title: {
text: 'Protein Sequence'
},
subtitle: {
text: 'Source'
},
xAxis: {
categories: categoryname,
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Proteomics',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ''
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 0,
y: 180,
floating: true,
borderWidth: 1,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: true
},
credits: {
enabled: false
},
series:[
{
name: 'Protein',
data: ybasevalue
},
]
});
}
}
I pass an array of Strings instead of an array of Numbers. Values inside single or double quotes are Strings in JavaScript.
So I use
var ybasevalue = [];
$.each(obj[i]['basevalue'], function( key, value ) {
ybasevalue.push(parseInt(value)); });

Highcharts percentage variability position

While percentage of each piece of pie chart reach 50%( or 52% and 48%) the position of percentage is changed, namely is not the same when was 16% and 84% each piece of graph.
The code that I use is:
Highcharts.chart('container1', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie',
options3d: {
enabled: true,
alpha:70,
beta: 0
}
},
title: {
text: ''
},
plotOptions: {
pie: {
allowPointSelect: false,
cursor: 'pointer',
size:100,
depth: 15,
dataLabels: {
textOverflow:'none',
enabled: true,
color:'black',
connectorColor:'transparent',
format:'{point.percentage:.1f}%',
distance:-30,
style:{
textShadow:false}
},
showInLegend: false
}
},
series: [{
type: 'pie',
name: 'ΑΞΚΟΙ - ΑΝΘΣΤΕΣ',
data: [
['Παρόντες', <?php
while ($row2 = mysql_fetch_assoc($res2)) {
while( $row1 = mysql_fetch_assoc($res1)){
$row3['COUNT(*)']=$row2['COUNT(*)'] - $row1['COUNT(*)'];
echo $row3['COUNT(*)'];
}
}?>],
['Απόντες', <?php
while( $row3 = mysql_fetch_assoc($res3)){
echo $row3['COUNT(*)'];
}
?>]
]
}]
});
There is a feature that can I use in order to make position of percentage constant?
Thanks in advance
You can set fixed position of the data labels by calling Highcharts.SVGElement.attr() function on each label:
events: {
load: function() {
var points = this.series[0].points;
points.forEach((p) => p.connector.destroy()); // destroy connectors
// set fixed position for both points
points[0].dataLabel.attr({
x: 300,
y: 100
});
points[1].dataLabel.attr({
x: 75,
y: 100
});
}
}
Live demo: http://jsfiddle.net/kkulig/8z3g1LLy/
API reference: https://api.highcharts.com/class-reference/Highcharts.SVGElement#attr

how to show mutipal dynamic highcharts based on json data

I want to use json data to construct mutipal pie charts. And put the pie chart inside class container, so for example:
data.data[0].usedPercentage=0,
data.data[1].usedPercentage=20,
data.data[2].usedPercentage=0,
the output pie chart should display like 0%, 20%, 0% ,
but now they display the same all in 0%, could anybody give some clues about that? Thanks a lot
$.ajax({
type: "GET",
url: 'http://XXX.XXX.XXX.XX',
dataType:'json',
contentType:"application/json",
success:function(data){
console.log(data);
var used = new Array();
for (var i = 0; i < data.data.length; i++) {
used[i]=data.data[i].usedPercentage;
pieIndex(used[i]);
projectList +="<div class='container'>pie</div>"
function pieIndex(used){
$(function () {
// Using classes to select multiple containers
var $containers = $(".container");
// You just set the configuration object once
var chartConfig = {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: ''
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: 'precentage',
colorByPoint: true,
data: [{
name: 'Unused',
y: 100-Number(used),
color: '#eeeeee',
sliced: true,
selected: true
}, {
name: 'Used',
y: Number(used),
color: '#f34s12',
selected: true
}]
}]
};
$containers.each(function() {
$(this).highcharts(chartConfig);
});
});
}
},
error:function(){
alert("connection error");
}
});
});
Each chart need a unique id on the container. Looks like you are overwriting those containers with the last chart. Try using a different id on each container div. For example:
projectList +="<div id='pie-chart-container-" + i + "' class='container'>pie</div>"

Highcharts - Pie Chart change slice colors dynamically

The chart calls in JSON file that hold a string(color) and integer(count). I want to change the color of the each slice in a pie chart according to what the JSON file holds. So if the JSON file is [["Green",1],["Red",44],["Yellow",30]] I would like the the "Green" slice to have the color of green...etc. I've tried:
plotOptions: {
pie: {
//colors: ['#739600', '#bb0826', '#fcc60A'],
formatter: function () {
if ('Green' === this.value) {
return '<span style="fill: #739600;">' + this.value + '</span>';
}
else if ('Red' === this.value) {
return '<span style="fill: #bb0826;">' + this.value + '</span>';
}
else if ('Yellow' === this.value) {
return '<span style="fill: #fcc60A;">' + this.value + '</span>';
}
}, ...
It's not working how I expected. http://jsfiddle.net/LazerickL/bvaxmcLr/4/
Any help would be appreciated.
UPDATE
I had to restructure my JavaScript to call $.getJSON function. So, how would I proceed to implement the color slices for my latest code below? Thanks for any help!
$(document).ready(function() {
var options = {
chart: {
renderTo: 'containter',
defaultSeriesType: 'pie',
options3d: {
enabled: true,
alpha: 45
}
},
title: {
text: null
},
credits: {
enabled: false
},
tooltip: {
pointFormat:
'{series.name}: <b>{point.y}</b>'
},
plotOptions: {
pie: {
//colors: ['#739600', '#bb0826', '#fcc60A'],
allowPointSelect: true,
cursor: 'pointer',
depth: 30,
showInLegend: true,
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.point.y;
}
}
}
},
series: [{
type: 'pie',
name: 'Amount',
data: []
}]
}
$.getJSON("js/test.json", function (json) {
options.series[0].data = json;
var chart = new Highcharts.Chart(options);
});
});
To set your colors on your pies you'll need to update how you're pushing things into the data array to include the color of your pie. I accomplish this by adding a field to your data array but you could use an if statement like you had in the function if you prefer.
Here is an updated fiddle: http://jsfiddle.net/bvaxmcLr/8/
Also, your placement of the formatter function is invalid. That formatter javascript only applies to data labels as far as I know.
The important change from your script is removing the formatter function and updating to this to push the color value onto each data point:
var data={'d':[
{'Status_Color':'Green', 'Corrective_Action_ID':3},
{'Status_Color':'Red', 'Corrective_Action_ID':5},
{'Status_Color':'Yellow', 'Corrective_Action_ID':10},
]};
$.each(data.d, function (key, value) {
var colorVal = '';
if(value.Status_Color=='Green'){
colorVal = '#739600';
}
if(value.Status_Color=='Red'){
colorVal = '#bb0826';
}
if(value.Status_Color=='Yellow'){
colorVal = '#fcc60A';
}
var temp = {name:value.Status_Color, color:colorVal, y:value.Corrective_Action_ID};
options.series[0].data.push(temp);
})
Here is the whole script:
$(function () {
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'pie',
options3d: {
enabled: true,
alpha: 45
}
},
title: {
text: null
},
subtitle: {
text: null
},
credits: {
enabled: false
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y:.1f}</b>'
},
plotOptions: {
pie: {
depth: 45,
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Amount',
data: []
}]
}
var data={'d':[
{'Status_Color':'Green', 'Corrective_Action_ID':3},
{'Status_Color':'Red', 'Corrective_Action_ID':5},
{'Status_Color':'Yellow', 'Corrective_Action_ID':10},
]};
$.each(data.d, function (key, value) {
var colorVal = '';
if(value.Status_Color=='Green'){
colorVal = '#739600';
}
if(value.Status_Color=='Red'){
colorVal = '#bb0826';
}
if(value.Status_Color=='Yellow'){
colorVal = '#fcc60A';
}
var temp = {name:value.Status_Color, color:colorVal, y:value.Corrective_Action_ID};
options.series[0].data.push(temp);
})
chart = new Highcharts.Chart(options);
});
});

Getting error when try to use external parameter to generate chart

I retrieve JSON data from server and put it in Highchart as series.I am facing this error:
Error: Invalid value for attribute y="NaN" highcharts.js : 9
The error happen if I send chartSeries parameter from callChart function.But if I copy chartSeries value and put it directly inside drawChart it able to display the chart.However there no problem for other parameter such chartCategory and chartTitle.
Here is my code:
function callChart(){
for (var i in jsonData){
console.log('#i '+i);
console.log('#subSegment i '+jsonData[i].subSegment);
var chartTitle= jsonData[i].subSegment;
console.log('categories '+ jsonData[i].categories);
var chartCategory= jsonData[i].categories;
console.log('series '+ JSON.stringify(jsonData[i].series));
var chartSeries=JSON.stringify(jsonData[i].series);
drawChart($('.chartContainer'),chartSeries,chartCategory,chartTitle);
break;}}
Here is the code of drawChart;
function drawChart(container,chartSeries,chartCategory,chartTitle) {
console.log('# test');
console.log('# chartSeries='+chartSeries);
console.log('# chartCategory='+chartCategory);
console.log('# chartTitle='+chartTitle);
//it works if I put the chartSeries directly here
/*chartSeries=[{"type":"column","stack":null,"pointPlacement":null,"name":"HDD","linkedTo":null,"id":"hdd","data":[30,30,70,90,37,200],"color":"greenColor","borderWidth":null},{"type":"column","stack":"old","pointPlacement":null,"name":"SSHD","linkedTo":null,"id":"sshd","data":[0,100,40,90,60,90],"color":"yellowColor","borderWidth":null},{"type":"column","stack":"old","pointPlacement":null,"name":"SSD","linkedTo":null,"id":"ssd","data":[50,100,40,90,60,100],"color":"blueColor","borderWidth":null},{"type":"column","stack":"forecast","pointPlacement":null,"name":"HDD","linkedTo":"hdd","id":null,"data":[30,80,40,100,60,90],"color":"greenColor","borderWidth":null},{"type":"column","stack":"forecast","pointPlacement":null,"name":"SSD","linkedTo":"ssd","id":null,"data":[30,80,40,100,60,90],"color":"yellowCollor","borderWidth":null},{"type":"spline","stack":null,"pointPlacement":null,"name":"Share","linkedTo":null,"id":null,"data":[30,80,40,100,60,90],"color":"black","borderWidth":null}] ;
*/
if (!container.length) {
return;
}
var chart = new Highcharts.Chart({
tooltip: {
enabled: true
},
credits: {
enabled: false
},
chart: {
renderTo: container[0],
style: {
fontFamily: '"Arial", "Helvetica", "sans-serif"',
fontSize: '12px',
fontWeight: 'bold'
},
marginLeft:60,
marginRight:65
},
title: {
text: chartTitle
},
xAxis: {
categories: chartCategory
},
yAxis: [{
min: 0,
title: {
text: 'Units in 000\' s'
},
stackLabels: {
enabled: false,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
}, { // Secondary yAxis
title: {
text: 'Share',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} %',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true,
min: 0,
max: 100
}],
legend: {
enabled:false
},
plotOptions: {
column: {
grouping: false,
stacking: 'normal',
pointWidth:30
},
series:{shadow:false}
}
,series:chartSeries
});
}
Thanks alot.
Okay, I found it already.
Instead pass JSON.stringify(jsonData[i].series) , directly pass jsonData[i].series.
Thanks

Categories

Resources