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>"
Related
I have one Json with multiple array and foreach array I want to create Pie chart, but I don't know how to do it.
This is the array thet I have. And this is what I tried :
function Pie() {
$.getJSON("/Admin/Attivita/OreOggi", function (data) {
console.log(data);
var oreTecico = [];
var oreTecico = [];
var oreMalatia = [];
var oreStraordinario = [];
var oreInfortunio = [];
var oreFerie = [];
for (var i = 0; i < data.length; i++) {
nomeTecnico.push(data[i].nome);
oreTecico.push(data[i].odinario);
oreMalatia.push(data[i].malatia);
oreStraordinario.push(data[i].straordinario);
oreInfortunio.push(data[i].infortunio);
oreFerie.push(data[i].ferie);
};
// Build the chart
Highcharts.chart('zdravko', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Ore segnate oggi'
},
tooltip: {
pointFormat: '<b>{point.name}</b>: {point.y:.1f} h.'
},
accessibility: {
point: {
valueSuffix: '%'
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: nomeTecnico[0],
colorByPoint: true,
data: [{
name: '',
y:0,
sliced: true,
selected: true
}, {
name: 'Odinario',
y: oreTecico[0]
}, {
name: 'Malatia',
y: oreMalatia[0]
}, {
name: 'Straordinario',
y: oreStraordinario[0]
}, {
name: 'Infortunio',
y: oreInfortunio[0]
}, {
name: 'Ferie',
y: oreFerie[0]
}]
}]
});
});
}
It shows only the last "data". I want to make fo each array one pie. If i have 100 arrays I want 100 pies.
UPDATE:
I added this :
data.forEach(function (el) {
var chartData = [el.data1, el.data2];
var chartContainer = document.createElement('div');
document.getElementById('zdravko').append(chartContainer);
Highcharts.chart(chartContainer, {
series: [{
type: 'pie',
data: chartData
}]
});
});
The chartData is array of undefined objects.
Is it possible to make for or foreach inside Highcharts?
You need to use the Highcharts.chart method in a loop, for example:
var data = [{
data1: 12,
data2: 25
}, {
data1: 67,
data2: 11
}];
data.forEach(function(el) {
var chartData = [el.data1, el.data2];
var chartContainer = document.createElement('div');
document.getElementById('container').append(chartContainer);
Highcharts.chart(chartContainer, {
series: [{
type: 'pie',
data: chartData
}]
});
});
Live demo: http://jsfiddle.net/BlackLabel/x95pbw7j/
API Reference: https://api.highcharts.com/class-reference/Highcharts#.chart
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
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);
});
});
my task is to add series dynamically and keep updating their data, which is received by ajax calls.
i know series can be added dynamically by declaring highchart funciton global. and using series.addseries() function , and also data can be updated by using settimout request to ajax call and updating points by using series.addpoint() function.
i have done both the work separably. but when i combine both the technique, data is not added to highchart. i have done lot of research on this, and i am not finding reason for not adding the data. infact script hang the browser.
i have checked the series object, which show x-data and y-data are processed. only difference i find is isDirty field and isDirtydata field are set to true. dont know the reason.
here is the full code
var serverUrl = 'http://'+window.location.hostname+':8000'
Highcharts.setOptions({
global: {
useUTC: false
}
});
data={}
$(document).ready(function(){
$(function () {
console.log("highcharts")
$('#first').highcharts({
chart: {
type: 'spline',
//marginRight: 150,
marginBottom: 5,
events: {
load: requestData(data)
}
},
title: {
text: 'Server Monitroting Tool'
},
subtitle: {
text: 'Cpu usage, Memory Usage,Disk Usage,Mongo Usage'
},
xAxis: {
type: 'datetime',
categories: ['TIME'],
dateTimeLabelFormats : {
hour: '%I %p',
minute: '%I:%M %p'
}
},
yAxis:{
showEmpty:false
},
legend:
{
backgroundColor: '#F5F5F5',
layout: 'horizontal',
floating: true,
align: 'left',
verticalAlign: 'bottom',
x: 60,
y: 9,
shadow: false,
border: 0,
borderRadius: 0,
borderWidth: 0
},
series: {}
});
});
from_date=new Date().getTime()-60000;
function requestData(data)
{
if(!data)
{
console.log("default ")
}
else
{
console.log("requesting")
$.ajax({
url:serverUrl+'/api/fetch_params/',
type:'GET',
data:data,
success:function(response)
{
console.log("in success")
//data = {'type':TypeOfParameter,'hostname':hostname,'sub-type':sub_type,'param':sub_type_parameter,'from-date':from_date}
var id=data['sub-type']+data['param']
var series = chart.get(id)
shift = series.data.length > 100; // shift if the series is longer than 300 (drop oldest point)
response= $.parseJSON(response)
var x=data['sub-type']
all_data=response.response.data[x]
// console.log(new Date(from_date),'latest timestamp')
console.log(series)
console.log("data",all_data)
from_date=all_data[all_data.length-1][0]
// console.log(from_date)
// series.isDirty=false
// series.isDirtyData=false
for (var i = 0; i < all_data.length; i++)
{
series.addPoint({ x: all_data[i][0],y: all_data[i][1],id: i},false,shift);
}
console.log("series object",series)
// chart.redraw();
console.log(" parameter",data)
data['from-date']=from_date
console.log("data",series.data)
// console.log(chart)
setTimeout(requestData(data), 10000);
console.log("out of success")
},
cache:false,
error:function()
{
console.log("err")
}
});
}
}
$.ajax({
url:serverUrl+'/api/fetch_all_servers/',
type:'GET',
success:function(response){
response = $.parseJSON(response)
sd = response.response.all_servers
$('input[name=select_menue]').optionTree(sd)
},
error:function(){
console.log('error')
}
});
$('.param-button').live('click',function(e){
e.stopPropagation()
})
$('param-select').live('hover',function(){
$(this).find('.type-select').show()
});
$('.final_value').live('change',function(){
select_name = 'select_menue_'
param_list = []
var param=$('select[name="'+select_name+'"] option:selected').attr('value')
while(param){
param_list.push(param)
select_name += '_'
var param=$('select[name="'+select_name+'"] option:selected').attr('value')
}
console.log(param_list,"param_list")
from_date=new Date().getTime()-300000 //5 minute data
hostname=param_list[0]
TypeOfParameter= param_list[1]
sub_type_parameter=param_list[param_list.length-1]
data = {'type':TypeOfParameter,'hostname':hostname,'param':sub_type_parameter,'from-date':from_date}
var sub_type;
if(param_list.length==4){
sub_type=param_list[2]
data['sub-type'] = sub_type
}
else
{
sub_type=sub_type_parameter
}
// console.log(hostname,TypeOfParameter,sub_type,sub_type_parameter)
data = {'type':TypeOfParameter,'hostname':hostname,'sub-type':sub_type,'param':sub_type_parameter,'from-date':from_date}
requestData(data)
$('#loadingmessage').show(); // show the loading message.
chart = $('#first').highcharts();
if(TypeOfParameter=='cpu')
{
console.log("adding axis")
chart.addAxis({ // Primary yAxis
id:'Cpu_axis'+sub_type_parameter,
labels: {
formatter: function() {
return this.value;
},
style: {
color: '#89A54E'
}
},
title: {
text: "core "+ sub_type+ " "+sub_type_parameter,
style: {
color: '#89A54E'
}
},
lineWidth: 1,
lineColor: '#08F'
});
console.log("adding series")
chart.addSeries({
id:sub_type+sub_type_parameter,
name: "core "+sub_type+" "+sub_type_parameter,
data :[],
tooltip : {
valueSuffix: ' %'
},
yAxis:'Cpu_axis'+sub_type_parameter
})
console.log("series out")
}
if(TypeOfParameter=='memory')
{
chart.addAxis ({
id:'memory'+sub_type_parameter,
labels:{
formatter: function() {
return this.value +'%';
},
style: {
color: '#89C54F'
}
},
title: {
text:sub_type+" "+sub_type_parameter
},
lineWidth: .5,
lineColor: '#08F',
opposite: true
});
chart.addSeries({
id:sub_type+sub_type_parameter,
name: sub_type+'memory usage',
data: [],
tooltip: {
valueSuffix: '%'
},
yAxis:'memory'+sub_type_parameter
});
}
if(TypeOfParameter=='disk')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'disk Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'disk',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'disk',
data: []
}]
});
}
if(TypeOfParameter=='db')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'mongo Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'mmongo',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'mongo',
data: []
}]
});
}
if(TypeOfParameter=='redis')
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'second',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'redis Usage'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'redis',
margin: 80
}
},
series: [{
id:sub_type+sub_type_parameter,
name: 'redis',
data: []
}]
});
}
$('#loadingmessage').hide(); // hide the loading message
}
)
});
i am stuck on this problem for quite a while. and still not able to figure out the solution.
here is the full code link
someone please please help. feeling frustrated ..:-(
As you know the addPoint method is bit dangerous when dealing with quite lots points. It is recommended to disable redraw per point when dealing with many new points - more info http://api.highcharts.com/highcharts#Series.addPoint() , I notice you are doing that already in the loop statement, but why did you commented out? have you tried enabling again. Make sure chart.redraw works by adding a new redraw chart event, and set an alert or console log.
Also you may try using, below as part of ajax, instead of cache:false. I had some problems in past.
headers: { 'Cache-Control': 'no-cache' }
Cheers
getting data from php page and I am passing chartData array to pie(title,chartData) function as second parameter. Now chartData array is placing in data: [ chartData ] but it not working. But when I add manually with key then It work data: [ chartData[0],chartData[1], ]. But I don't want to mention it manually with key. I want to arry work automatically like data: [ chartData ]
What I have to do?
function createChart(chart) {
if ( chart == 'pie' ) {
var title = $("#chart-title").val();
/***************** Data Elements ****************/
var totalElements = $("#addMoreRowNo").val();
var chartData = new Array();
for(var j = 1; j <= totalElements; j++)
{
var key = $("#chart-pie-text_"+j).val();
var value = $("#chart-pie-percentage_"+j).val();
var data = [key, parseFloat(value)];
chartData[j-1] = data;
}
/***************** Data Elements ****************/
pie(title,chartData);
}
}
function pie(title,chartData) {
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: title
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
chartData
/*chartData[0],
chartData[1],*/
//['Active Postings (13)', 20.00],
]
}]
});
}
I'm pretty sure your problem can be solved by replacing
data: [
chartData
]
with
data : chartData
The way you're writing it, you're defining data as an array containing chartData, which itself is an array. The way you indicate you're testing it, though, is to get the items out of chartData and put each item into data, which results in a different structure.