AmCharts don't plot graph when data = 0 - javascript

[
{ "category": "Q12012", "value1": 31845935.15, "value3": 0.00 },
{ "category": "Q22012", "value1": 29674500.79, "value3": 0.00 },
{ "category": "Q32012", "value1": 30935441.96, "value3": 0.00 },
{ "category": "Q42012", "value1": 31748214.07, "value3": 0.00 },
{ "category": "Q12013", "value1": 36601910.60, "value3": 31051022.99 },
{ "category": "Q22013", "value1": 39663505.35, "value3": 32240016.86 },
{ "category": "Q32013", "value1": 39822373.03, "value3": 34737268.00 },
{ "category": "Q42013", "value1": 37821101.06, "value3": 36959000.76 },
{ "category": "Q12014", "value1": 47430411.67, "value3": 38477222.51 },
{ "category": "Q22014", "value1": 47493801.18, "value3": 41184347.78 },
{ "category": "Q32014", "value1": 0.00, "value3": 43141921.74 }
]
Picture showing my graph was created using the code below.
How can I not display if my data value = 0?
Means that if my data == 0.00, I don't want it to be plotted on the graph. Where can I set them?
How can I name both line (orange and yellow line), my x-axis and y-axis?
thank you
<!-- the chart code -->
<script>
var chart;
// create chart
AmCharts.ready(function() {
// load the data
var chartData = AmCharts.loadJSON('dataMainForecasting.php');
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.pathToImages = "http://www.amcharts.com/lib/images/";
chart.dataProvider = chartData;
chart.categoryField = "category";
chart.title = 'Hello';
//chart.dataDateFormat = "YYYY-MM-DD";
// GRAPHS
var graph1 = new AmCharts.AmGraph();
graph1.valueField = "value1";
graph1.bullet = "round";
graph1.bulletBorderColor = "#FFFFFF";
graph1.bulletBorderThickness = 2;
graph1.lineThickness = 2;
graph1.lineAlpha = 0.5;
chart.addGraph(graph1);
var graph2 = new AmCharts.AmGraph();
graph2.valueField = "value2";
graph2.bullet = "round";
graph2.bulletBorderColor = "#FFFFFF";
graph2.bulletBorderThickness = 2;
graph2.lineThickness = 2;
graph2.lineAlpha = 0.5;
chart.addGraph(graph2);
// CATEGORY AXIS
chart.categoryAxis.parseString = true;
// WRITE
chart.write("Quarter2");
});
json = json.filter(function(val) {
return val !== 0;
});
</script>
and this is all my data being extracted from
mysql_select_db("test",$connect);
// Fetch the data
$query = "
SELECT *
FROM `table 5` ";
$result = mysql_query( $query );
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die( $message );
}
// Print out rows
// Print out rows
$prefix = '';
echo "[\n";
while ( $row = mysql_fetch_assoc( $result ) ) {
echo $prefix . " {\n";
echo ' "category": "' . $row['category'] . '",' . "\n";
echo ' "value1": ' . $row['value1'] . ',' . "\n";
echo ' "value2": ' . $row['value2'] . '' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]";
// Close the connection
//mysql_close($link);
?>

Latest answer
check AmChart addLabel method
see this working Demo
I've added implementations for both 1) remove zero values from graph and 2) Change labels of axes.
JS
//function prototype
addLabel(x, y, text, align, size, color, rotation, alpha, bold, url)
where
x - horizontal coordinate
y - vertical coordinate
text - label's text
align - alignment (left/right/center)
size - text size
color - text color
rotation - angle of rotation
alpha - label alpha
bold - specifies if text is bold (true/false)
url - url of a
This was my answer earlier before the original question was changed
you can just pre-process the data you are feeding to the chart api and remove the ones with zero value. This would be easy instead of trying to modify the graph api.
check the JSFiddle Demo
HTML:
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 400px"></div>
JS:
$(function() {
var options = {
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: ''
},
tooltip: {
formatter: function() {
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
},
plotOptions: {
line: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000'
}
}
},
events: {
load: function() {
var theChart = this;
var theSeries = this.series;
}
},
series: [{
type: 'line',
name: 'Browser share'
}]
};
//though this is a simple array, you will use a real json object here
json = [11, 71.5, 0, 0, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4];
json = json.filter(function(val) {
return val !== 0;
});
options.series[0].data = json;
$('#container').highcharts(options);
});
So basically you need to change your code to something like this:
$.getJSON("dataHome.php", function(json) {
//now you need to remove the zeros
json = json.filter(function(val) {
return val !== 0;
});
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
you can remove an element from a json object using its key see this Link

Related

Chart.JS Chart Not Being Generated

I am attempting to display 3 charts on this page. 2 of the 3 display perfectly, I asked a different question as I thought the issue was related to the syntax of the 2nd chart (cone) however a friendly user pointed out that the syntax is sound there, so alas I post back with full on syntax and hopefully someone can present me with the resolution to have all 3 charts display on my page.
And the exact error I receive is:
Uncaught type error. Can not read property 'data' of undefined.
On this line data: sb }] and the red X in the dev console is directly after the ]
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'Server';
$option['user'] = 'User';
$option['password'] = 'Pass';
$option['database'] = 'DB';
$option['prefix'] = '';
$db = JDatabaseDriver::getInstance($option);
$sql = $db->getQuery(true);
$sql = "Select * from green";
$db->setQuery($sql);
$rows = $db->loadRowList();
$output = array();
foreach ($rows as $row) {
array_push($output, $row);
}
$data = json_encode($output[0]);
$sql = "Select * from alpha";
$db->setQuery($sql);
$rows = $db->loadRowList();
$newoutput = array();
foreach ($rows as $row) {
array_push($newoutput, $row);
}
$newop = json_encode($newoutput[0]);
$sql = "Select * from jibjab";
$db->setQuery($sql);
$rows = $db->loadRowList();
$joc = array();
foreach ($rows as $row) {
array_push($joc, $row);
}
$yoytr = json_encode($joc[0]);
?>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
</head>
<style>
.doublecolumn { -webkit-column-count: 2; /* Chrome, Safari, Opera */ -moz-column-count: 2; /* Firefox */ column-count: 2;}
</style>
<body>
<h1><?php echo $paramname; ?> Place Header Here</h1>
<div class="doublecolumn">
<div id="container" style="width: 100%;"><canvas width:="100px;" id="canvas"></canvas></div>
<div id="containerone" style="width: 100%;"><canvas width:="100px;" id="cone"></canvas></div></div>
<script>
"use strict";
var jsondata = <?php echo $data; ?>;
var values = [];
for (var i = 0; i < jsondata.length; i++) {
values.push(jsondata[i]);
}
var jdata1 = <?php echo $newop; ?>;
var values1 = [];
for (var i = 0; i < jdata1.length; i++) {
values1.push(jdata1[i]);
}
var jdata2 = <?php echo $yoytr; ?>;
var yoyvalues = [];
for (var i = 0; i < jdata2.length; i++) {
yoyvalues.push(jdata2[i]);
}
var mainlabels = ["Jose 12", "Jose 13", "Jay 12", "Jay 13", "Rob 12", "Rob 13"];
var salesbyperson = [21, 31, 21, 16, 22, 24];
var ctx = document.getElementById('canvas').getContext('2d');
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: mainlabels,
datasets: [{
label: 'First',
backgroundColor: 'rgba(0, 129, 214, 0.8)',
data: salesbyperson
}]
},
options: {
tooltips: {
callbacks: {
label: function (t, d) {
var xLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
return xLabel + ': ' + yLabel;
}
}
},
legend: {
display: false,
position: 'top',
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function (value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}]
}
}
});
var ml = ["Jose 12", "Jose 13", "Jay 12", "Jay 13", "Rob 12", "Rob 13"];
var sb = [21, 31, 21, 16, 22, 24];
var ctx = document.getElementById('cone').getContext('2d');
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ml,
datasets: [{
label: 'Sum of Sales',
backgroundColor: 'rgba(0, 129, 214, 0.8)',
data: sb
}]
},
options: {
tooltips: {
callbacks: {
label: function(t, d) {
var xLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
return xLabel + ': ' + yLabel;
}
}
},
legend: {
display: false,
position: 'top',
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}]
}
},
plugins: [{
beforeDraw: function(chart) {
var labels = chart.data.labels;
labels.forEach(function(e, i) {
var bar = chart.data.datasets[0]._meta['0'].data[i]._model;
var dataPoint = e.split(/\s/)[1];
if (dataPoint === '12')
bar.backgroundColor = 'blue';
else if (dataPoint === '13')
bar.backgroundColor = 'green';
});
}
}]
});
</script>
<h1><?php echo $paramname; ?> Place Header Here</h1>
<div id="containerGPPercent" style="width: 50%;"><canvas width:="100px;" id="cavasme"></canvas></div>
<script>
var m2 = ["Jose 12", "Jose 13", "Jay 12", "Jay 13", "Rob 12", "Rob 13"];
var sb1 = [21, 31, 21, 16, 22, 24];
var ctx = document.getElementById('cavasme').getContext('2d');
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: m2,
datasets: [{
type: 'line',
fill: false,
label: 'Gross Profit',
backgroundColor: 'rgba(255,0,0,1)',
borderColor: 'rgba(255,0,0,1)',
data: sb1,
yAxisID: 'y-axis-1'
}, {
label: 'Total Revenue',
backgroundColor: 'rgba(0, 129, 214, 0.8)',
data: sb
}]
},
options: {
tooltips: {
callbacks: {
label: function (t, d) {
var xLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
return xLabel + ': ' + yLabel;
}
}
},
legend: {
display: false,
position: 'top',
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function (value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}, {
id: 'y-axis-1',
position: 'right',
ticks: {
beginAtZero: true,
callback: function (value, index, values) {
return value + '%';
}
}
}]
}
}
});
</script>
</body>
</html>
</body>
</html>
{/source}
There seems to be an issue with the plugin. TRY using the following one :
plugins: [{
beforeDraw: function(chart) {
var labels = chart.data.labels;
labels.forEach(function(e, i) {
var meta = chart.data.datasets[0]._meta;
var bar = meta[Object.keys(meta)[0]].data[i]._model;
var dataPoint = e.split(/\s/)[1];
if (dataPoint === '12') bar.backgroundColor = 'blue';
else if (dataPoint === '13') bar.backgroundColor = 'green';
});
}
}]

Loading data via `dataLoader` in serial AmCharts does not renders the chart

I'm using dataLoader for retrieving data in AmChart from PHP/MySql backend.
However the simple serial bar chart is generated but don't know what is the problem with rendering graphs, graphs are not getting generated.
Then with another try using ajax call I've done re-parsing of JSON response to object via loop just like generateChartData(), it's the same data. But still chart is not getting rendered.
These options I've passed to dataLoader
"dataLoader": {
"url": 'data.php',
"format": "json"
}
In ajax call I call chart.validateData() but this is not working. What can done to solve this?
setting async option for ajax request false gives warning and doesn't work too.
Here is the js code app.js:
var chartData = [];
loadChartData();
function loadChartData() {
var time = new Date();
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var cur = new Date();
var data = JSON.parse(ajax.responseText);
data.forEach(function(d, i) {
chartData.push({
date: d.date,
visits: parseInt(d.visits, 10)
});
});
// alert('Request Completed in '+ (cur - time)+ ' mili seconds');
console.log(chartData.length);
// chart.validateData();
}
};
ajax.open('GET', 'data.php', true);
ajax.setRequestHeader("Content-type", "application/json");
ajax.send();
}
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"marginRight": 80,
// "dataLoader": {
// "url": "data.php",
// "format": "json"
// }, this doesn't work too!
"dataProvider": chartData,
"dataDateFormat": "YYYY-MM-DD",
"valueAxes": [{
"position": "left",
"title": "Energy Generated"
}],
"graphs": [{
"id": "g1",
"fillAlphas": 0.4,
"valueField": "visits",
"balloonText": "<div style='margin:5px; font-size:19px;'><b>[[value]]kWh</b></div>"
}],
"chartScrollbar": {
"graph": "g1",
"scrollbarHeight": 80,
"backgroundAlpha": 0,
"selectedBackgroundAlpha": 0.1,
"selectedBackgroundColor": "#888888",
"graphFillAlpha": 0,
"graphLineAlpha": 0.5,
"selectedGraphFillAlpha": 0,
"selectedGraphLineAlpha": 1,
"autoGridCount": true,
"color": "#AAAAAA"
},
"chartCursor": {
"categoryBalloonDateFormat": "JJ:NN, DD MMMM",
"cursorPosition": "mouse"
},
"categoryField": "date",
"categoryAxis": {
"minPeriod": "mm",
"parseDates": true
},
});
// this method is called when chart is first inited as we listen for "dataUpdated" event
function zoomChart() {
// different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
chart.zoomToIndexes( chart.dataProvider.length - 250, chart.dataProvider.length - 100);
}
zoomChart();
And here is my php code data.php
$link = new mysqli( "localhost", "root", "", "test" );
if ( $link->connect_errno ) {
die ("Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error);
}
// Fetch the data
$query = "SELECT *
FROM daily_visits
ORDER BY date ASC";
$result = $link->query( $query );
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . $link->error . "\n";
$message .= 'Whole query: ' . $query;
die( $message );
}
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );
// Close the connection
mysqli_close($link);
And the returned json looks like
[{"date":"2016-09-03","visits":"16"},{"date":"2016-09-03","visits":"49"},...]
Remove "dataProvider": chartData from makeChart, when using dataloader.
You should update the instance of the chart:
let chartInstance = AmChart.makeCharts(...);
(<any>this.chartInstance).dataProvider = parsedArray; // yes, here we update the dataProvider directly
If anyone doesn't understand this, please leave a message here.

HighCharts / Wordpress - How do I generate unique charts for ~4,800 posts?

Relatively new to HighCharts, PHP and JS but continuing to learn. I have searched extensively on the web but have not found anything that works so far.
I have a listing website that displays information on a variety of hospitals. As part of this offering, I am looking to show salary information unique to each hospital (~4,800) in HighCharts, using the WP post ID as the identifier.
I have a static chart showing across all hospitals as a placeholder right now but would like make this dynamic based on the individual hospital in question. I tried to use an Ajax POST command to push the right data without any luck thus far.
Any help or guidance would be greatly appreciated!
Code below:
JS Chart Display (Contained in a Widget)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!--
updatepage();
//--></script>
*** Function does not work when included ***
//var post_id = parseInt( ( document.body.className.match( /(?:^|\s)postid-([0-9]+)(?:\s|$)/ ) || [ 0, 0 ] )[1] ); // - JS to get post ID
var post_id = "1"; //Temporary post_id
jQuery(function($){
$('.section').click(function () {
jQuery.ajax({
url: http://www.rndeer.com/data.php,
type: 'POST',
data: post_id,
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
});
***********************
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
colors: ['#0000FF', '#0066FF', '#3396d1'],
title: {
text: '<?php echo get_the_title();?>',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Salary ($ per / hour)'
},
plotLines: [{
value: 0,
width: 1,
color: '#3396d1'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': $'+ this.y+' per / hour';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("data.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
chart = new Highcharts.Chart(options);
});
});
</script>
Data.PHP Script
<?php
$con = mysql_connect("localhost","Database_Name","Password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//$post_id = $_POST['post_id']; - Attempt at getting posted data
$post_id = '1';
mysql_select_db("Database Name", $con);
$query = mysql_query("SELECT hospital, newgrad, median, high FROM salary_estimates WHERE id='".$post_id."'");
$category = array();
$category['name'] = 'Hospital';
$series1 = array();
$series1['name'] = 'New Grad';
$series2 = array();
$series2['name'] = 'Median';
$series3 = array();
$series3['name'] = 'High';
while($r = mysql_fetch_array($query)) {
$category['data'][] = $r['hospital'];
$series1['data'][] = $r['newgrad'];
$series2['data'][] = $r['median'];
$series3['data'][] = $r['high'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series2);
array_push($result,$series3);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>

Post request inside php code var anidade

I am working with Dygraphs to chart Arduino sensor data.I need to get a subtract between two data so i am using php inside a script function but it doesn't work.It is possible to include
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start=<?php echo $_POST['day_ini'];?>%20<?php echo $_POST['hour_ini'];?>&end=<?php echo $_POST['day_end'];?>%20<?php echo $_POST['hour_end'];?>", "r")) !== FALSE) {
...
?>','2015-11-02 20:54:50 UTC,1049703,5,5'
];
This is all my function code:
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start=2015-11-02%2020:50:45&end=2015-11-02%2021:50:45", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 50, ",")) !== FALSE) {
if($row == 1){ $row++; continue; }
$num = count($data);
for ($c=0; $c < $num; $c++) {
if(strpos($data[$c], 'Finished') !== false) {
$c++;
echo $data[$c] . "," ; }
Else{
echo $data[$c] . "," ;
}
}
}
fclose($handle);
}
?>','2015-11-02 20:54:50 UTC,1049703,5,5'
//... etcetera
];
function getPairDifference(pair) {
//"pair" is a zero-based integer.
// "0" will return a difference between csv rows "0" & "1"
// "1" will return a difference between csv rows "1" & "2"
// etcetera...
var firstVal = parseInt(csv[pair].split(",")[3]);
var secondVal = parseInt(csv[pair + 1].split(",")[3]);
return firstVal - secondVal;
}
for (var i = 0; i < csv.length; i += 1) {
// Demo code to visualize numbers.
// Actual function call of interest is simply "getPairDifference( i )"
var plot = getPairDifference(i);
// $("<div></div>").text(plot).appendTo("body");
$(function() {
$("#chart3").chart({
template: "line_basic_6",
tooltips: {
serie1: [plot],
width:20,
height:15,
},
values: {
serie1: [plot]
},
labels: ["Period 1","Period 2"],
defaultSeries: {
type: "bar",
stacked: true
},
series: {
serie3: {
type: "line",
stacked: false,
axis: "r"
}
},
axis: {
r: {
max: 100,
suffix: "%"
}
}
});
});
$.elycharts.templates['line_basic_6'] = {
type: "line",
margins: [10, 40, 40, 30],
defaultSeries: {
highlight: {
newProps: {
r: 8,
opacity: 1
},
overlayProps: {
fill: "white",
opacity: 0.2
}
}
},
series: {
serie1: {
color: "90-#003000-#009000",
tooltip: {
frameProps: {
stroke: "green"
}
}
},
},
defaultAxis: {
labels: true
},
axis: {
x: {
labelsRotate: 0,
labelsProps: {
font: "11px Verdana"
}
}
},
features: {
grid: {
draw: true,
forceBorder: true,
ny: 5
}
},
barMargins: 180
};
}
</script>
Thanks in advance.
no need to echo like that and you are using <?php inside another <?php before closing that.
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start={$_POST['day_ini']}%20{$_POST['hour_ini']}&end={$_POST['day_end']}%20{$_POST['hour_end']}", "r")) !== FALSE) {
}
?>', '2015-11-02 20:54:50 UTC,1049703,5,5'
];
</script>
And i am not sure of }, please check that once.
You have missunderstood something about PHP and Javascript.
Javascript gets sended to the Client, so it works in the Browser and also get's executed.
PHP altough gets executed on the Server first, there lies your problem, you can't execute on the Client something that needs to be done by a Server.

Want to fetch mysql Field record in highchart tooltip

Here I am using highchart with codeigniter. I got highchart record with graph but I want record comes from mysql database field of "zreadactivity" in tooltip. I could not get proper name in tooltip for "zreadactivity" as it contains record. So, I just want to know that where I am stuck?
Here is my code:
Controller:
public function branchwiseactivityavg()
{
$data = $this->Data->branch_wise_activities();
$category = array();
$category['name'] = 'EndDate';
$series1 = array();
$series1['name'] = 'TotalValue';
$series2 = array();
$series2['name'] = 'zreadactivity';
foreach ($data as $row)
{
$category['data'][] = $row->EndDate;
$series1['data'][] = $row->TotalValue;
$series2['data'][] = $row->zreadactivity;
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series2);
print json_encode($result, JSON_NUMERIC_CHECK);
}
Javascript:
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container5',
type: 'column',
marginRight: 130,
marginBottom: 25,
zoomType: 'x'
},
title: {
text: 'Branch wise activities Last 30 Days',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories : []
},
yAxis: {
title: {
text: 'TotalValue'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip:
{
formatter: function() { return ' ' +
'EndDate: ' + this.x + '<br />' +
'TotalValue: ' + this.y + '<br />' +
'zreadactivity: ' + this.series.name;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
};
$.getJSON("branchwiseactivityavg", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
</script>
zreadactivity table:
zreadacivity
---------------
Refund
Exchange
Voids
Cancel
Discount
Price Overwrite
One way is to create JSON where for series' data each point is defined as an array like:
[value_from_TotalValue, value_from_zreadactivity]
and set keys for series like:
series: [{keys: ['y','zreadactivity']}]
and in tooltip's formatter use this.point.zreadactivity to access zreadactivity.
Other option is to build this structure for series in JavaScript after getting JSON data.
Example with keys: http://jsfiddle.net/yhx2dp2g/
Example without keys: http://jsfiddle.net/yhx2dp2g/1/

Categories

Resources