CanvasJS line chart generation? - javascript

I am busy trying to make a javascript chart for real-time data display. I found this CanvasJS API. The default code for that specific chart on their webpage is nice, but of course the part where they get the data, they have left the variable array empty and used a math randomize data function instead, in order that specific data will be randomly generated and used in the graph.
However I would like to full that array with my database data coming from a specific table I would like to use!
I have tried many things but if I implement my part, the graph won't display anymore. What am I doing wrong?
Here are the 3 codes I use:
The default code (just for comparison purpose):
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Live Random Data"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
My own chart-code, based on the above code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script src="jquery.js"></script>
<script src="jquery.canvasjs.js" ></script>
<script src="canvasjs.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
and my data.php which displays the following output:
[{"x":"1","y":"5"},{"x":"2","y":"5"},{"x":"3","y":"4"},{"x":"4","y":"1"},{"x":"5","y":"8"},{"x":"6","y":"9"},{"x":"7","y":"5"},{"x":"8","y":"6"},{"x":"9","y":"4"},{"x":"10","y":"7"}]
<?php
//header('Content-Type: application/json');
$con = mysqli_connect("localhost","root","","WebApplication");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}
else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM info");
while($row = mysqli_fetch_array($result))
{
$point = array("x" => $row['id'] , "y" => $row['acceleration']);
array_push($data_points, $point);
}
echo json_encode($data_points, 32); //define('JSON_NUMERIC_CHECK',32); // Since PHP 5.3.3
}
mysqli_close($con);
?>
Hopefully you have enough info!
Thank you
Mieer
EDIT
I swapped the code from 'my own chart' -code for the following, based on #feedback-comment from: Anjali Jain
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script src="jquery.js"></script>
<script src="jquery.canvasjs.js" ></script>
<script src="canvasjs.js"></script>
<script type="text/javascript" src="canvasjs.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
Yet, I still get nothing.

CanvasJS requires x and y values to be numbers while you are passing strings directly. You can convert them to numbers as shown below
$.getJSON("data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});

Related

How to show two charts in the same html page

I'm working on a project where I should show two kind of charts :
a Real time Chart and I'm using smoothie.js lib for this.
a normal chart with zoom option and I'm using canvas lib for this.
as it showen in the code below the smoothie.js use on the body tag an "onload" :
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>Pression en temps réel</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="smoothie.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.bufferX = [];
setInterval(function () {
if( typeof lastid == 'undefined' ) {
$.get( "../be.php/lastid_1", function( dataA ) {
lastid = dataA[0].id_x+1;
})
}
else {
$.get( "../be.php/1&"+lastid, function( dataB ) {
var i =0;
var j=0;
if( typeof counter == 'undefined' ) {
counter = 0;
}
if( typeof pck_prev == 'undefined' ) {
pck_prev = -1;
}
lastid = dataB[0].last_id;
for(i=0;i<dataB.length;i++) {
for(j=0;j<dataB[i].data.length;j++) {
if(dataB[i].data[j] !== "" && dataB[i].data[j] !== 0 && typeof dataB[i].data[j] !== 'undefined' && pck_prev !== dataB[i].pck) {
window.bufferX.push(dataB[i].data[j]);
}
}
pck_prev = dataB[i].pck;
}
if(typeof window.bufferX[counter] == 'undefined') {
data_p.append(new Date().getTime(), window.bufferX[counter-1]);
}
})
}
},3000);
var data_p = new TimeSeries();
setInterval(function() {
if(window.bufferX.length>50 && counter <window.bufferX.length)
{
if( typeof counter == 'undefined' ) {
counter = 0;
}
else {
data_p.append(new Date().getTime(), window.bufferX[counter]);
counter++;
}
}
}, 250);
function createTimeline() {
var chart = new SmoothieChart({responsive: true});
chart.addTimeSeries(data_p, { strokeStyle: 'rgba(0, 255, 0, 1)', fillStyle: 'rgba(0, 255, 0, 0.2)', lineWidth: 4 });
chart.streamTo(document.getElementById("chart"), 250);
}
</script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
zoomEnabled: true,
title:{
text: "Try Zooming And Panning"
},
axisY:{
includeZero: false
},
data: data, // random generator below
});
chart.render();
}
var limit = 1000; //increase number of dataPoints by increasing this
var y = 0;
var data = []; var dataSeries = { type: "line" };
var dataPoints = [];
for (var i = 0; i < limit; i += 1) {
y += (Math.random() * 10 - 5);
dataPoints.push({
x: i - limit / 2,
y: y
});
}
dataSeries.dataPoints = dataPoints;
data.push(dataSeries);
</script>
</head>
<body onload="createTimeline()">
<canvas id="chart" style="width:100%; height:700px;"></canvas>
<div id="chartContainer" style="height: 700px; width: 100%;">
</div>
</body>
</html>
The problem is if I delete onload from body tag I will get the canvas chart only and if I let it I will get the real time chart only.
I would like to have both charts showen on my page.
Thanks for reading.
window.onload and <body onload="yourfunction();"> are different ways of using the same event and you are using both which is causing the issue. The easiest way to fix this problem is that you should write both the implementation in one event either in window.onload or in onload of body tag.
Find the updated fiddle here.
You can find both the chart are visible at the same time.

Dynamic chart with CanvasJs doesn't get update while reading from a file

I've been trying to get a dynamic chart working with CanvasJs. I have a file that gets updated (by another program) and I would like to update my chart each time I have a new record.
I've seen this example (last chart) and I tried to do the same but I'm actually reading from a file.
Here is my code :
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var dps = [{x: new Date(2017, 04, 20, 07, 20, 00 ), y: 30}]; //dataPoints.
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: " Cooling Machine Status "
},
axisX:{
valueFormatString: "DD-MM-YY HH:mm:ss" ,
labelAngle: -50
},
axisY:{
title: "Cooling Temperature (F)"
},
data: [{
type: "line",
showInLegend: true,
name: "Temperature",
dataPoints : dps
}]
});
chart.render();
var updateChart = function () {
var rawFile = new XMLHttpRequest();
rawFile.open("GET","/analyticResults/coolingMachine.csv", true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var dps = csvLines = points = [];
csvLines = rawFile.responseText.split(/[\r?\n|\r|\n]+/);
for (var i = 0; i < csvLines.length; i++)
if (csvLines[i].length > 0) {
points = csvLines[i].split(",");
var dateTime = points[0].split(" ");//dateTime[0] = date, dateTime[1] = time
var date = dateTime[0].split("-");
var time = dateTime[1].split(":");
dps.push({
x: new Date(date[2], date[1], date[0], time[0], time[1], time[2]),
y: parseFloat(points[1])
});
}
}
}
};
rawFile.send(null);
if (dps.length > 10 )
{
dps.shift();
}
chart.render();
};
setInterval(function(){updateChart()}, 1000);
}
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 70%;">
</div>
</body>
</html>
When I debug the javascript I can see that the values are getting pushed in dps but the chart is not updating...
Did I miss someting ?
Thank you for your time
You are passing dps to chart-dataPoints. But at the same time you are pushing dps that is declared locally within updateChart method. Removing dps declaration within updateChart method should work in your case.

Google line chart not working

the following code writes data to the screen and this needs to be plotted in a graph. The graph should be similar to the attachment So, when the array indicator is calculated (line 112), it contains 3 subarrays: one with a date, one with normalised prices and one with the mRS values. The array indicator is also calculated 3 times: one for AAL, one for ABF and one for ADM. So I need 3 graphs displayed, one for each symbol.
So essentially the multilinechart code needs to be integrated into the transpose code whereby 3 line charts are generated, namely after the calculation of the indicator array
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var prices = [['Date', 'AAL', 'ABF', 'ADM'],
['2016-12-01', 1207.5, 2514.55, 1847.00],
['2016-11-01', 1123.5, 2475.00, 1901.00],
['2016-10-01', 1131, 2462.00, 1917.00],
['2016-09-01', 967.6, 2600.00, 2049.00],
['2016-08-01', 779.8, 3041, 2013.36],
['2016-07-01', 830.5, 2691, 2125.32],
['2016-06-01', 726.9, 2719, 1993.72],
['2016-05-02', 600.1, 2933.644, 1933.282],
['2016-04-01', 763.4, 3053.222, 1792.365],
['2016-03-01', 552.1, 3337.219, 1913.98],
['2016-02-01', 480.25, 3394.019, 1671.716],
['2016-01-04', 277.45, 3138.919, 1712.254],
['2015-12-01', 299.45, 3330.244, 1601.257],
['2015-11-02', 408.65, 3508.387, 1564.58],
['2015-10-01', 546.6, 3418.352, 1556.858],
['2015-09-01', 550.9, 3304.572, 1449.722],
['2015-08-03', 741, 3168.036, 1472.785],
['2015-07-01', 789.923, 3189.803, 1407.223],
['2015-06-01', 894.409, 2840.547, 1317.905],
['2015-05-01', 999.089, 2985.838, 1414.824],
['2015-04-01', 1076.017, 2817.219, 1458.897],
['2015-03-02', 985.457, 2778.762, 1432.678],
['2015-02-02', 1119.873, 3081.488, 1381.177],
['2015-01-01', 1030.099, 3059.794, 1355.894],
['2014-12-01', 1111.081, 3109.098, 1237.909],
['2014-11-03', 1223.068, 3134.425, 1161.125],
['2014-10-01', 1218.441, 2695.038, 1250.082],
['2014-09-01', 1280.913, 2621.644, 1201.39],
['2014-08-01', 1416.038, 2801.704, 1227.186],
['2014-07-01', 1461.646, 2718.524, 1339.334],
['2014-06-02', 1307.163, 2983.722, 1423.904],
['2014-05-01', 1332.301, 2943.89, 1340.253],
['2014-04-01', 1446.106, 2898.044, 1285.099],
['2014-03-03', 1395.374, 2712.71, 1290.464],
['2014-02-03', 1369.37, 2924.382, 1296.79],
['2014-01-01', 1284.4, 2648.331, 1305.827],
['2013-12-02', 1180.646, 2384.961, 1183.829],
['2013-11-01', 1206.584, 2212.07, 1123.282],
['2013-10-01', 1328.227, 2186.987, 1155.815],
['2013-09-02', 1357.743, 1809.787, 1114.245],
['2013-08-01', 1322.413, 1779.881, 1119.517],
['2013-07-01', 1242.815, 1875.387, 1245.585],
['2013-06-03', 1117.474, 1673.764, 1178.112],
['2013-05-01', 1347.412, 1738.319, 1187.878],
['2013-04-01', 1381.396, 1856.318, 1118.274],
['2013-03-01', 1493.496, 1823.7, 1162.796],
['2013-02-01', 1664.242, 1776.693, 1092.085],
['2013-01-01', 1633.503, 1677.881, 1067.642],
['2012-12-03', 1639.998, 1500.404, 1012.645]];
// Pairwise multiplication of the elements in two arrays; for use in mUp and mDown calculation
function dotproduct(a, b) {
var n = 0;
for (var i = 0; i < Math.min(a.length, b.length); i++) n += a[i][1] * b[i];
return n;
}
// Define array of weights that is global to the program
var weight = [];
// Weighting function
function weights() {
var k = 1;
var lambda = 2;
for (var x = 0.1; x < 20; x++) {
weight.push([x, k * Math.pow(x/lambda, k-1) * Math.exp(-Math.pow(x/lambda, k)) / lambda]);
}
}
// Create the weights
weights();
document.write(weight + '<hr>');
// Fetch first row of the prices array and keep the remainder as actual prices
var symbols = prices[0];
prices.shift();
// Loop through all columns of prices
for (var c in prices[0]) {
var min = prices[0][c];
var max = prices[0][c];
var up = [];
var down = [];
var indicator = [];
// Loop through all rows of prices and calculate the minimum and maximum, the up-value and down-value
for (var r in prices) {
min = Math.min(prices[r][c], min); // minimum price, for normalisation
max = Math.max(prices[r][c], max); // maximum price, for normalisation
var last = (typeof prices[parseInt(r)+1] != "undefined") ? prices[parseInt(r)+1][c] : 0;
up.push(Math.max(prices[r][c] - last, 0)); // up value
down.push(-Math.min(prices[r][c] - last, 0)); // down value
}
document.write('symbol: ' + symbols[c] + '<br>');
var mUp = []; // weighted up values
var mDown = []; // weighted down values
// Loop through all values of up and down and apply the weighting to the up and down values progressively
for (var i in up) {
mUp.push(dotproduct(weight, up));
up.shift(); // drop the first element off the up array
mDown.push(dotproduct(weight, down));
down.shift(); // drop the first element off the down array
}
// Add date and price to indicator array
for (var r in prices) {
indicator.push([prices[r][0], (prices[r][c]-min)/max, mUp[r]/(mUp[r]+mDown[r])]);
}
// *********
// Add the code to generate the line graph of array indicator here
// *********
document.write('indicator: ' + indicator + '<br>');
// Calculate percentile
document.write('first indicator: ' + indicator[0][2] + '<br>');
// Define a counter
var count = 0;
// Count the number of data points smaller than or equal to n
for (i in indicator) if (indicator[i][2] <= indicator[0][2]) count++;
document.write('count: ' + count + '<br>');
// Return the percentile
document.write('percentile: ' + count/indicator.length + '<br>');
document.write('<hr>');
}
</script>
Assuming that the array prices is the result of those calculations, you use .arrayToDataTable() to interface the data to the Google Visualization API.
SNIPPET
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title>Line Chart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'AAL', 'ABF', 'ADM'],
['2016-12-01', 1207.5, 2514.55, 1847.00],
['2016-11-01', 1123.5, 2475.00, 1901.00],
['2016-10-01', 1131, 2462.00, 1917.00],
['2016-09-01', 967.6, 2600.00, 2049.00],
['2016-08-01', 779.8, 3041, 2013.36],
['2016-07-01', 830.5, 2691, 2125.32],
['2016-06-01', 726.9, 2719, 1993.72],
['2016-05-02', 600.1, 2933.644, 1933.282],
['2016-04-01', 763.4, 3053.222, 1792.365],
['2016-03-01', 552.1, 3337.219, 1913.98],
['2016-02-01', 480.25, 3394.019, 1671.716],
['2016-01-04', 277.45, 3138.919, 1712.254],
['2015-12-01', 299.45, 3330.244, 1601.257],
['2015-11-02', 408.65, 3508.387, 1564.58],
['2015-10-01', 546.6, 3418.352, 1556.858],
['2015-09-01', 550.9, 3304.572, 1449.722],
['2015-08-03', 741, 3168.036, 1472.785],
['2015-07-01', 789.923, 3189.803, 1407.223],
['2015-06-01', 894.409, 2840.547, 1317.905],
['2015-05-01', 999.089, 2985.838, 1414.824],
['2015-04-01', 1076.017, 2817.219, 1458.897],
['2015-03-02', 985.457, 2778.762, 1432.678],
['2015-02-02', 1119.873, 3081.488, 1381.177],
['2015-01-01', 1030.099, 3059.794, 1355.894],
['2014-12-01', 1111.081, 3109.098, 1237.909],
['2014-11-03', 1223.068, 3134.425, 1161.125],
['2014-10-01', 1218.441, 2695.038, 1250.082],
['2014-09-01', 1280.913, 2621.644, 1201.39],
['2014-08-01', 1416.038, 2801.704, 1227.186],
['2014-07-01', 1461.646, 2718.524, 1339.334],
['2014-06-02', 1307.163, 2983.722, 1423.904],
['2014-05-01', 1332.301, 2943.89, 1340.253],
['2014-04-01', 1446.106, 2898.044, 1285.099],
['2014-03-03', 1395.374, 2712.71, 1290.464],
['2014-02-03', 1369.37, 2924.382, 1296.79],
['2014-01-01', 1284.4, 2648.331, 1305.827],
['2013-12-02', 1180.646, 2384.961, 1183.829],
['2013-11-01', 1206.584, 2212.07, 1123.282],
['2013-10-01', 1328.227, 2186.987, 1155.815],
['2013-09-02', 1357.743, 1809.787, 1114.245],
['2013-08-01', 1322.413, 1779.881, 1119.517],
['2013-07-01', 1242.815, 1875.387, 1245.585],
['2013-06-03', 1117.474, 1673.764, 1178.112],
['2013-05-01', 1347.412, 1738.319, 1187.878],
['2013-04-01', 1381.396, 1856.318, 1118.274],
['2013-03-01', 1493.496, 1823.7, 1162.796],
['2013-02-01', 1664.242, 1776.693, 1092.085],
['2013-01-01', 1633.503, 1677.881, 1067.642],
['2012-12-03', 1639.998, 1500.404, 1012.645]
]);
var options = {
title: 'Line Chart',
curveType: 'function',
legend: {
position: 'bottom'
}
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>

Efficient real-time plotting using Plot.ly

I push data from node.js using socketio to the visualization website. The desired interval is 1ms.
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
</head>
<div id="tester" style="width:90%;height:70%;"></div>
<script type="text/javascript">
window.onload = function() {
console.log("testing")
TESTER = document.getElementById('tester');
var N = 1000
signals = {
time: [],
top: [],
bottom: []
};
var layout = {
yaxis: {range:[0, 1024]}
}
var socket = io();
console.log("Set up succefully!")
socket.on('data', function (msg) {
if (signals.time.length > N) {
signals.time.shift();
signals.top.shift();
signals.bottom.shift();
}
signals.time.push(msg['time'])
signals.top.push(msg['top'])
signals.bottom.push(msg['bottom'])
var trace1 = { x: signals.time,
y: signals.top}
var trace2 = { x: signals.time,
y: signals.bottom}
Plotly.newPlot( TESTER, [trace1, trace2], layout);
});
}
</script>
This works if I set the interval to be 1s. If I set it smaller than 0.5s, the whole page is not responding. I checked in the chrome application, and can see the socket io frames arriving. How can I fix this problem?

Google Chart : Unable to get property 'arrayToDataTable'

I want to show google chart using data that i acquired from SQL server using javascript. But i got IE error "Unable to get property arrayToDataTable" even i already add google chart JS. I already check the data by alert it, and the data is ok. How to fix this?
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var array = loadData();
google.load("visualization", "1.1", {packages:["bar"]});
google.setOnLoadCallback(drawChart(array));
function loadData(){
var array = [
['Year', 'Sales', 'Expenses', 'Profit']
];
//Connection
var connection = new ActiveXObject("ADODB.Connection") ;
var connectionstring="Provider=SQLOLEDB.1;Password=Password1234;Persist Security Info=True;User ID=sa;Initial Catalog=all_data;Data Source=172.16.11.90";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open("SELECT * FROM bar_chart", connection);
rs.MoveFirst;
while(!rs.eof)
{
array.push([rs.fields(0), parseInt(rs.fields(1)), parseInt(rs.fields(2)), parseInt(rs.fields(3))]);
rs.movenext;
}
rs.close;
connection.close;
return array;
}
function drawChart(x) {
alert(x[4][3]);
var data = google.visualization.arrayToDataTable(x);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017'
},
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, options);
}
</script>
And here is my html:
<body>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>
</body>
This error occurs since google.setOnLoadCallback function expects a callback as an argument.
Replace:
var array = loadData();
google.setOnLoadCallback(drawChart(array));
In this case drawChart function is invoked immediately without
waiting google visualization API to load
with:
google.setOnLoadCallback(function () {
var array = loadData();
drawChart(array);
});
Example
google.load("visualization", "1.1", { packages: ["bar"] });
google.setOnLoadCallback(function () {
var data = generateData();
drawChart(data);
});
function generateData() {
var data = [
['Year', 'Sales', 'Expenses', 'Profit']
];
for (var year = 2000; year < 2010; year++) {
data.push([year.toString(), getRandomArbitrary(100, 200), getRandomArbitrary(100, 400), getRandomArbitrary(100, 500)]);
}
return data;
}
function drawChart(data) {
var dataTable = google.visualization.arrayToDataTable(data);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017'
},
bars: 'horizontal' // Required for Material Bar Charts.
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(dataTable, options);
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>

Categories

Resources