draw pie chart from arrays in highcharts - javascript

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/

Related

How to use json data as highcharts Pie Chart?

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
}]

Passing items into array and keeping format?

I am trying to do a drilldown chart like this one http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-drilldown/ and I am pretty close but I am trying loop my output of my items into an array and get the same format as the demo drilldown chart however it seems to only be getting the last set of items in my each loop. How can I keep the same format and pass them into my array? https://jsfiddle.net/pwbz0mxy/
chart_user_hours = {
chart: {
type: 'column',
renderTo: 'hours_chart_container'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total Hours'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.2f}'
}
}
},
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: [],
drilldown: {
series: []
}
};
data = '{"comparison":false,"title":"User Capacity Breakdown | January 2016 to July 2016","series":{"name":"User Hours Breakdown ","colorByPoint":true,"data":{"series":{"data":[{"name":"test","y":10,"drilldown":"test"},{"name":"test","y":154,"drilldown":"test"},{"name":"Large Move","y":29,"drilldown":"Large Move"},{"name":"Invoice 78554","y":20,"drilldown":"Invoice 78554"},{"name":"Small Move*","y":13,"drilldown":"Small Move*"}]}}},"drilldown":{"drilldown":{"series":[{"name":"test","id":"test","work_date":["2016-06-10"],"data":[10]},{"name":"test","id":"test","work_date":["2016-07-11","2016-07-10","2016-07-08","2016-07-06"],"data":[37,51,44,22]},{"name":"Large Move","id":"Large Move","work_date":["2016-07-04","2016-07-05","2016-07-08","2016-07-11"],"data":[9,8,7,5]},{"name":"Invoice 78554","id":"Invoice 78554","work_date":["2016-06-14","2016-06-24"],"data":[10,10]},{"name":"Small Move*","id":"Small Move*","work_date":["2016-06-30","2016-06-03"],"data":[3,9]}]}}}';
var obj = $.parseJSON(data);
chart_data = typeof obj.series.data.series != 'undefined' ? obj.series.data.series.data : '';
chart_user_hours['series'] = [{
name: obj.series.name,
data: chart_data
}];
$.each(obj.drilldown.drilldown.series, function( key, value ) {
chart_user_hours['drilldown']['series'] = [{
name: value.work_date,
id: value.id,
data: value.data
}];
});
var chart_hours = new Highcharts.Chart(chart_user_hours);
You are replacing the value of chart_user_hours['drilldown']['series'] each time in your loop. So actually it has to look like this:
Declaring the array – Before Loop
chart_user_hours['drilldown']['series'] = [];
Use push function of the array to add the value at the end of your array – In Loop
chart_user_hours['drilldown']['series'].push({
name: value.work_date,
id: value.id,
data: value.data
});

how to create a column char with highcharts where each column has a different color

I´ve a chart using highcharts, the only problem is that each column has the same column.
What should I do so each column has a different column.
Here is my code:
var charts = [];
$containers = $('#container1');
var datasets = [
{
name: 'Tokyo',
data: [49, 57]
}];
var cat = ['A', 'B'];
console.log(datasets);
$.each(datasets, function(i, dataset) {
console.log(dataset);
charts.push(new Highcharts.Chart({
chart: {
renderTo: $containers[i],
type: 'column',
marginLeft: i === 0 ? 100 : 10
},
title: {
text: dataset.name,
align: 'left',
x: i === 0 ? 90 : 0
},
credits: {
enabled: false
},
xAxis: {
categories: cat,
labels: {
enabled: i === 0
}
},
yAxis: {
allowDecimals: false,
title: {
text: null
}
},
legend: {
enabled: false
},
series: [dataset]
}));
});
Thanks in advance.
To have each column be a different color, all you have to do is set the colorByPoint property to true.
Reference:
http://api.highcharts.com/highcharts#plotOptions.column.colorByPoint
Alternatively you can make each column a separate series, which gives you additional levels of control.
OTOH, in the majority of cases, having each column a separate color serves no purpose except to clutter and confuse the data, and make the user work harder cognitively to interpret the chart.
If you want to highlight a single column for a particular reason, you can do that by adding the fillColor property to the data array:
Something like:
data:[2,4,5,{y:9,fillColor:'rgba(204,0,0,.75)',note:'Wow, look at this one'},4,5,6]
I finally found a way to show more than 1 color for each column:
var charts1 = [];
var $containers1 = $('#container1');
var datasets1 = [{
name: 'Dalias',
data: [29]
},
{
name: 'Lilas',
data: [1]
},
{
name: 'Tulipanes',
data: [15]
}];
$('#container1').highcharts({
chart: {
type: 'column',
backgroundColor: 'transparent'
},
title: {
text: 'Montos pedidos por división'
},
tooltip: {
pointFormat: '<span style="color:{series.color};" />{series.name} </span>:<b>{point.y}</b>',
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
},
series : {
cursor: 'pointer',
point: {
events: {
/*click: function() {
verDetalle("Especialidades,"+ this.series.name);
}*/
}
}
}
},
credits:{
enabled: false
},
yAxis: {
min: 0,
title: {
text: ''
}
},
xAxis: {
categories: ['División']
},
series: datasets1
});

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