Am using Highcharts for pie chart. Below is the JS code for it :
$(document).ready(function () {
var chart;
var graphData = $("#graphContentdata").val();
console.log(graphData);
var options = {
chart: {
renderTo: 'graphContainer',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'SOV'
},
tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: []
}]
}
chart = new Highcharts.Chart(options);
chart.series[0].setData("["+graphData+"]");
});
And PHP Code for generating the Data :
foreach ($sumArray as $key=>$value)
{
$sumArray[$key] = array_sum($value);
$percent = (number_format(($sumArray[$key]/$sovGrandTotal)*100,2));
$data[] = "['$key', $percent]";
}
$data = join(",", $data);
?>
<input type='hidden' id='graphContentdata' value="<?php echo $data; ?>">
The Data format Am getting is :
['www.quora.com', 0.23],['www.slideshare.net', 0.25],['me', 99.52]
Problem is :
chart.series[0].setData("["+graphData+"]");
not creating graph, but if i copy paste the value from console at palce of graphData variable, its working like:
chart.series[0].setData([['www.quora.com', 0.23],['www.slideshare.net', 0.25],['me', 99.52]]);
is working.
What's the mistake am doing here???
The problem is your are passing your data as a String when you are using
chart.series[0].setData("["+graphData+"]");
You need to set your data as an Array. You could do that by converting your String using eval:
chart.series[0].setData(eval("["+graphData+"]"));
You could also use jQuery to convert your String to JSON, but in that case you must use double quotes to open and close Strings:
$.parseJSON("[[\"www.quora.com\", 0.23],[\"www.slideshare.net\", 0.25],[\"me\", 99.52]]");
Related
I am working with chartjs and I am wondering how to give '%' on datalabel of bar chart. My code like below:
data: {
datasets: [{
label: 'My Label',
data: <?php echo json_encode($myData); ?> // contains number like: 77.43, 78.22, etc
datalabels: {
align: 'end',
anchor: 'end'
}
}],
labels: <?php echo json_encode($myLabel); ?>
}
I tried to put string '%' like this data: <?php echo json_encode($myData); ?> + '%' but it returned nothing but a blank page. So anyone can help me to fix this?
You can setting the tooltip in the following way:
data: {
datasets: [{
label: 'My Label',
data: <?php echo json_encode($myData); ?> // contains number like: 77.43, 78.22, etc
datalabels: {
align: 'end',
anchor: 'end'
}
}],
labels: <?php echo json_encode($myLabel); ?>
},
options: {
tooltips: {
callbacks: {
label: function(tooltipItems, data) {
return data.datasets[tooltipItems.datasetIndex].label +': ' + tooltipItems.yLabel + ' %';
}
}
}
}
Reference : http://www.chartjs.org/docs/latest/configuration/tooltip.html
So, I found the solution on Chartjs Official Github Page. I just need to put
formatter: function (value) {
return value + "%";
}
inside datalabels
It acts similar with callback in yAxes option.
See this link
add quotes around php code and end with a comma: data: "<?...?>",
I'm trying to create a highchart with irregular x axis, a bit like this: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/spline-irregular-time/
I'm pulling my data from mySQL via PHP and processing in JSON format.
I can't get highcharts/JS to read the dates in date format - it seems to be pulling them as strings.
Here's my script:
$(document).ready(function() {
var options = {
chart: {
type: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'some title',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
categories: []
},
yAxis: {
title: {
text: 'L/min'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
plotOptions: {
spline: {
marker: {
enabled: true
}
}
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +': '+
this.y +'</b><br>'+ this.x;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("allreports/report.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.chart.renderTo = 'container';
chart = new Highcharts.Chart(options);
});
and here's my PHP page:
<?php
$con = mysql_connect("localhost","db-user","db-pw");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$sth = mysql_query("SELECT v1,v2 FROM table");
$rows = array();
$rows['name'] = 'v1';
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['v1'];
}
$result = array();
array_push($result,$rows1);
array_push($result,$rows);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
This outputs the following:
[{"name":"medicinetime","data":["01,01,1970,01,00,00","01,01,1970,01,33,36","01,01,1970,01,33,36","01,01,1970,01,33,36"]},{"name":"units","data":[1,3,2,2]}]
But my chart is as follows:
Any thoughts on what I'm doing wrong please? What do I need to do to get PHP/JS to pick up on this array as a series of datetimes rather than strings?
Thank you!
You have two issues. First, you need to convert your date-component values into an actual Javascript date object. The format you're looking for for your series data is an array of X/Y pairs. It'll look like this, using your data:
[
[Date.UTC(1970,1,1,1,0,0),1],
[Date.UTC(1970,1,1,1,33,36),3],
[Date.UTC(1970,1,1,1,33,36),2],
[Date.UTC(1970,1,1,1,33,26),2]
]
Try something like this:
var xVals= json[0].data.map( item => {
var dateArr = point[0].join(',');
return Date.UTC(dateArr[2],dateArr[1],dateArr[0],dateArr[3],dateArr[4],dateArr[5]);
});
var yVals = json[1].data;
options.series[0] = {
name: json[1].name,
data: xVals.map( (x,i) => [x,yVals[i]])
}
Some documentation on valid formats for the series data is here: http://www.highcharts.com/docs/chart-concepts/series
Second, you have some duplicate X values there, and that's going to be confusing...you're going to want your timestamps to be unique, or it's going to be hard to make a line chart out of them.
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.
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
I want to update the pie's data when the li is clicked. If data.php $cid get the value fixed value it works. Example : user_student.cid = 1 will work. If i use user_student.cid = $cid it doesn't work. Does anyone have any idea?
Thanks you,pquest.
But there have some problems.If I use fixed value 1 ,the alert value is: [["apple",1],["banana",2],["orange",3]] and the pie is working. If I use $cid value(if $cid value is 1) , the value alert is:[["apple",1],["banana",2],["orange",3]] but the pie is not working.
Anyone have any idea?
<script type="text/javascript">
$(document).ready(function() {
$('table.display').dataTable({
"paging": false,
"info": false
});
$('li').click(function(){
var cid = $(this).attr("id");
$.ajax({
type: "POST",
url: 'data.php',
data:{ cid:cid },
success:function(reponse){
alert(reponse)
/*options.series[0].data = reponse;
chart = new Highcharts.Chart(options);*/
}
});
var options = {
chart: {
renderTo: 'pie',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Web Sales & Marketing Efforts'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1,
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ Highcharts.numberFormat(this.percentage, 1); +' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ Highcharts.numberFormat(this.percentage, 1); +' %';
}
}
}
},
series: [{
type: 'pie',
dataType: 'json',
name: 'Browser share',
data: []
}]
}
$.getJSON("data.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
});
});
</script>
data.php
<?php
require_once("../connectDB.php");
$cid = isset($_POST["cid"]) ? $_POST["cid"] : "";
$result = $db->prepare("SELECT stu_info.reference FROM stu_info , user_student WHERE stu_info.sid = user_student.sid and user_student.cid = :cid");
$result ->execute(array(':cid' => $cid,));
$one = 0; $two = 0; $three = 0;
while($r = $result -> fetch()) {
if($r['reference'] === "apple")
$one = $one+1;
else
if($r['reference'] === "banana")
$two = $two+1;
else
if($r['reference'] === "orange")
$three = $three+1;
}
$ra = array($one,$three,$two);
$rb = array(apple,banana,orange);
$rows = array();
for($i=0 ; $i<=2 ; $i=$i+1)
{
$row[0] = $rb[$i];
$row[1] = $ra[$i];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
?>
You cant just write $cid in the query text. You have to build the string:
"SELECT stu_info.reference FROM stu_info , user_student WHERE stu_info.sid = user_student.sid and user_student.cid = " . $cid
Edit: It looks like the concatenation operator in php is . Rather than +