Reputation: 167
So I have database where that gets random values at random times. example:
2019-02-22 12:05, 500
2019-02-22 12:15, 2
2019-02-22 12:19, 90
So I want to show it in a line chart. this is my code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"><script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart', 'line']});
google.setOnLoadCallback(drawAxisTickColors);
function drawAxisTickColors() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Price');
data.addColumn('datetime', 'Date');
var dateArr2 = (<?php echo json_encode($dateArr); ?>);
var number = (<?php echo json_encode($number); ?>);
var length = Math.min(dateArr2.length, number.length);
var rows = [];
for (var i = 0; i < length; ++i) {
rows.push([number[i], new Date(dateArr2[i]) ]);
}
data.addRows(rows);
var options = {
// backgroundColor: '#E4E4E4',
curveType: 'function',
chartArea: {
left: 0,
top: 0,
right: 0,
bottom: 0,
width: "100%",
height: "100%"
},
hAxis: {
textPosition: 'none',
baselineColor: 'none',
gridlines: {
color: 'none'
},
},
vAxis: {
textPosition: 'none',
baselineColor: 'none',
gridlines: {
color: 'none'
}
},
colors: ['#2098d4', '#ffffff'],
legend: 'none'
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);
chart.draw(data, options);
}
</script>
and this is how my database looks like this:
But my chart looks like this:
What am I doing wrong, please help.
EDIT
tried this:
number = number.map(Number);
after
var number = (<?php echo json_encode($number); ?>);
this is the result:
Upvotes: 4
Views: 71
Reputation: 61275
each chart has a specific data format,
for LineChart
, the first column is used as the x-axis,
each additional column appears on the y-axis.
in this case, to have the date on the x-axis,
just swap the order of the columns...
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Price');
and...
rows.push([new Date(dateArr2[i]), number[i]]);
ALSO, you're using an old version of google charts.
jsapi
should no longer be used, see update library loader code,
this will only change the load
statement.
from...
google.load('visualization', '1', {packages: ['corechart', 'line']});
google.setOnLoadCallback(drawAxisTickColors);
to...
google.charts.load('current', {packages:['corechart']});
google.charts.setOnLoadCallback(drawAxisTickColors);
note: the line
package is not needed, it is for material charts...
google.charts.Line
you're using a classic chart...
google.visualization.LineChart
Upvotes: 1