Loading JSON string into a pie chart in highcharts - javascript

I need to include my json String output to a highcharts --pie chart category
but chart is not loading properly
This is my JSON string
var json = {"{\"name\":\"BillToMobile\"}":{"y":2.35},"{\"name\":\"Telenav\"}":{"y":13.59}}
Highcharts.chart('container', {
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: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: 'Brands',
colorByPoint: true,
data: json
}]
});
Below is the chart what I'm getting when loading this jsonstring.
Can any one help me with this because I'm new to this.Thanks in advance.

Try formatting your json this way
var json = [{name: "BillToMobile", y: 2.35}, {name: "Telenav", y: 13.59}]
To convert the json you have you can use this:
ES5 or earlier
var properJson = [];
for (var i in json) {
var item = JSON.parse(i);
for (var j in json[i]) {
item[j] = json[i][j];
}
properJson.push(item);
}
ES6
var properJson = [];
for (var i in json) {
var item = JSON.parse(i);
Object.assign(item, json[i]);
properJson.push(item);
}

Related

How to add dynamic data in highcharts pie chart in laravel

i am using pie chart of highcharts and i am not able to popluate dynamic data. Here is static form pie chart view
and code for above graph is
Highcharts.setOptions({
colors: projectColor.split(','),
});
Highcharts.chart('myChartStatics', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: 0,
plotShadow: false,
type: 'pie',
},
title: {
text: ''
},
navigation: {
buttonOptions: {
enabled: false
}
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
accessibility: {
point: {
valueSuffix: '%'
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
},
}
},
series: [{
type: 'pie',
innerSize: '60%',
name: 'Tasks',
colorByPoint: true,
data: [
[
"Inbox", 12
],
[
"Usage Guidance", 12
],
[
"Jobeegoo", 12
],
]
}]
});
now i want to add data array dynmaic on ajax call i am tried but it does not show graph
projectName = projectName.split(',')
totalTask = totalTask.split(',')
var loop = [];
for(var x = 0; x < projectName.length; x++){
loop.push([projectName[x] , parseInt(totalTask[x])]);
}
var data_value = JSON.stringify(loop);
console.log(data_value)
and console disply
[["inbox",128],["Usage Guidance",116],["FocusChain",0]]
tell me where i am wrong

Highcharts series doesnt show data and render the chart

I've got the following array which I want to use for draw pie chart with highchairs
and this is my code
var dataChart = [];
function getData()
{
return $.get('/report/charts-top-10-claimant')
.done(function(data) {
for (var i=0; i<data.length; i++) {
dataChart.push(data[i]);
}
});
}
getData();
$(function() {
console.log(dataChart);
$('#test').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: ''
},
tooltip: {
pointFormat: '{point.y} <b>({point.percentage:.1f}%)</strong>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</strong>: {point.y} ({point.percentage:.1f}%)',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
colorByPoint: true,
data: []
}]
});
$('#claimant-by-amount').on('click', function(e) {
var chart = $('#test').highcharts();
chart.series[0].setData(dataChart);
});
});
After loading the page and checking the error console saying "Uncaught Highcharts error #14: www.highcharts.com/errors/14 ". What am doing wrong, please help me out
If you click on the error in console it should redirect you to:
https://www.highcharts.com/errors/14
Which clearly states what is the problem.
Your y-values are strings when numbers are expected.

Highmaps, how to pass data from CSV to my world map

I have a large CSV file from which I need to select data from various columns and put them on a highmaps map.
How can I select the columns to use for the map? Lets say that I have country names at column 0, country codes at column 8 and number of things at column 1. How can I pass them to the map.
This is the CSV reader I use:
$.get('downloads/dg_mare_piwik_countries.csv', function(data) {
// Split the lines
var lines = data.split('\n');
$.each(lines, function (lineNo, line) {
var items = line.split(',');
if(lineNo !== 0) {
var iso_country = items[9],
name=items[0],
no_items = parseFloat(items[1]);
//options.series[0].data.push([visits]);
options.series[0].data.push({
name: name,
code3: iso_country,
value: no_items
});
}
});
var chart = new Highcharts.Map(options);
});
And the Map, copied from the highmaps example
var options = {
chart: {
renderTo: 'chart_container'
},
title: {
text: 'Fixed tooltip with HTML'
},
legend: {
title: {
text: 'Population density per km²',
style: {
color: (Highcharts.theme && Highcharts.theme.textColor) || 'black'
}
}
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
tooltip: {
backgroundColor: 'none',
borderWidth: 0,
shadow: false,
useHTML: true,
padding: 0,
pointFormat: '<span class="f32"><span class="flag {point.flag}"></span></span>' +
' {point.name}: <b>{point.value}</b>/km²',
positioner: function () {
return { x: 0, y: 250 };
}
},
colorAxis: {
min: 1,
max: 1000,
type: 'logarithmic'
},
series: [{
data: [],
mapData: Highcharts.maps['custom/world'],
joinBy: ['iso-a2', 'code'],
name: 'Population density',
states: {
hover: {
color: '#BADA55'
}
}
}]
};
Sorry for being perhaps too ignorant. I cannot short it out and any help will be deeply appreciated.
Thank you.

Highcharts Pie chart not accepting values

I'm using JavaScript to format the y values of a piechart to two decimal places but they are not appearing on the chart.
I need to take the percentage of each and then return them. fiddle
If the fiddle doesn't work this is my code.
$(function () {
var dataPie =[];
var abc =[{"val":"19981","name":"TOTAL"},{"val":"2051","name":"\"NATURAL GAS\""},{"val":"274","name":"\"OTHER FOSSIL FUELS\""},{"val":"8826","name":"\"DUAL FUEL\""},{"val":"5351","name":"\"NUCLEAR\""},{"val":"2628","name":"\"HYDRO\""},{"val":"501","name":"\"WIND\""},{"val":"350","name":"\"OTHER RENEWABLES\""},{"val":" ","name":"\"UNKNOWN\" "}];
$.each(abc,function(i,el)
{
var total = null;
if(el.name == "TOTAL"){
total = parseInt(el.val);
}else{
var p = parseInt(el.val) / total * 100;
dataPie.push({name :el.name,y: p});
}
});
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares January, 2015 to May, 2015'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.2f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.2f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: dataPie
}]
});
});
highcharts is capable to do that ,you need to simply use
{point.percentage:.2f}
See the fiddle, which has your last question's data updated here

How can i get pie chart with dynamic json data in Angular js

in my controller:
calling the web services if the services is success then get the data and pushinig the data into corresponding arrays
for(var i = 0; i < $scope.reportRangeList.length; i++)
{
count++;
if(angular.isNumber($scope.reportRangeList[i].businessName))
{
$scope.nameBusiness.push($scope.reportRangeList[i].businessName);
}else{
$scope.nameBusiness.push(+$scope.reportRangeList[i].businessName);
}
if(angular.isNumber($scope.reportRangeList[i].total1))
{
$scope.total.push($scope.reportRangeList[i].total1);
}else{
$scope.total.push(+$scope.reportRangeList[i].total1);
}
if(count == $scope.reportRangeList.length){
//$log.info("dddd"+ angular.toJson($scope.bname) )
$scope.fetchChart();
$scope.comlete = true;
}
}
and in fetchChart() :
$scope.fetchChart = function(){
$scope.chartConfig = {
title: {
text: ""
},tooltip: {
visible: true,
pointFormat: '<b>{point.name}</b>: {point.percentage:.1f} %',
},
options: {
chart: {
type: 'pie'
},
plotOptions: {
series: {
stacking: ''
},
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
},
showInLegend: true
},
},
legend: {
layout: 'vertical',
align: 'topleft',
verticalAlign: 'top',
borderWidth: 1,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
}
},
/*xAxis: {
categories: $scope.bname
},*/
credits: {
enabled: true
},
seriesDefaults: {
labels: {
template:'{series.name}: <b>{point.percentage:.1f}%</b>',
position: "outsideEnd",
visible: true,
background: "transparent"
}
},
series: [{
type: "pie",
name: "",
data: //$scope.bname,
[
$scope.nameBusiness,$scope.total
//['Firefox', 42.0]
/* ['IE', 26.8],
{
name: 'Chrome',
y: 14.8,
sliced: true,
selected: true
},
['Safari', 6.5],
['Opera', 8.2],
['Others', 0.7]*/
],
}],
loading: false
}
};
I would like to display the pie chart high chart with above data ,in for loop i am try to push only numbers but it shows single line of pie chart even the circle is not formed .with out converting to number type when I was push ,it shows http://www.highcharts.com/errors/14 error .One more thing I can share $scope.reportRangeList[i].businessName is string type and $scope.reportRangeList[i].total1 is number type .
The pie chart is working with hard coded data .Now how can I get pie chart with dynamic json data .
The problem is that businessName is string, and your data format expects to be number. I guess you have pairs businessName + total1 for each slice, that's correct? In that case, create one point for each of pairs:
series: [{
type: "pie",
name: "",
data: [
[ $scope.nameBusiness, $scope.total ] // [name, value] format
]
}],
As I'm working on angular 2, I'll provide solution related to it.. See if it can help you..
Firstly, create a function and call the service which will fetch
result from the server and store the result in a variable.
Then use that variable in data section of your graph in place of static data.
Hope it will solve your issue.

Categories