How to use json data as highcharts Pie Chart? - javascript

I've created an ajax request that returns data like this
Object
negative:3
neutral:3
positive:94
This is directly from console.log();
Im trying to create a pie chart using this data but when I try it doesn't draw the chart and nothing shows up except for the credits and no errors in the console either. But if I manually input data like this:
series: [{
name: 'Brands',
data: [
{ name: 'Positive', y: 94 },
{ name: 'Negative', y: 3 },
{ name: 'Neutral', y: 3 },
]
}]
it works no problem.
My code is:
function pieChart(data) {
// Make monochrome colors and set them as default for all pies
Highcharts.getOptions().plotOptions.pie.colors = (function () {
var colors = [],
base = Highcharts.getOptions().colors[0],
i;
for (i = 0; i < 10; i += 1) {
// Start out with a darkened base color (negative brighten), and end
// up with a much brighter color
colors.push(Highcharts.Color(base).brighten((i - 3) / 7).get());
}
return colors;
}());
// Build the chart
Highcharts.chart('pieChart', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares at a specific website, 2014'
},
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',
data: data
}]
});
};

The response you've received from server using ajax request is an object.
All you need is to create a json array from the response you've received.
var object={'positive':94,'neutral':2,'negative':2};
var data=[];
for(i in object){
data.push({"name":i,"y":object[i]});
}
And set it to highchart series.
series: [{
name: 'Brands',
data: data
}]

Related

How to fetch json array data into highcharts in angularjs

I want to display a bar graph using highcharts.I am devoloping an app in play framework(play-java),in which I return a response from the java api which contains data in json format.It contains a field 'name' which contains data like 'Data','Gadgets','Others' etc.I want the x axis of the chart to take these values from json array which gets returned in response.
Here is the code for the response in .js
for(var i=0;i<response.data.result.length;i++)
{
$scope.total=$scope.total+parseInt(response.data.result[i].item_price);
}
var j=0;
console.log(response.data.result);
while(j<response.data.result.length)
{
$scope.jsonArray=[{
name:response.data.result[j].category_name,
y: (parseInt(response.data.result[j].item_price)/$scope.total)*100,
}]
$scope.renderChart();
}
The code for bar graph
$scope.renderChart = function()
{
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Your Expenses'
},
subtitle: {
text: 'Your total spent money is '+$scope.total+'.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Money spent in percentage'
}
},
legend: {
enabled: false
},
credits: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: 'Categories',
colorByPoint: true,
data:$scope.jsonArray
}]
});
}
I know that I can't use the while loop in the response code mentioned.That's where i am looking help for.The y axis should calculate the percentage value .I want to generate 'names' for x axis and percentage for y axis of the chart.Thanks in advance..
All we have to do is to just initialize the jsonArray as empty before doing the looping.Add a for loop so that it iterates through the array and assigns the values appropriately.
The changed code
$scope.jsonArray = [];
for(var i=0;i<response.data.result.length;i++)
{
$scope.jsonArray[i]={
name:response.data.result[i].category_name,
y: (parseInt(response.data.result[i].item_price)/$scope.total)*100,
}
$scope.renderChart();
console.log(response.data.result[i]);
}
console.log($scope.jsonArray);
})
Anyway thanks....

draw pie chart from arrays in highcharts

I want to merge two arrays and display them on chart but can't do it. Please show the correct syntax of drawing that type of chart. If someobdy could provide a jsfiddle link it would be better for my understanding. Thanks.
$(function () {
var name = ['chrome','firefox','opera'];
var data = [11.22,81.54,6];
var final = [name,data];
$('#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:.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: "Results",
colorByPoint: true,
data:JSON.parse(final)
}]
});
});
You don`t have to merge arrays. You have to build new array with list of objects. Those objects should have structure based on arrays that you provided. Propriety "name", of each object, should get its value form the "name" array. Propriety 'y', in its turn should get value from the "data" array. Something like:
var final = [
{
name: 'chrome',
y: '11,22'
},
{
name: 'firefox',
y: '81.5'
},
{
name: 'opera',
y: '6'
}
]
That is how you can get it:
var name = ['chrome','firefox','opera'];
var data = [11.22,81.54,6];
var final = [];
for(var i=0; i < name.length; i++) {
final.push({
name: name[i],
y: data[i]
});
}
Here is the fiddle: http://jsfiddle.net/ujahc83h/2/

How do I make a Tornado Chart using Highcharts

I am trying to prepare a Tornado Chart using the column chart in Highcharts. Here is my fiddle.
My current code is:
$('#container').highcharts({
chart: {
type: 'columnrange',
inverted: true
},
title: {
text: 'Net Sales'
},
subtitle: {
text: 'MM $'
},
xAxis: {
categories: ['Annual Revenue', 'Number of Years', 'Annual Costs']
},
yAxis: {
title: {
text: 'MM $'
}
},
plotOptions: {
columnrange: {
dataLabels: {
enabled: true,
formatter: function () {
return this.y;
}
}
},
scatter:{
marker:{
symbol:'line',
lineWidth:11,
radius:8,
lineColor:'#f00'
}
}
},
legend: {
enabled: false
},
series: [{
name: 'Temperatures',
data: [
[12.15, 46.86],
[15.45, 42.28],
[27.77, 31.24]
]
},
{
name:'Base',type: 'scatter',data:[120],
}]
});
The problem is that the last series (Annual Costs) does not show, as it is in reversed order. Also, I'd like the Tornado Chart to look more like this:
Note that the labels in this chart are different from the actual values plotted. Also note that the bar in the center - in the example code, there would be a vertical line at 29.5. I would also like to support a combined uncertainty bar like the one at the bottom. Any suggestions would be greatly appreciated.
Your last bat is not showing, because first number is lower than second, see: http://jsfiddle.net/kErPt/1/
If you want to display another values at labels, then add that info first. Example:
data: [{
low: 12,
high: 15,
lowLabel: 35,
highLabel: 46
}, {
low: 2,
high: 35,
lowLabel: 15,
highLabel: 26
} ... ]
And then use dataLabels.formatter for series.
To add vertical line use plotLines.
I'm not sure what is the last bar called 'combined uncertainty'.
I've used Highcharts with separate series (thanks jlbriggs) to create a Tornado Chart: http://jsfiddle.net/uRjBp/
var baseValue = 29.5;
var outputTitle = "Net Sales";
var chart = new Highcharts.Chart({
chart: {
renderTo:'container',
//type:'column'
//type:'area'
//type:'scatter'
//type:'bubble'
},
credits: {},
exporting: {},
legend: {},
title: {
text: outputTitle
},
subtitle: {
text: "MM $"
},
tooltip: {
formatter: function() {
var msg = "";
var index = this.series.chart.xAxis[0].categories.indexOf(this.x);
var low = round(this.series.chart.series[0].data[index].y+baseValue);
var high = round(this.series.chart.series[1].data[index].y+baseValue);
if (this.x === "Combined Uncertainty") {
msg = "Combined Uncertainty in "+outputTitle+": "+low+" to "+high;
} else {
var lowLabel = this.series.chart.series[0].data[index].label;
var highLabel = this.series.chart.series[1].data[index].label;
msg = '<b>'+outputTitle+'</b> goes from '+ low +' to '+ high+'<br/> when '+this.x +
' goes from <br/> '+lowLabel+" to "+highLabel;
}
return msg;
}
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
formatter: function () {
var index = this.series.chart.xAxis[0].categories.indexOf(this.x);
if (this.series.userOptions.labels === undefined) {
return this.y+baseValue;
}
return this.key === "Combined Uncertainty" ? "":this.series.userOptions.labels[index];
}
}
}
},
xAxis: {
title: {
text: 'Factor'
},
allowDecimals:false,
categories: ['Annual Revenue', 'Number of Years', 'Annual Costs', 'Combined Uncertainty']
},
yAxis: {
title: {
text: 'MM $'
},
labels: {
formatter:function() {
return this.value+baseValue;
}
}
},
series:[{
name: 'Low',
grouping:false,
type:'bar',
data:[{y:12.15-baseValue, label:10},{y:15.45-baseValue, label:1},{y:31.25-baseValue, label:2},{y:12.15-baseValue, color:'#99CCFF', label: ""}],
labels:[10,1,2,]
},{
name: 'High',
grouping:false,
type:'bar',
data:[{y:46.86-baseValue, label:30},{y:42.28-baseValue, label:3},{y:27.77-baseValue, label:4},{y:46.86-baseValue, color:'#99CCFF', label:""}],
labels:[30,3,4,]
},
{
name: 'Median',
type: 'scatter',
data: [null,null, null,27-baseValue],
marker: {
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[3],
fillColor: 'white'
}
}]
});
function round(num) {
return Math.round(num*100)/100;
}
usually, this kind of chart is done using a separate series for the left and right portions
One way to do this is by setting one set of data as negative numbers, and then using the formatters to make the axis labels, datalabels, and tooltips display the absolute values
example:
http://jsfiddle.net/jlbriggs/yPLVP/68/
UPDATE:
to show a line as in your original chart, you can extend the marker symbols to include a line type, and use a scatter series to draw that point:
http://jsfiddle.net/jlbriggs/yPLVP/69/
If you don't want to have the extra code for the line marker type, you could use any of the other existing marker symbols for the scatter series.

Smallest pie can't be seen in HighCharts

How can I customize to make the smallest pie visible?
Youtube can't be seen as you can see from here: http://d.pr/i/nxeP
Here's my code ( my fetcher is in RAILS ):
$(function () {
//for donut
var data_series = <%= raw get_all_identities(#user) %> ;
var getColor ={
facebook: "#3d599b",
twitter: "#00abee",
instagram: "#736c59",
soundcloud: "#fa3d00",
youtube: "#d43c3b",
tumblr: "#3d5a71",
vine: "#00b589",
foursquare: "#0abadf",
linkedin: "#0abadf",
vimeo: "#1ab7ea",
fivehundredpx: "#000000",
wordpress: "#257ba0",
rdio: "#028ed4",
behance: "#000000",
flickr: "#ff0084"
};
$('#user_follower_chart').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: ''
},
credits: {
enabled: false
},
tooltip: {
pointFormat: '<b>{point.percentage:.2f}%</b>'
},
plotOptions: {
pie: {
dataLabels: {
enabled: false,
color: '#000000',
connectorColor: '#000000',
format: '<b>{point.name}</b>: {point.percentage:.2f} %'
},
startAngle: -90,
endAngle: 0
}
},
series: [{
type: 'pie',
name: 'Followers By Network',
allowPointSelect: true,
innerSize: '50%',
data: []
}]
});
var follower_chart, n, i, len;
for (i = 0, len = data_series.length; i < len; i++) {
n = data_series[i];
if (n[1] !== 0) {
follower_chart = $("#user_follower_chart").highcharts();
follower_chart.series[0].addPoint({
name: n[0],
y: n[1],
color: getColor[n[2]]
});
}
}
The red slice is visible, and appears to appropriately scaled.
I'm not sure what you expect to see for a slice at 0.2 %...
two things I would suggest:
1) set the borderWidth 0, and the slices will stand out a little more clearly.
2) this should really be a bar chart anyway.... if you make it a bar chart, you can set the minPointLength property so that small data points are still apparent.
example: http://jsfiddle.net/jlbriggs/4FxYg/
You can also try to use innerSize parameter
http://api.highcharts.com/highcharts#plotOptions.pie.innerSize

Formatting data for highcharts

I'm trying to make charts with Highcharts, but can't figure out why my data isn't in the right format.
When I use the following array as data my chart does his job.
fake = [['Joe', 0.1576]];
But when I try to make one by pushing elements like this it won't make a chart out of it.
name = 'Joe';
percentage = 0.1576;
element = [];
element.push(name, percentage);
graph.push(element);
When I compare them by getting them in console they seem totaly the same. But where is the difference between them that is causing the problem?
Edit:
Thanks to your help I found where it should go wrong, probably in the $.getJSON and var 'graph' that is not set properly?
graph = [];
$.getJSON("graph.php",function(data){
/* Loop through array */
for (var i = 0; i < data.length; i++) {
graph.push([data[i][1], Number(data[i][3])]);
}
});
$(function () {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Individuele productprijzen uiteengezet tegen de totaalprijs'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
format: '<b>{point.name}</b>: {point.percentage:.2f} %'
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: graph
}]
});
});
The data it gets is in JSON format made with json_encode in PHP.

Categories

Resources