I am working on a KPI dashboard, my database contains hot water (hwater) usage per month(adate), comparing this year with last year as an area chart.
However when I run this report my webpage is blank. I have tried setting google.visualization.arrayToDataTable to .DataTable while declaring the column names and also tried with server side AJAX with no success.
Area_Chart.php
<?php
require_once ("connect.php");
//fetch table rows from mysql db
$query = $handler->query("
SELECT MONTH(adate) as month,
MAX(case when YEAR(adate) = YEAR(CURRENT_DATE)-1 THEN hwater ELSE 0 END) as 'Last_Year',
MAX(case when YEAR(adate) = YEAR(CURRENT_DATE) THEN hwater ELSE 0 END) as 'This_Year'
FROM utlt
WHERE YEAR(adate) = YEAR(CURRENT_DATE)-1 OR year(adate) = YEAR(CURRENT_DATE)
GROUP BY MONTH(adate)
ORDER BY MONTH(adate)");
$query->execute();
$results=$query->fetchAll(PDO::FETCH_NUM);
$json=json_encode($results);
//echo $json;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
[ {label: 'Year', id: 'month'},
{label: 'Last_Year', id: 'Last_Year', type: 'number'},
{label: 'This_Year', id: 'This_Year', type: 'number'}],
<?=$json?>
], false);
var options = {
isStacked: 'absolute',
title: 'Hot Water Useage',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 100%; height: 500px;"></div>
</body>
</html>
Output of echo $json:
[["1","1.671","21.269"],["2","3.810","22.017"],["3","5.554","24.045"],["4","6.930","25.036"],["5","8.845","27.116"],["6","11.793","28.058"],["7","13.244","28.996"],["8","14.471","30.342"],["9","16.260","30.977"],["10","17.199","31.923"],["11","18.494","33.155"],["12","19.563","33.797"]]
I notice above that hwater from utlt are rapped in "", does this mean its a string? The field type is actually a decimal (6,3).
hwater from utlt being wrapped in "" is definitely a problem,
since the column type is 'number'
try using JSON_NUMERIC_CHECK to encode the json
$json=json_encode($results, JSON_NUMERIC_CHECK);
EDIT
think i found the problem here...
var data = google.visualization.arrayToDataTable([
[ {label: 'Year', id: 'month'},
{label: 'Last_Year', id: 'Last_Year', type: 'number'},
{label: 'This_Year', id: 'This_Year', type: 'number'}],
<?=$json?> // <-- problem
], false);
the problem is the outer array wrapping the row arrays
//--> [[1,1.671,21.269]...
given where <?=$json?> is placed, the rows shouldn't be wrapped in array
this can easily be corrected by using the addRows method to load the json
remove json from arrayToDataTable
var data = google.visualization.arrayToDataTable([
[ {label: 'Year', id: 'month', type: 'number'},
{label: 'Last_Year', id: 'Last_Year', type: 'number'},
{label: 'This_Year', id: 'This_Year', type: 'number'}],
]);
then add another statement for the addRows method, which needs the outer array
data.addRows(
<?=$json?>
);
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
[ {label: 'Year', id: 'month', type: 'number'},
{label: 'Last_Year', id: 'Last_Year', type: 'number'},
{label: 'This_Year', id: 'This_Year', type: 'number'}],
]);
data.addRows(
[[1,1.671,21.269],[2,3.810,22.017],[3,5.554,24.045],[4,6.930,25.036],[5,8.845,27.116],[6,11.793,28.058],[7,13.244,28.996],[8,14.471,30.342],[9,16.260,30.977],[10,17.199,31.923],[11,18.494,33.155],[12,19.563,33.797]]
);
var options = {
isStacked: 'absolute',
title: 'Hot Water Useage',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Related
I am trying to create a gantt chart with Chart.js. I use horizontalBar chart type and this works fine if I populate numbers instead of dates, but it does not render when I pass dates as data.
Data structure: Task, Start Date, End Date
this.chartData = {
labels: ['Task 1', 'Task 2'],
datasets: [{
data: ['2019-01-20', '2019-01-30'],
}],
};
this.options = {
title: {
display: true,
text: 'Title of Chart',
},
legend: {display: false},
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
},
}],
},
};
Template:
<chart class="chart" type="horizontalBar" [data]="chartData" [options]="options"></chart>
Tried another example
You are passing the values as strings. Try to pass as dates:
datasets: [{
label: 'Demo',
data: [{
t: new Date("2015-3-15 13:3"),
y: 12
},
I am using google chart plugin to plot a area chart,by using JSON data as show below code, which contains value and a date by the chart should be printed based on month.
Link show in image
enter image description here
how to plot the chart based on month using google chart
is it possible to do it with google charts buit in features and need to write some customized javascript for that achive?
<script type="text/javascript">
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'value'],
[
"1/Jan/2017",
28
],
[
"5/Feb/2019",
174
],
[
"8/Mar/2017",
150
],
[
"2/Apr/2019",
174
],
[
"18/May/2019",
100
],
[
"22/Jun/2019",
5
],
[
"30/Jul/2019",
178
],
[
"28/Aug/2019",
59
],
[
"1/Sep/2019",
87
],
[
"10/Oct/2019",
50
],
[
"15/Nov/2019",
123
],
[
"20/Dec/2019",
108
]
]);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Date',
titleTextStyle: {
color: '#333'
}
},
curveType: 'function',
legend: {
position: 'bottom'
},
pointSize: 5,
dataOpacity: 0.5,
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="width: 100%; height: 500px;"></div>
in order to format the x-axis as a date,
need to convert the first column in the data table from a string to an actual date...
we can use a data view with a calculated column to convert the date...
var view = new google.visualization.DataView(data);
view.setColumns([{
type: 'date',
label: 'Date',
calc: function (dt, row) {
return new Date(dt.getValue(row, 0));
}
}, 1]);
also, since the data is not in order by date, we can convert the view back to a data table and sort it...
data = view.toDataTable();
data.sort([{column: 0}]);
see following working snippet...
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'value'],
[
"1/Jan/2017",
28
],
[
"5/Feb/2019",
174
],
[
"8/Mar/2017",
150
],
[
"2/Apr/2019",
174
],
[
"18/May/2019",
100
],
[
"22/Jun/2019",
5
],
[
"30/Jul/2019",
178
],
[
"28/Aug/2019",
59
],
[
"1/Sep/2019",
87
],
[
"10/Oct/2019",
50
],
[
"15/Nov/2019",
123
],
[
"20/Dec/2019",
108
]
]);
var view = new google.visualization.DataView(data);
view.setColumns([{
type: 'date',
label: 'Date',
calc: function (dt, row) {
return new Date(dt.getValue(row, 0));
}
}, 1]);
data = view.toDataTable();
data.sort([{column: 0}]);
var options = {
chartArea: {bottom: 56},
title: 'Company Performance',
hAxis: {format: 'MMM', title: 'Date', titleTextStyle: {color: '#333'} },
curveType: 'function',
legend: { position: 'bottom'},
pointSize: 5,
dataOpacity: 0.5,
vAxis: {minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I am trying to set ticks for a double y-axis line graph but either the graph wont load, it it loads exactly the same. Any help will be greatly appreciated
Goal is to set Price ticks: [0.002, 0.004. 0.006. 0.008], and Volume increment by lets say 1000
Also having issues with prices for instance being: 0.00242, 0.00521 all showing up as 0.1
<?php
$sql = "SELECT Timestamp, LastPrice, Volume FROM vol";
$result = $dbconnect->query($sql);
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
google.charts.load('current', {'packages':['line', 'corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var button = document.getElementById('change-chart');
var chartDiv = document.getElementById('chart_div');
var data = google.visualization.arrayToDataTable([
['Timestamp','LastPrice','Volume'],
<?php
while($row = mysqli_fetch_assoc($result)){
echo "[ '".$row["Timestamp"]."', ".$row["LastPrice"].", ".$row["Volume"].", ],";
}
echo $row["LastPrice"];
?>
]);
var materialOptions = {
chart: {
},
width: 600,
height: 300,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {axis: 'LastPrice' },
1: {axis: 'BaseVolume'}
},
vAxis: {1: {ticks:[0, 0.002, 0.004, 0.006]} },
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
LastPrice: {label: 'Price'},
BaseVolume: {label: 'Volume'}
}
}
};
function drawMaterialChart() {
var materialChart = new google.charts.Line(chartDiv);
materialChart.draw(data, materialOptions);
button.innerText = 'Classic';
button.onclick = drawClassicChart;
}
drawMaterialChart();
}
</script>
there are several configuration options that aren't supported by Material charts, including...
{hAxis,vAxis,hAxes.*,vAxes.*}.ticks
see --> Tracking Issue for Material Chart Feature Parity
instead, recommend using a Classic chart with the following option...
theme: 'material'
for dual y-axis charts, use the series option to specify the target axis
series: {
1: {
targetAxisIndex: 1,
}
},
use option vAxes, with an e, to specify ticks for each y-axis
vAxes: {
0: {
ticks:[0, 1000, 2000, 3000],
title: 'Last Price'
},
1: {
ticks:[0, 0.002, 0.004, 0.006],
title: 'Base Volume'
}
}
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable({
cols: [
{label: 'x', type: 'string'},
{label: 'y0', type: 'number'},
{label: 'y1', type: 'number'}
],
rows: [
{c:[{v: 'row 0'}, {v: 1800}, {v: 0.00242}]},
{c:[{v: 'row 1'}, {v: 2200}, {v: 0.00521}]},
{c:[{v: 'row 2'}, {v: 2800}, {v: 0.00343}]},
{c:[{v: 'row 3'}, {v: 2800}, {v: 0.00441}]},
{c:[{v: 'row 4'}, {v: 2300}, {v: 0.00532}]}
]
});
var container = document.getElementById('chart');
var chart = new google.visualization.LineChart(container);
chart.draw(data, {
width: 600,
height: 300,
series: {
1: {
targetAxisIndex: 1,
}
},
theme: 'material',
vAxes: {
0: {
ticks:[0, 1000, 2000, 3000],
title: 'Last Price'
},
1: {
ticks:[0, 0.002, 0.004, 0.006],
title: 'Base Volume'
}
}
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
I'm trying to create compound chart with a given data, that is, [date, value1, value2], however I can not handle such inputs:
// [["Day","Dose","INR"],["17/04",1.5,null]]
// [["Day","Dose","INR"]]
// [["Day","Dose","INR"],["17/04",1.5,null],["18/04",2.5,null]]
that is, when there are a set of data with a particular value all consist of nulls, I can not draw it on graph. Such inputs are fine:
// [["Day","Dose","INR"],["17/04",1.5,null],["18/04",2.5,0.9]]
// [["Day","Dose","INR"],["17/04",1.5,null],["18/04",2.5,0.9],["19/04",null,1.4]]
And here is my javascript code drawing the graph. Data is coming from a Ruby model.
$(function () {
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable(<%= DrugInr.generate_array(#patient) %>);
var options = {
vAxes: { 1: {title: 'Dose', format: '#.#', maxValue: 20},
0: {title: 'INR',format: '#.#', minValue: -1, baselineColor:"#CCCCCC"} },
hAxis: {title: 'Day'},
seriesType: 'bars',
bar: {
groupWidth: 2
},
series: {
0:{ type: "bars", targetAxisIndex: 1 },
1:{ type: 'line', targetAxisIndex: 0}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
});
How can I handle these half empty values?
I would recommend the interpolateNulls option. See the ComboChart Configuration Options documentation for details.
var options = {
interpolateNulls: true
};
This option just tells the chart to guess what your values are if there's a null, rather than leave a gap. Works for most cases, anyway.
I solved this creating my data table like this:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'INR');
data.addColumn('number', 'Dosage');
data.addRows(<%= DrugInr.generate_array(#patient) %>);
var options = {
vAxes: { 1: {title: 'Dose', format: '#.#', maxValue: 20},
0: {title: 'INR',format: '#.#', minValue: -1, baselineColor:"#CCCCCC"} },
hAxis: {title: 'Day'},
seriesType: 'bars',
bar: {
groupWidth: 5
},
series: {
0:{ type: "bars", targetAxisIndex: 1 },
1:{ type: 'line', targetAxisIndex: 0}
}
};
I have the following code which generates a column chart.
<script type="text/javascript">
//google.charts.load('current', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawBar);
function drawBar() {
var data = google.visualization.arrayToDataTable([
['Number of Visits', 'Average Check Size',{ role: 'style' }],
['8+', 26.22, '#083874'],
['4-7', 30.34,'#94CAFC'],
['2-3', 24.09,'#EBBA25'],
['1', 27.95,'#F59E47']
]);
var formatter = new google.visualization.NumberFormat({
fractionDigits: 1,
prefix: '$'
});
formatter.format(data, 1);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" }]);
var options = {
//chartArea: {width: '50%'},
hAxis: {
title: 'Average Check Size',
titleTextStyle: {italic: false},
minValue: 0,gridlines: { color: 'transparent'}
},
vAxis: {
minValue: 0,
title: 'Number of Visits',
titleTextStyle: {italic: false},
gridlines: { color: 'transparent'}},
//colors: ['red','green','blue','yellow'],
legend: {position: 'none'},
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_bar'));
chart.draw(view, options);
}
The output is a column chart with annotations on each of the bars. I want to have a similar kind of output but all four bars must have different colors. How do I do that? Please suggest
You can use the style role. There are examples on google charts page. And here is a jsfiddle.
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }],
['Copper', 8.94, '#b87333'], // RGB value
['Silver', 10.49, 'silver'], // English color name
['Gold', 19.30, 'gold'],
['Platinum', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
]);