Highcharts Pie Chart data formatting - javascript

I have a Pie Chart that gets its data from the file. In raw form, this is the data:
[{"name":"Dual","load":"20"},{"name":"Gas","load":"35"},{"name":"Other_Fossil_Fuels","load":"15"},{"name":"Nuclear","load":"12"},{"name":"Hydro","load":"8"},{"name":"Wind","load":"10"},{"name":"Other_Renwables","load":"10"}]
I am trying to make a method that formats this data correctly so that it can be used in the pie chart. However only the Names come through correctly, with all of the percentages set to 0. I have a feeling that it is because the raw data is saved as a String. But using parseInt() on the data before pushing doesn't help and the === check returns num. Here is the code i am trying to implement.
function setPieData(data){
var json = JSON.parse(data);
var fuelTypes = [{name: 'Dual',load:[]},
{name: 'Gas', load:[]},
{name: 'Other_Fossil_Fuels', load:[]},
{name: 'Nuclear', load: []},
{name: 'Hydro', load: []},
{name: 'Wind', load: []},
{name: 'Other_Renwables', load:[]}];
for(i=0; i < json.length; i++){
if(json[i].name == fuelTypes[i].name){
fuelTypes[i].load.push(parseInt(json[i].load));
}
if(fuelTypes[i].load === parseInt(fuelTypes[i].load, 10)){
alert("not num");
}else{
alert("num");
}
}
drawChart(fuelTypes);
}
function drawChart(stuff){
var globalDate = new Date();
var dMth = globalDate.getMonth() + 1;
var dDay = globalDate.getDate();
var dYr = globalDate.getFullYear();
var dStr = dMth + '/' + dDay + '/' + dYr;
title = "Real-time Fuel Mix " + dStr;
var seriesData= stuff;
Highcharts.setOptions({
colors: ['#C00000', '#FF0000', '#7F7F7F', '#FFC000', '#4F81BD', '#00B050', '#92D050']
});
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: title
},
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'
}
},
showInLegend: true
}
},
series: [{
name: "MI Power",
colorByPoint: true,
data: stuff
}]

create an Array and push your data like following
var dataPie =[];
var abc =your data //your json
$.each(abc,function(i,el)
{
dataPie.push({name :el.name,y: parseInt(el.load)});
});
use dataPie in your drawChart function.
see working fiddle here

Related

Cannot Remove Credits (Link) in HighChart's PieChar

I tried enable:false
but i cannot remove highchart's link from my chart (pie).
I got bit confused
This is my Javascript code.
<script language="JavaScript">
$(document).ready(function() {
var chart = {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
credits: false ///<= HERE I TRIED IT LAST
};
var title = {
text: ''
};
var tooltip = {
pointFormat: '{series.name}: <b>{point.y:.1f} Coupon(s)</b>'
};
var plotOptions =
{
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true,
borderWidth: 0
},
series: {
states: {
hover: {
halo:
{
size: 0
}
}
}
},
};
var series= [{
type: 'pie',
name: 'Source',
data: [
<?php
for($x=0; $x<sizeof($data); $x++)
{
echo $data[$x];
echo ",";
}
?>
]
}];
var json = {};
json.chart = chart;
json.title = title;
json.tooltip = tooltip;
json.series = series;
json.plotOptions = plotOptions;
$('#container').highcharts(json);
});
</script>
I tried to put this code at multiple positions. But it is showing no result.
Thanks in advance
var license = {
enabled: false
};
then at bottom:
json.credits = license;
previously asked and answered here
If you are using the free version, you CAN remove the attribution link, but if you are using free code the honour system is there so at least you can leave a "hat tip" to the developers as a thank you for saving you time.

How to Hide rest of the region when user clicks pie chart?

I have pie chart representation of user locations as below in figure 1,i have successfully made the representation working but how can i make the rest of users hidden as figure 2 when click any particular sector ?
Figure 1:
Figure 2:
Javascript :
$(function () {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'users location'
},
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: [{
type: 'pie',
name: 'Browser share',
data: [
['Africa', 45.0],
['Asia', 26.8],
{
name: 'Australia',
y: 12.8,
sliced: true,
selected: true
},
['Europe', 8.5],
['North America', 6.2],
['Others', 0.7]
]
}]
});
});
Fiddle Link
You can use plotOptions.series.point.events.click function to tell the chart exactly what to do after the click of a slice:
series: {
point: {
events: {
click: function () {
var index = this.x;
$('.highcharts-series-group g path').toggle();
$('.highcharts-series-group g path:nth-child(' + (index+1) + ')').toggle();
$('.highcharts-data-labels path').toggle();
$('.highcharts-data-labels path:nth-child(' + (index+1) + ')').toggle();
$('.highcharts-data-labels g').toggle();
$($('.highcharts-data-labels g').get(index)).toggle();
}
}
}
}
The first two toggles are for the slices themselves. $('.highcharts-series-group g path') refers to all the colored slices in the chart, and I changed back the one user just clicked by adding :nth-child.
The second pair of toggles are for the lines coming out of the slices connecting the datalabels to them. And the third pair is for the datalabels.
Here's the DEMO.
And example in pure Highcharts. As an another answer, use pie.point.events.click handler, to hide/show elements: http://jsfiddle.net/5oLmj00L/8/
point: {
events: {
click: function() {
var _self = this,
undef,
method = _self.clicked ? "show" : "hide";
Highcharts.each(this.series.data, function(p, i) {
if(p !== _self) {
// hide/show slice
if(p.graphic) {
p.graphic[method]();
}
// hide/show label
if(p.dataLabel) {
p.dataLabel[method]();
}
// hide/show connector
if(p.connector) {
p.connector[method]();
}
}
});
// set flag for next click:
_self.clicked = _self.clicked !== undef ? !_self.clicked : true;
}
}
}

Pie Chart is not coming with dynamic data in HIghChart

I am making a pie chart with json data but pie chart is not coming with data backend data.I am generating the data with this format which is actually the format given by HighCharts.I am pasting my code
function createChart(array){
//alert(array);
var arrJobName = [];
var arrRevenue = [];
for(var i=0; i<array.length; i++){
searchResultArray = array[i].split("$$##$$##");
//var label = '\''+ searchResultArray[1]+ '\'';
//var value = parseInt(searchResultArray[5]);
//arrJobName.push(searchResultArray[1]);
//arrRevenue.push(parseInt(searchResultArray[5]));
//alert(parseFloat(searchResultArray[5]))
// arrRevenue.push(['\''+ searchResultArray[1]+ '\'',""(parseFloat(searchResultArray[5]))]);
arrRevenue.push('['+searchResultArray[1]+","+parseFloat(searchResultArray[5])+']');
}
alert(arrRevenue)
//
$(function () {
$('.containerForDiagram').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
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: [{
type: 'pie',
name: 'Job By Revenue',
data: [
[arrRevenue]
//['Director - Inventory/Planning Systems',36800],['DevOps Engineer',20000], ['Java Developer',0],['Software Development Manager',0],['Sr. Business Analyst / Oracle Functional',0],['Product Manager Native Advertising',0],['Corporate Recruiter ',26000],['Sr. Oracle Supply Chain BA',0],['Network Engineer',0],['Sharepoint Programmer Analyst',0],['Commercial Manager - Mexico',0],['Commercial Manager Colombia',0],['Sr. Global Architect - End User Computing',29900],['Head of Marketing Peru',0],['Director, Sr Attorney',0]
this is the data i am getting with my code ]
}]
});
});
}
The data i am getting for the arrRevenue is given here.But the arrRevenue is not working when i am using it dynamically.I have tried all syntax.But no use still .Somebody please help.
The problem is with generating data. Required are two changes:
data assignment: data: [arrRevenue] -> data: arrRevenue
data generation: arrRevenue.push('['+searchResultArray[1]+","+parseFloat(searchResultArray[5])+']'); -> arrRevenue.push( [ searchResultArray[1], parseFloat(searchResultArray[5]) ] );

Highcharts tooltip not working

I cannot figure out how to get the 'to' and 'from' dates from my data into the tooltips. Tried various methods I found around SO. Anyone got any tips? I normally load data from CSV. Right now the data is hard-coded in the code.
var options = {
chart: {
zoomType: 'y',
borderWidth: '0',
borderRadius: '15',
renderTo: 'container',
inverted: true,
backgroundColor: {
linearGradient: [0, 0, 500, 500],
stops: [
[0, 'rgb(44, 44, 58)'],
[1, 'rgb(62, 62, 62)']
]
},
plotBackgroundColor: 'rgba(255, 255, 255, .9)'
},
tooltip: {
formatter: function () {
var point = this.point;
return '<b>' + point.category +
'</b><br/>' + Highcharts.dateFormat('%b %e, %Y', this.y) +
' - ' + Highcharts.dateFormat('%b %e, %Y', this.series[0]);
}
},
legend: {
enabled: false
},
title: {
text: 'EVMS Calendar'
},
xAxis: {
categories: []
},
plotOptions: {
series: {
grouping: false
}
},
yAxis: {
type: 'datetime',
minRange: '604800000',
startOnTick: false,
endOnTick: false,
title: {
text: ''
}
},
series: []
},
categories = [];;
//// This is the data processing section \\\\
// Hard Coded Data
var data ="valid data";
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
// Split the data by comma
// Get the number of items in the object (iLen)
// Series start
// Series type is columnrange
// Servies name is item 0 of the line (employees name)
$.each(lines, function (lineNo, line) {
var items = line.split(','),
iLen = items.length,
series = {
type: 'columnrange',
data: [],
name: items[0]
};
// Start categories
// for each items (0) get the row data (dates) and push to categories(line number, from and to)
categories.push(items[0]);
for (var i = 1; i < iLen; i += 2) {
var from = (new Date(items[i])).getTime(),
to = (new Date(items[i + 1])).getTime();
if (!isNaN(from) && !isNaN(to)) {
series.data.push([lineNo, from, to]);
}
};
options.series.push(series);
});
options.xAxis.categories = categories;
// Create the chart
var chart = new Highcharts.Chart(options);
ah, my bad. Its this.point.high / low. I found out by looking through the elements in chrome

Donut Slices Not Visible On Load

Here is a jsFiddle for an issue i have been trying to solve:
http://jsfiddle.net/kSSYg/
When the donut chart loads, the slices are not visible, but the legends are. When you hover over, they appear.
Has anyone else encountered this?
code
$(function () {
var chart;
$(document).ready(function() {
var colors = Highcharts.getOptions().colors,
categories = ['Security', 'Interfaces', 'SNMP', 'Management', 'General'],
name = 'Rule Categories',
data = [{"y":23.53,"drilldown":{"name":"Security","categories":["Pass","Fail"],"data":[11.77,11.77]}},{"y":23.53,"drilldown":{"name":"Interfaces","categories":["Pass","Fail"],"data":[23.53,0]}},{"y":23.53,"drilldown":{"name":"SNMP","categories":["Pass","Fail"],"data":[11.77,11.77]}},{"y":5.88,"drilldown":{"name":"Management","categories":["Pass","Fail"],"data":[5.88,0]}},{"y":23.53,"drilldown":{"name":"General","categories":["Pass","Fail"],"data":[23.53,0]}}];
// Build the data arrays
var browserData = [];
var versionsData = [];
for (var i = 0; i < data.length; i++) {
// add browser data
browserData.push({
name: categories[i],
y: data[i].y,
color: data[i].color
});
// add version data
for (var j = 0; j < data[i].drilldown.data.length; j++) {
var brightness = 0.2 - (j / data[i].drilldown.data.length) / 5 ;
versionsData.push({
name: data[i].drilldown.categories[j],
y: data[i].drilldown.data[j],
color: Highcharts.Color(data[i].color).brighten(brightness).get()
});
}
}
// Create the chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie'
},
title: {
text: 'Browser market share, April, 2011'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
plotOptions: {
pie: {
shadow: false
}
},
tooltip: {
valueSuffix: '%'
},
series: [{
name: 'Browsers',
data: browserData,
size: '60%',
dataLabels: {
formatter: function() {
return this.y > 5 ? this.point.name : null;
},
color: 'white',
distance: -30
}
}, {
name: 'Versions',
data: versionsData,
innerSize: '60%',
dataLabels: {
formatter: function() {
// display only if larger than 1
return this.y > 1 ? '<b>'+ this.point.name +':</b> '+ this.y +'%' : null;
}
}
}]
});
});
});​
Do you have to define your own colors? If you remove the two lines which are setting the colors, it works. See http://jsfiddle.net/kSSYg/2/
remove:
color: data[i].color
and
color: Highcharts.Color(data[i].color).brighten(brightness).get()
The reason these lines are not working is because your data array objects do not define the attribute "color"

Categories