Pie Graph Click in Highcharts - highcharts

I have a graph that opens up a colorbox when a piece of the pie is selected. However, I am trying to put permissions on this so that if a particular person is apart of an array of allowed pieces of the pie, then allow the click, otherwise ignore it.
Is there some advice you can give me that would point me in the right direction?
My array is called $allowedRegs, which would return NE, NW, SW, and the $person variable contains an employee Id number. The getRegMgr() function should be returning the ID number of the allowed employee. Is that allowed?
<script type="text/javascript">
$(document).ready(function() {
Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function(color) {
return {
radialGradient: { cx: 0.5, cy: 0.3, r: 0.7 },
stops: [
[0, color],
[1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
]
};
});
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
backgroundColor: null
},
title: {
text: ''
},
tooltip: {
pointFormat: '{series.name}: <b>${point.y}</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
}
}
},
series: [{
type: 'pie',
events: {
click: function(e) {
//window.console.log(this);
var point = e.point.name;
var explode = point.split("~");
var loc = explode[0];
var person = <?php echo $respid;?>
<?php
if(in_array($person, getRegMgr($allowedRegs))) {
?>
$.colorbox({ iframe:true, width:"90%", height:"90%", href: "reportDetails.php?dept=<?php echo $dept;?>&fy=<?php echo $selectedFy;?>&location="+loc+"&person="+person});
<?php } ?>
}
},
name: 'Total Revenue Earned:',
data: [
<?php
foreach($regionId as $region) {
//Get Data
$getData = mysql_query("SELECT SUM(hire_net) as rentalRev FROM dw_invoice LEFT JOIN dw_rep_zips ON dw_invoice.zip = dw_rep_zips.zip WHERE contract_type='H' and region = '".$region."' and invoice_date >= '".$fyStart."' AND invoice_date < '".$fyEnd."' GROUP BY region") or die("Cannot get data: " . mysql_error());
if(mysql_num_rows($getData) > 0) {
while($row = mysql_fetch_assoc($getData))
{
echo "['".getRegName($region)."', " . $row["rentalRev"]."], ";
}
}
}
?>
]
}]
});
});
</script>

Better is setting global variable in javascript, which value is getting form PHP. Then only what you need is add if in click event.
if(globalVariablePermission)
//do this
else
return false;

Related

HighChart data table keeps adding number of tables at bottom on every call

I am using HighChart library to show Pie Chart on my page, I am keeping showTable always true to show every time.
The problem is whenever data binds to charts using JQuery Ajax post dynamically, i see proper data in chart but also it keeps adding new data table everytime at the bottom. E.g. First time there will be only one table, after another call there will be two tables added and so on. Why Hightcharts not updating the same table again or is there a way to kill any existing table.?
hc = Highcharts.chart(chartName, {
chart: {
type: 'pie',
options3d: {
enabled: false,
alpha: 45
},
style: {
color: '#575962'
}
},
title: {
text: title,
style: {
color: '#575962',
fontweight: '400'
}
},
subtitle: {
text: 'Current Month(Top 10)'
},
plotOptions: {
pie: {
innerSize: 100,
depth: 45,
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
credits: {
enabled: false
},
exporting: {
showTable: true
},
series: [{
name: 'Price',
data: [],
dataLabels: {
formatter: function () {
//const point = this.point;
//return '<span style="color: #575962;font-size:11px;font-weight: 400">' +
// point.name + ': $' + point.y + '</span>';
}
}
}]
});
Why Hightcharts not updating the same table again or is there a way to kill any existing table.?
I have achieved this by removing the series on each call and adding them again with new data. Hope this helps if anyone else looking and couldn't find any other answer.
//Removing Series
while (hc.series.length > 0) {
hc.series[0].remove(false);
}
//Adding new Series
hc.addSeries({
name: 'Price',
data: [],
dataLabels: {
formatter: function () {
const point = this.point;
return '<span style="color: #575962;font-size:11px;font-weight: 400">' +
point.name + ': $' + point.y + '</span>';
}
}
});
//Binding Series data
var res = result.Data.slice(0, 10);
res.forEach(function (element, index) {
hc.series[0].addPoint({
name: element.ResourceGroupName,
y: element.TotalMonthlyPrice,
});
});

how to put some data option key url on Highchart?

i tried add some url on my chart bar so when it click it goes to another page
but i have no idea where i should put the option key. Please give some advice, here's my code
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function () {
location.href = 'https://xxxxxxxx.com/ratnik2/chart_month.php?m=' +
this.options.key;
}
}
}
},
column: {
stacking: 'normal',
pointPadding: 0.2,
borderWidth: 0,
dataLabels:
{
enabled:true
}
}
},
series: [ {
name: 'Surat Terbit',
data: [";
$query->execute("select month(tanggal), count(*) as jumlah
from surat where year(tanggal)=year(now())
and tgl_ttd is not null
group by month(tanggal)
order by month(tanggal) asc
");
while ($row = $query->fetch()){
$isi .= $row["jumlah"].",";
}
$isi .="]
name: '',
key: ''
}]
});
Take a look at this demo: http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-point-events-click-url/
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function () {
location.href = 'https://en.wikipedia.org/wiki/' +
this.options.key;
}
}
}
}
},

Highcharts pie graph with two rings filtering

I have a pie chart here that I'm working on that has two "rings" in it. The inner ring is just a summation of the outer ring for that given category.
Here is the fiddle: http://jsfiddle.net/jeffvan576/a50859s7/1/
(Apologies for the code - it's a bit of a mess right now)
I've been messing around with the showInLegend functionality but that will (as it's intended) only pull out the given piece of the pie chart. So, for instance, if you click google, it pulls out that piece of the pie chart but leaves the outer ring. To completely eliminate google you need to click "google", "match", "funds added" and "organic" for google.
My question is, is there a way to remove the entire slice (google and all it's children) from the chart at once?
The issue is that in order to get the functionality / layout on the chart that I need, this pie chart is actually built out of two series.
ShowInLegend code:
pie: {
shadow: false,
center: ['50%', '50%'],
showInLegend: true
}
I started building a custom visibility function at the bottom of the fiddle but dialed it back until I understood showInLegend a little better.
Thanks in advance!
you can achieve this by getting name of series on which clicked by using http://api.highcharts.com/highcharts#plotOptions.pie.events.click of plotoptions -> pie.
after that calling visibility function to hide Channel series along with its children to hide/show.
Event:
plotOptions: {
pie: {
shadow: false,
center: ['50%', '50%'],
showInLegend: true,
point: {
events: {
}
}
}
}
also static line put into visibility function to hide/show need to remove.
// chart.series[0].data[0].visible = false;
http://jsfiddle.net/a50859s7/27/
Full code:
$(function () {
var dataObject = {
facebook: {
'organic': 10.85,
'match': 7.35,
'fundsadded': 33.06,
'total': 0,
'status': 'disabled'
},
google: {
'organic': 10.85,
'match': 7.35,
'fundsadded': 33.06,
'total': 0,
'status': 'disabled'
},
email: {
'organic': 10.85,
'match': 7.35,
'fundsadded': 33.06,
'total': 0,
'status': 'enabled'
},
colorSelections: {
'facebook': '#3b5998',
'google': '#dd4b39',
'disabled': '#c6c6c6'
}
}
var sumObjects = function () {
for (var channel in dataObject) {
if (channel === 'colorSelections') continue;
var sum = 0;
for (var key in dataObject[channel]) {
if (key === 'status') continue;
sum += dataObject[channel][key];
}
dataObject[channel].total = sum;
}
}
sumObjects();
var colors = Highcharts.getOptions().colors,
categories = ['Facebook', 'Google', 'Email'],
data = [{
y: dataObject.facebook.total + 1,
//color: dataObject.facebook.status === 'disabled' ? dataObject.colorSelections.disabled : dataObject.colorSelections.facebook,
color: 'rgba(59, 89, 152, 0.3)',
drilldown: {
name: 'Facebook',
categories: ['organic', 'match', 'funds added'],
data: [
dataObject.facebook.organic,
dataObject.facebook.match,
dataObject.facebook.fundsadded],
color: 'rgba(59, 89, 152, 0.3)'
},
}, {
y: dataObject.google.total + 1,
color: '#dd4b39',
drilldown: {
name: 'Google',
categories: ['organic', 'match', 'funds added'],
data: [
dataObject.google.organic,
dataObject.google.match,
dataObject.google.fundsadded],
color: '#e46f61'
}
}, {
y: dataObject.email.total + 1,
color: colors[2],
drilldown: {
name: 'Email',
categories: ['organic', 'match', 'funds added'],
data: [
dataObject.email.organic,
dataObject.email.match,
dataObject.email.fundsadded],
color: colors[2]
}
}],
browserData = [],
versionsData = [],
i,
j,
dataLen = data.length,
drillDataLen,
brightness;
// Build the data arrays
for (i = 0; i < dataLen; i += 1) {
// add browser data
browserData.push({
name: categories[i],
y: data[i].y,
color: data[i].color
});
// add version data
drillDataLen = data[i].drilldown.data.length;
for (j = 0; j < drillDataLen; j += 1) {
brightness = 0.2 - (j / drillDataLen) / 5;
versionsData.push({
name: data[i].drilldown.categories[j],
y: ((data[i].drilldown.data[j] / browserData[0].y) * 100),
color: Highcharts.Color(data[i].color).brighten(brightness).get()
});
}
}
// Create the chart
$('#container').highcharts({
chart: {
type: 'pie'
},
title: {
text: 'Browser market share, April, 2011'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
plotOptions: {
pie: {
shadow: false,
center: ['50%', '50%'],
showInLegend: true,
point: {
events: {
click: function (event) {
var seriesIndex;
var secondarySeriesIndex;
if (this.name == 'Facebook') {
seriesIndex = 0;
secondarySeriesIndex = 0;
} else if (this.name == 'Google') {
seriesIndex = 1;
secondarySeriesIndex = 3;
} else if (this.name == 'Email') {
seriesIndex = 2;
secondarySeriesIndex = 6;
}
var chart = $('#container').highcharts();
visibility(chart.series[0].data[seriesIndex]);
visibility(chart.series[1].data[secondarySeriesIndex]);
visibility(chart.series[1].data[secondarySeriesIndex + 1]);
visibility(chart.series[1].data[secondarySeriesIndex + 2]);
}
}
}
}
},
tooltip: {
valueSuffix: '%'
},
series: [{
name: 'Channel',
type: 'pie',
data: browserData,
size: '120%',
dataLabels: {
formatter: function () {
return this.y > 5 ? this.point.name : null;
},
color: 'white',
distance: -30
}
}, {
name: 'Added',
type: 'pie',
data: versionsData,
size: '120%',
innerSize: '80%',
dataLabels: {
formatter: function () {
// display only if larger than 1
return this.y > 1 ? '<b>' + this.point.name + ':</b> ' + this.y + '%' : null;
}
}
}]
});
var visibility = function (series) {
series.visible ? series.graphic.hide() : series.graphic.show();
// chart.series[0].data[0].visible = false;
}
var chart = $('#container').highcharts();
$('.update').click(function () {
visibility(chart.series[0].data[0]);
visibility(chart.series[1].data[0]);
visibility(chart.series[1].data[1]);
visibility(chart.series[1].data[2]);
chart.redraw();
});
function synchronizePieSeries(event, slice) {
debugger;
$(chart.series[1].data).each(function (i, e) {
if (slice.name === e.name) {
slice.visible ? e.graphic.hide() : e.graphic.show();
}
});
}
//$('.update').click(function (event) {
// synchronizePieSeries(event, this);
//});
});

Function to create Highcharts where the series has the correct prototype

I am attempting to write a function to add a highchart to a page and a function that can update the data for that chart based on a streaming API. I added a setInterval to simulate the streaming api.
The issue occurs on line 80. I believe it is because I have not set the series array with the chart object properly. When I need to add new data via 'addPoint', the prototype is not there. What am I missing in my AddChart function that wires the series up to highcharts?
FIDDLE:
http://jsfiddle.net/puto3Lg0/2/
$(function () {
$(document).ready(function () {
var metrics = [];
Highcharts.setOptions({
global: {
useUTC: false
}
});
function AddChart(metric) {
$("#divMain").append('<div id="' + metric.key + '" style="min-width: 310px; height: 200px; margin: 0 auto"></div>');
$('#' + metric.key).highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
},
title: {
text: metric.Title
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Messages'
},
plotLines: [
{
value: 0,
width: 1,
color: '#808080'
}
]
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: metric.series
});
};
function ParseData(message) {
var jsonObj = JSON.parse(message);
$.each(jsonObj.Metrics, function(index, value) {
var metricName = value.Metric.Name.replace(' ', '');
if (metrics[metricName] == undefined) {
metrics[metricName] = {
"title": value.Metric.Name,
"key": metricName,
"series": [
{
name: value.Metric.Name,
data: []
}
],
}
AddChart(metrics[metricName]);
}
metrics[metricName].series.addPoint([new Date().getTime(), parseInt(value.Metric.CurrentValue)], true, false);
});
};
setInterval(function () {
var m = "{\"Metrics\": [{\"Metric\":{\"Name\":\"Queue 01\",\"CurrentValue\":\"0\",\"TimeStamp\":\"\\\x2FDate(1415826323291)\\\x2F\"}},{\"Metric\":{\"Name\":\"Queue 02\",\"CurrentValue\":\"3\",\"TimeStamp\":\"\\\x2FDate(1415826323344)\\\x2F\"}},{\"Metric\":{\"Name\":\"Queue 03\",\"CurrentValue\":\"9\",\"TimeStamp\":\"\\\x2FDate(1415826323405)\\\x2F\"}}]}";
ParseData(m);
}, 1000);
});
});
First, you have metrics declared as an array. Should be an empty object:
var metrics = {};
Second, the data structure you've created, metrics[metricName].series is not a Highcharts series object. It's an object you created and used to supply Highcharts data. To get the real series object, you'll have to get it back from the chart.
// getting the chart from the DOM, then the first series...
$("#"+metricName).highcharts().series[0].addPoint([new Date().getTime(), parseInt(value.Metric.CurrentValue)], true, false);
Updated fiddle.

highchart autoupdate(addpoint) cause corrupted chart view

Im using multiple highchart chart inside my page and i use addpoint function to update the chart.
the problem is after some time the chart will be compressed into less than a half of original chart size.
i captured my screen which could be found here for make the problem clear:
http://www.screenr.com/f3E7
sample chart generation code:
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
//var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'ch_trafficio',
type: 'spline',
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
var series1= this.series[1];
}
}
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
plotOptions : {
area : {
lineWidth : 1,
marker : {
enabled : false,
states : {
hover : {
enabled : true,
radius : 5
}
}
},
shadow : false,
states : {
hover : {
lineWidth : 1
}
}
}
},
legend: {
enabled: true
},
exporting: {
enabled: true
},
series: [{
name: 'InBound',
type : "area",
color: '#89A54E',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -119; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
},{
name: 'OutBound',
type : "area",
color: '#AA4643',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -119; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}
]
});
chart update functions:
chart.series[0].addPoint([x,data.oid1], false, true);
chart.series[1].addPoint([x,data.oid2], true, true);
chart1.series[0].addPoint([x,data.oid5], true, true);
chart2.series[0].addPoint([x,data.oid3], false, true);
chart2.series[1].addPoint([x,data.oid4], true, true);
chart3.series[0].addPoint([x,data.oid7], true, true);
thanks in advance
you need to add a shifting parameter for your points to shift over the chart
var series = chart.series[0],
shift = series.data.length > 100; // shift if the series is longer than 100
and to change adding point like below
chart.series[0].addPoint([x,data.oid1], true, shift);
example here

Resources