Google line chart dual Y-axis issue - php

I'm working on a dual Y-axis linechart that is to have both height and weight on the Y-axes with the date displaying on the X-axis:
I'm pulling the data from my MYSQL database and encoding it into json and the passing it to my function that draws the chart as shown:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Height');
data.addColumn('number', 'Weight');
data.addRows([
<?php
$chart_info = $db->prepare("SELECT `height`, `weight`, `date_captured` FROM `child_results_capture` ");
$chart_info->execute();
$result = $chart_info->fetchAll(PDO::FETCH_ASSOC);
$chart_data = '';
foreach($result as $value)
{
$chart_data.="['".$value['date_captured']."',".$value['height'].",".$value['weight']."],";
// var_dump($chart_data);exit;
// echo $chart_data;
}
echo $chart_data;
?>
]);
var options = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
0: {axis: 'Height'},
1: {axis: 'Weight'}
},
axes: {
y: {
Height: {label: 'Height (cm)'},
Weight: {label: 'Weight (kg)'}
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('graph_chart'));
chart.draw(data, options);
}
</script>
<div id="graph_chart"></div>
The Json returned from my php bit looks like this:
['2016-07-27',51,3.4],['2016-08-03',52,4],['2016-08-10',53,5],['2016-08-17',54,6],['2016-08-24',55,7],['2016-08-31',56,8],
And my output looks like this:
As shown above, I only get one Y-axis(for the height) and my chart axes are not labelled with the corresponding names
Will appreciate being pointed in the right direction

the specific configuration options used in the question to build the Dual-Y Chart
are for Material charts only --> google.charts.Line
var optionsMatl = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
0: {axis: 'Height'},
1: {axis: 'Weight'}
},
axes: {
y: {
Height: {label: 'Height (cm)'},
Weight: {label: 'Weight (kg)'}
}
}
};
a different set of options is needed to build a Dual-Y Chart
in a Classic chart --> google.visualization.LineChart
var optionsCore = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
1: {
targetAxisIndex: 1
}
},
vAxes: {
0: {
title: 'Height (cm)'
},
1: {
title: 'Weight (kg)'
}
},
theme: 'material'
};
from the documentation for Dual-Y Charts...
In the Material code ..., the axes and series options together specify the dual-Y appearance of the chart. The series option specifies which axis to use for each. The axes option then makes this chart a dual-Y chart.
In the Classic code, this differs slightly. Rather than the axes option, you will use the vAxes option (or hAxes on horizontally oriented charts). Also, instead of using names, you will use the index numbers to coordinate a series with an axis using the targetAxisIndex option.
see following working snippet, which draw both...
google.charts.load('current', {packages:['corechart', 'line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Height');
data.addColumn('number', 'Weight')
data.addRows([
['2016-07-27',51,3.4],
['2016-08-03',52,4],
['2016-08-10',53,5],
['2016-08-17',54,6],
['2016-08-24',55,7],
['2016-08-31',56,8]
]);
var optionsMatl = {
title: 'Height-Weight graph',
width: 900,
height: 500,
series: {
0: {axis: 'Height'},
1: {axis: 'Weight'}
},
axes: {
y: {
Height: {label: 'Height (cm)'},
Weight: {label: 'Weight (kg)'}
}
}
};
var chartMatl = new google.charts.Line(document.getElementById('chart_div_matl'));
chartMatl.draw(data, google.charts.Line.convertOptions(optionsMatl));
var optionsCore = {
title: 'Height-Weight graph',
width: 900,
height: 500,
legend: {
position: 'top',
alignment: 'end'
},
series: {
1: {
targetAxisIndex: 1
}
},
vAxes: {
0: {
title: 'Height (cm)',
},
1: {
title: 'Weight (kg)'
}
},
theme: 'material'
};
var chartCore = new google.visualization.LineChart(document.getElementById('chart_div_core'));
chartCore.draw(data, optionsCore);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>Material Chart</div>
<div id="chart_div_matl"></div>
<div>Core Chart</div>
<div id="chart_div_core"></div>

Related

How to show values on pie or bar graph chart in php using chart.js

I want to show values on graphs. i search alot but could not find my solution.
Here is the code below:
<script>
var ctx = document.getElementById("barChart");
ctx.height = 100;
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: <?php echo json_encode($Division); ?>,
datasets: [{
label: 'Target',
data: <?php echo json_encode($TARGET_QTY); ?>,
//backgroundColor: "rgba(255, 159, 64, 0.2)",
backgroundColor: "rgb(231, 123, 126)",
borderColor: "rgb(219, 219, 219)",
borderWidth: 1
},
{
label: 'Actual',
data: <?php echo json_encode($DISPATCH_QTY); ?>,
backgroundColor: "rgb(0, 191, 255)",
borderColor: "rgb(252, 252, 252)",
borderWidth: 1
}
]
},
options: {
responsive: true,
tooltips: {
"enabled": false
},
scales: {
yAxes: [{
gridLines: {
display:false,
},
ticks: {
beginAtZero:true
}
}]
},
title: {
display: true,
// position:"bottom",
text: 'Target vs Actual Dispatch'
},
hover: {
// Overrides the global setting
mode: 'label'
},
animation: {
duration: 1,
onComplete: function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i)
{
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
},
/*legend: {
display: true,
// position : "bottom",
labels: {
fontColor: 'rgb(0, 0, 0)'
}
}*/
}
});
</script>
<div class="row">
<div class="col-md-12">
<div class="chart">
<canvas id="barChart" style="position: relative; height: 300px;"></canvas>
</div>
</div>
</div>
I search alot but could not show values in the bar graph. In this code value will be shown on the top of the graph but could not show on the bar. i want to show value on the bars of graph. either its a bar chart or pie chart. i use chart.js library. Please help me to get rid of this situation. Thanks in Advance.

Google charts - Get the equation of Linear trendlines

I have a chart like this (drawn by google charts)
the line is generated by google with option of Linear trendlines
image
code
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Diameter', 'Age'],
[8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]]);
var options = {
title: 'Age of sugar maples vs. trunk diameter, in inches',
hAxis: {title: 'Diameter'},
vAxis: {title: 'Age'},
legend: 'none',
trendlines: { 0: {} } // Draw a trendline for data series 0.
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
how to know the equation of this line?
adding the trendline to the legend will reveal the equation...
trendlines: {
0: {
visibleInLegend: true
}
}
you can remove the series from the legend, if so desired...
series: {
0: {
visibleInLegend: false
}
},
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Diameter', 'Age'],
[8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]]);
var options = {
title: 'Age of sugar maples vs. trunk diameter, in inches',
hAxis: {title: 'Diameter'},
vAxis: {title: 'Age'},
legend: {
alignment: 'end',
position: 'top'
},
series: {
0: {
visibleInLegend: false
}
},
trendlines: {
0: {
visibleInLegend: true
}
}
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
once the equation has been added to the legend,
you can get the value from the <text> element used to draw the legend marker
but need to wait on the 'ready' event first,
to know the chart has finished drawing
also, you will need a way to determine the legend marker <text> element
from the other labels, such as the chart title
in this example, both the title and the legend marker
have an attribute text-anchor with a value of 'start'
text-anchor could change depending the legend's alignment and position
the font color (fill) is used to separate the title from the legend marker...
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Diameter', 'Age'],
[8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]]);
var options = {
title: 'Age of sugar maples vs. trunk diameter, in inches',
hAxis: {title: 'Diameter'},
vAxis: {title: 'Age'},
legend: {
alignment: 'end',
position: 'top'
},
series: {
0: {
visibleInLegend: false
}
},
trendlines: {
0: {
visibleInLegend: true
}
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.ScatterChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var equation = $('text[text-anchor="start"][fill="#222222"]').text();
console.log(equation);
});
chart.draw(data, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
This works for me:
var container = document.getElementById('chart_div');
var chart = new google.visualization.ScatterChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
console.log(chart.Zl().jp[1].text);
});
chart.draw(data, options);
chart.Zl().jp looks like this:
[
{
"id": "",
"text": "Age",
"brush": "{\"fill\":\"#3366cc\",\"fillOpacity\":1,\"stroke\":\"none\",\"strokeWidth\":1,\"strokeOpacity\":1,\"strokeDashStyle\":\"solid\",\"rx\":null,\"ry\":null,\"gradient\":null,\"pattern\":null,\"shadow\":null}",
"index": 0,
"ja": false
},
{
"id": "_trendline",
"text": "y = 4.885 * x + 0.73",
"brush": "{\"fill\":\"#3366cc\",\"fillOpacity\":0.5,\"stroke\":\"none\",\"strokeWidth\":1,\"strokeOpacity\":1,\"strokeDashStyle\":\"solid\",\"rx\":null,\"ry\":null,\"gradient\":null,\"pattern\":null,\"shadow\":null}",
"index": 1,
"ja": true
}
]
so for each series there will be two objects, one for series and second for trendline, so if for example you have two trendlines you can get the second equation with chart.Zl().jp[3].text

How to avoid Y axis negative values from google charts

How to avoid the negative values from google chart, I tried viewWindow: { min: 0,} in my Y axis, but still it showing negative values only.
please help some one please. Thanks in advance
<div class="timeline-item">
<div id="top_x_div" style="width: 100%; height: 300px;"></div>
</div>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawStacked);
function drawStacked() {
var data = new google.visualization.arrayToDataTable([
['Courses', 'Students'],
["Electronics", 2 ],
]);
var options = {
legend: { position: 'none' },
isStacked: true,
colors: ['green'],
bars: 'vertical', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'bottom', label: 'Percentage'} // Top x-axis.
}
},
axes: {
y: {
0: { side: 'bottom', label: 'Students'}, // Top x-axis.
/* viewWindow: {
min: 0,
},*/
}
},
vAxis: {
viewWindow: {
min: 0
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
};
</script>
You need to set the viewWindow on the vAxis option.
vAxis: {
viewWindow: {
min: 0
}
}
Source

Google BarChart decimal values Not appears

I am creating google barchart, that takes data from database.The problem is that data contains values below "1" like 0.6,0.7 etc
It wont appear on graph. Graph only shows values starting from 1.
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: 'string',
role: 'annotation',
sourceColumn: 1,
calc: 'stringify'
}]);
var options = {
width: 395,
height: 200,
title: 'Values',
'chartArea': {right: 37,width:'40%'},
titleTextStyle: {
fontName: 'Arial',
fontSize: 14
},
legend: {position: 'none'},
colors:['#4A9218'],
};
var chart = new google.visualization.BarChart(document.getElementById('ch7'));
chart.draw(view, options);
}
</script>
<div id="ch7" style="width:33%; height:200px"></div>
If your values are all positive you can use logarithmic scale setting option hAxis.logScale to true. Othervise you can set also minimum value to be shown. Options are set like:
hAxis: {
logScale: true
}
or like
hAxis: {
minValue: 0
}

Remove blank space above and below Google Charts horizontal column chart

I am show graphs from Google Charts, using a horizontal column chart. I want to remove the blank space above and below the graph.
Here is the code called (some info removed due to NDA):
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[null, "...","...","...","...","...","...","...","...","Total Average"],
[null, 100,100,100,100,100,88.89,100,100,98.70]
]);
var options = {
height: 540,
title: 'Title here',
vAxis: { textPosition: 'none', viewWindowMode: 'maximized' },
colors:["#0B0842","#ADAEAE","#BE3351","#498101","#0D80CA","#A3C116","#91A96B","#E8F72B","#424242"],
hAxis: { textPosition: 'none', minValue: 0, maxValue: 100 },
chartArea: { left: 0, width: "78%" },
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
The space above and below the bars is normally there to separate bar groups when you have multiple rows of data. If you don't want that space, then you can set the bar.groupWidth option in your chart to a larger percentage (up to 100%; default is the golden ratio, roughly 61.8%):
var options = {
height: 540,
title: 'Title here',
vAxis: { textPosition: 'none', viewWindowMode: 'maximized' },
colors:["#0B0842","#ADAEAE","#BE3351","#498101","#0D80CA","#A3C116","#91A96B","#E8F72B","#424242"],
hAxis: { textPosition: 'none', minValue: 0, maxValue: 100 },
chartArea: { left: 0, width: "78%" },
bar: {groupWidth: '100%'}
};
Try this, it worked for me:
var chart_height = data.getNumberOfRows() * 40;
var options = {
chartArea: {
top: 0,
left: '30%',
width: '70%',
bottom: 0
},
height: chart_height
};

Categories