Fill in JSchart with JSON file - javascript

I'm creating a JSchart with some JSON data i gathered from a FitBit.
https://jsfiddle.net/d0708akg/4/
This is my Code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="chart-wrap" style="width: 100%; height: 100%;">
<canvas id="canvas" style="width: 100%; height: auto;"></canvas>
</div>
<div id="js-legend" class="chart-legend"></div>
</body>
</html>
<script>
$.getJSON("fitbitdata.json", function (json) {
// will generate array with ['Monday', 'Tuesday', 'Wednesday']
var labels = json.map(function(item) {
return item.Weight;
});
});
//there was a comma separating these two var declarations. Changed it to a `;`
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "Gewicht",
fillColor : "rgba(141,255,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
backgroundColor : "rgba(215, 44, 44, 0.2)",
pointStrokeColor : "#fff",
data: []
},
{
label : "BMI",
fillColor : "rgba(215, 40, 40, 0.9)",
strokeColor : "rgba(151,187,205,1)",
backgroundColor : "green",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : []
}
]
};
// I put the canvas element in a var just to clean up the 'new Chart' syntax
var canvas = document.getElementById("canvas").getContext("2d");
//this is the new syntax
var myLine = new Chart(canvas, {
type: 'line',
data: lineChartData//,
//options: options //if you had any to pass
});
</script>
What I'm trying to do is this:
I've got a json file with some data like this:
[{<br>
"Datum":"Week 1",
"Weight":74,
"BMI":21.39,
"Fat":0,
"CaloriesBurned":2.103,
"Steps":3.53,
<br>
}]
when I do alert(labels)
It shows all the values. Why not in my jschart?

Related

Using Different Colors In a Chart

My Code:
<div><canvas id="canvas_line" height="200" width="800"></canvas></div>
<div><canvas id="canvas_bar" height="200" width="800"></canvas></div>
<script>
var lineChartData = {
labels : ["14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets : [
{
label: "CPU IDLE",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [85,35,65,59,90,81,56,55,40,100]
}
]
}
var barChartData = {
labels : ["12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : [85,35,65,59,90,81,56,55,40,100]
}
]
}
var ctx_line = document.getElementById("canvas_line").getContext("2d");
window.myLine = new Chart(ctx_line).Line(lineChartData, {
responsive: true
});
var ctx_bar = document.getElementById("canvas_bar").getContext("2d");
window.myLine = new Chart(ctx_bar).Bar(barCharData, {
responsive: true
});
</script>
It looks like this, everything is grey.
But I'd like to change the lineChart's pointColor and barChart's fillcolor to red if its data is above 80, the data below 80 are still grey.
I want it like this, but I don't know how to use different colors in a canvas.
<!DOCTYPE html>
<html>
<head>
<title>123</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://apps.bdimg.com/libs/Chart.js/0.2.0/Chart.min.js"></script>
</head>
<body>
<canvas id="chartCanvas" height="200" width="800"></canvas>
<script>
$(document).ready(function() {
var chartData = {
labels: ["12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets: [
{
data : [85,35,65,59,90,81,56,55,40,100],
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)'
}
]
}
var chartCanvas = document.getElementById("chartCanvas").getContext("2d");
var barChart = new Chart(chartCanvas).Bar(chartData, {responsive: true});
// Set warning color
var bars = barChart.datasets[0].bars;
for(var i = 0; i < bars.length ; i++) {
if(bars[i].value > 80) {
bars[i].fillColor = "rgba(255, 0, 0, 0.2)";
bars[i].strokeColor = "rgba(220, 0, 0, 0.5)";
}
}
// Update the chart
barChart.update();
});
</script>
</body>
</html>
You have to loop to all the bars/points of your chart, check if the value is over 80 and set the color.
Here is an example for the bar chart:
var bars = barChart.datasets[0].bars;
for(var i = 0; i < bars.length; i++) {
if(bars[i].value > 80) {
bars[i].fillColor = "rgba(255, 0, 0, 0.2)";
bars[i].strokeColor = "rgba(220, 0, 0, 0.5)";
}
}
// Update the chart
barChart.update();
Check out this fiddle for a working demo.
To set the color on a line chart you just have to iterate over the points instead of the bars:
var points = lineChart.datasets[0].points;
And of course set the pointColor or whatever you want.

Chart.js sets canvas width and height to 0 when using angular tabs

When I call a new tab, the width and height of the canvas set to 0 and I cannot see the graph that should be in the tab. I have seen other answers to this problem but they were all in jquery and my whole app is currently in angular.
This is the html
<div class="container col-xs-10">
<h3>Comparison Results</h3>
<section ng-app="myApp" ng-controller="TabController as tab">
<ul class="nav nav-pills">
<li ng-class="{active:tab.isSet(1)}"><a href ng-click="tab.setTab(1)">Exe Count</a></li>
<li ng-class="{active:tab.isSet(2)}"><a href ng-click="tab.setTab(2)">Exe Time</a></li>
<li ng-class="{active:tab.isSet(3)}"><a href ng-click="tab.setTab(3)">CPU Time</a></li>
<li ng-class="{active:tab.isSet(4)}"><a href ng-click="tab.setTab(4)">Wait Time</a></li>
<li ng-class="{active:tab.isSet(5)}"><a href ng-click="tab.setTab(5)">Rows Read</a></li>
<li ng-class="{active:tab.isSet(6)}"><a href ng-click="tab.setTab(6)">Rows Written</a></li>
<li ng-class="{active:tab.isSet(7)}"><a href ng-click="tab.setTab(7)">Logical Reads</a></li>
<li ng-class="{active:tab.isSet(8)}"><a href ng-click="tab.setTab(8)">Physical Reads</a></li>
</ul>
<div ng-show="tab.isSet(1)">
<canvas id="numExe" width="1400" height="550"></canvas>
</div>
<div ng-show="tab.isSet(2)">
<canvas id="exeTime" width="1400" height="550"></canvas>
</div>
<div ng-show="tab.isSet(3)">
<canvas id="cpuTime" width="1400" height="550"</canvas>
</div>
</section>
This is where the canvas and tabs are set
$scope.makeGraph = function(){
var numExeData = {
labels : numExe.hash,
datasets : [ {
label : "Baseline",
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill : "rgba(220,220,220,0.75)",
highlightStroke : "rgba(220,220,220,1)",
data : numExe.base
}, {
label : "Comparative",
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,0.8)",
highlightFill : "rgba(151,187,205,0.75)",
highlightStroke : "rgba(151,187,205,1)",
data : numExe.compare
} ]
};
var exeTimeData = {
labels : exeTime.hash,
datasets : [ {
label : "Baseline",
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill : "rgba(220,220,220,0.75)",
highlightStroke : "rgba(220,220,220,1)",
data : exeTime.base
}, {
label : "Comparative",
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,0.8)",
highlightFill : "rgba(151,187,205,0.75)",
highlightStroke : "rgba(151,187,205,1)",
data : exeTime.compare
} ]
};
var cpuTimeData = {
labels : cpu.hash,
datasets : [ {
label : "Baseline",
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill : "rgba(220,220,220,0.75)",
highlightStroke : "rgba(220,220,220,1)",
data : cpu.base
}, {
label : "Comparative",
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,0.8)",
highlightFill : "rgba(151,187,205,0.75)",
highlightStroke : "rgba(151,187,205,1)",
data : cpu.compare
} ]
};
var numExe = document.getElementById("numExe").getContext("2d");
var numExeChart = new Chart(numExe).Bar(numExeData, { multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>", barValueSpacing: 20 });
var exeTime = document.getElementById("exeTime").getContext("2d");
var exeTimeChart = new Chart(exeTime).Bar(exeTimeData, { multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>", barValueSpacing: 20 });
var cpuTime = document.getElementById("cpuTime").getContext("2d");
var cpuTimeChart = new Chart(cpuTime).Bar(cpuTimeData, { multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>", barValueSpacing: 20 });
}
This is the tab controller
app.controller('TabController', function() {
this.tab = 1;
this.setTab = function(tabId) {
this.tab = tabId;
};
this.isSet = function(tabId) {
return this.tab === tabId;
};
});

How to plot line chart using chart.js with ajax?

I am trying to plot a line chart using chart.js with AJAX but not successful yet. The chart is plotting very fine on normal form submission and window onload event but when I use AJAX I am not able to plot it. Actually I don't know how to achieve it when the data comes from server after ajax call.
HTML:
<form method="post" action="" id="order_form">
<label for="selogtype">Graph Type:</label>
<select name="selogtype" id="selogtype">
<option value="total_order_value">Total Order Value</option>
<option value="total_order_qty">Total Order Quantity</option>
<option value="avg_order_value">Average Order Value</option>
<option value="avg_order_qty">Average Order Quantity</option>
</select>
<br /><br />
<label for="radodays">Duration:</label>
<input type="radio" name="radoduration" id="radodays" value="days" checked='checked' /><label for="radodays">Days</label>
<input type="radio" name="radoduration" id="radodates" value="dates" /><label for="radodates">Date Range</label>
<div id="div_odays">
<select name="seloduration">
<option value="week">Last 7 Days</option>
<option value="month">Last 30 Days</option>
<option value="curweek">Current Week</option>
<option value="curmonth">Current Month</option>
</select>
</div>
<div id="div_odate">
<span class="spanodate">Start Date:</span> <input type="text" name="txtosdate" id="txtosdate" value="" />
<span class="spanodate">End Date:</span> <input type="text" name="txtoedate" id="txtoedate" value="" />
</div>
<input type="submit" name="btnorderchart" id="btnorderchart" value="Draw Chart" />
</form>
<div id="outer_ocanvas" style="margin-top:25px;">
<canvas id="ocanvas" height="400" width="800"></canvas>
</div>
JS:
// ajax part of chart //
// order //
$("#order_form").submit(function(){
var btnorderchart = $("#btnorderchart").attr("name") + "=" + $("#btnorderchart").val();
$.ajax({
beforeSend: function(){ sendRequest("outer_ocanvas"); },
cache: false,
type: "POST",
dataType: "json",
url: "ajax/chart.php",
data: $(this).serialize() + "&" + btnorderchart,
success: function(data){
//alert(data.labels);
//alert(data.points);
var lineChartData = {
labels : "[" + data.labels + "]",
datasets : [
{
label: "Recent Orders",
fillColor : "rgba(150,150,245,0.2)",
strokeColor : "rgba(0,0,255,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : "[" + data.points + "]",
}
]
}
var ctx = document.getElementById("ocanvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: false
});
},
});
return false;
});
In AJAX file chart.php (remote server file), I am sending the data through
echo json_encode(array('labels' => $labels, 'points' => $points));
The data comes in correct format what we require in chart.js but I guess the below is the part which have something wrong:
var ctx = document.getElementById("ocanvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: false
});
},
Because in normal way on page loading after form submission, we usually draw the chart by
window.onload = function(){
var ctx = document.getElementById("ocanvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: false
});
}
But in AJAX, i don't know how to do it after successful response from server.
EDIT:
After applying some solution given by some users on this website, my latest updated code in a standalone file is:
index.html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>AJAX JSON Chart</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript">
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: false
});
}
// ajax part of chart //
$(document).ready(function(e) {
$("#frm1").submit(function(){
var canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
// ctx = $('#canvas').get(0).getContext("2d");
var btnchart = $("#btnchart").attr("name") + "=" + $("#btnchart").val();
$.ajax({
//beforeSend: function(){ sendRequest("canvas"); },
cache: false,
type: "POST",
dataType: "json",
url: "ajax/chart.php",
data: $(this).serialize() + "&" + btnchart,
success: function(data){
//alert(data.labels);
//alert(data.points);
renderGraph(data.labels, data.points, ctx);
},
});
return false;
});
});
var renderGraph = function (labels, points, ctx) {
// var ctx = $("#canvas")[0].getContext("2d");
var lineChartData = {
labels: "[" + labels + "]",
datasets: [
{
label: "Recent Orders",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: "[" + points + "]",
}
]
};
var myChart = new Chart(ctx)
.Line(lineChartData, {
responsive: false,
animation: false
});
//myChart.update(lineChartData);
}
function sendRequest(id)
{
$("#"+id).html('<div style="width:100px; margin:0 auto;"><img id="loader-img" alt="" src="images/preloader.gif" width="100" height="100" /></div>');
}
</script>
</head>
<body>
<div style="width:30%">
<div>
<canvas id="canvas" height="450" width="960"></canvas>
</div>
</div>
<form id="frm1" name="frm1" method="post" action="">
<input type="submit" name="btnchart" id="btnchart" value="Draw Chart" />
</form>
</body>
</html>
chart.php:
<?php
$labels = array('29 April 2015', '30 April 2015', '1 May 2015', '2 May 2015', '3 May 2015', '4 May 2015', '5 May 2015');
$points = array('100', '250', '10', '35', '73', '0', '25');
echo json_encode(array('labels' => $labels, 'points' => $points));
?>
On first time page loads, the output is:
After clicking button "Draw Chart", the output comes through AJAX is:
But when i hover my mouse over the image, it automatically converts into first image. Strange!!!
I know this is old, but i had the same problem with my ajax implementation and i found the solution.
adding:
dataType: 'json'
will fix this problem.
example request
$.ajax({url: "chartData.php",
async: false,
dataType: 'json',
success: function(result){
//...
}});
You should use return instead of echo in your php script.
Assume your php script will return right data.
In your html.
<canvas id="request" width="450" height="200"></canvas>
In jquery,
$(document).ready(function(){
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/chart.php",
data: //data to send,
beforeSend: function(){
// Do staff before send
},
success: function(data){
renderGraph(data.labels, data.points);
}
});
});
var renderGraph = function (labels, points) {
var canvas = $("#request")[0].getContext("2d");
var data = {
labels: labels,
datasets: [
{
label: "Recent Orders",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: points
}
]
};
var myChart = new Chart(canvas)
.Line(data, {
responsive: true,
animation: true
});
}
Hope it will help!

Updating chart.js in AJAX doesn't render the graph properly

I am trying to plot a line chart using chart.js with AJAX but the chart is not plotted properly when data comes from server. The chart is plotting fine on window onload event but with AJAX it failed to render properly. What could be the issue? Here is my code -
index.html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>AJAX JSON Chart</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript">
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: false
});
}
// ajax part of chart //
$(document).ready(function(e) {
$("#frm1").submit(function(){
var canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
var btnchart = $("#btnchart").attr("name") + "=" + $("#btnchart").val();
$.ajax({
//beforeSend: function(){ sendRequest("canvas"); },
cache: false,
type: "POST",
dataType: "json",
url: "ajax/chart.php",
data: $(this).serialize() + "&" + btnchart,
success: function(data){
//alert(data.labels);
//alert(data.points);
renderGraph(data.labels, data.points, ctx);
},
});
return false;
});
});
var renderGraph = function (labels, points, ctx) {
var lineChartData = {
labels: "[" + labels + "]",
datasets: [
{
label: "Recent Orders",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: "[" + points + "]",
}
]
};
var myChart = new Chart(ctx)
.Line(lineChartData, {
responsive: false,
animation: false
});
myChart.update(lineChartData);
}
function sendRequest(id)
{
$("#"+id).html('<div style="width:100px; margin:0 auto;"><img id="loader-img" alt="" src="images/preloader.gif" width="100" height="100" /></div>');
}
</script>
</head>
<body>
<div style="width:30%">
<div>
<canvas id="canvas" height="450" width="960"></canvas>
</div>
</div>
<form id="frm1" name="frm1" method="post" action="">
<input type="submit" name="btnchart" id="btnchart" value="Draw Chart" />
</form>
</body>
</html>
chart.php:
<?php
$labels = array('29 April 2015', '30 April 2015', '1 May 2015', '2 May 2015', '3 May 2015', '4 May 2015', '5 May 2015');
$points = array('100', '250', '10', '35', '73', '0', '25');
echo json_encode(array('labels' => $labels, 'points' => $points));
?>
On first time page loads, the output is:
After clicking button "Draw Chart", the output comes through AJAX is:
But when i hover my mouse over the image, it automatically converts into first image i.e. the first correct graph when window was loaded. Strange!!!
so before drawing your chart again, what you can do just destroy the earlier created chart with
myChart.destroy();
or
myChart.clear();
and then redraw your chart. Then hopefully it will work correct

chart.js in meteor not drawing

In a meteor project, I have copied the demo code from chart.js into my client folder as follows:
function drawChart(){
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}
//Get context with jQuery - using jQuery's .get() method.
var ctx = $("#myChart").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
var myNewChart = new Chart(ctx);
new Chart(ctx).Line(data);
}
Meteor.startup(function() {
drawChart();
});
In the HTML I have:
<canvas id="myChart" width="400" height="400"></canvas>
Nothing is drawn, nor any errors thrown. The same code run in the console produces a chart. What am I missing?
I am using the meteor-chartjs library.
Add the canvas to a template
<template name="chart">
<canvas id="myChart" width="400" height="400"></canvas>
</template>
Use the template rendered callback to call your drawChart function
Template.chart.rendered = function(){
drawChart();
}
function drawChart(){
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}
//Get context with jQuery - using jQuery's .get() method.
//var ctx = $("#myChart").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
//var myNewChart = new Chart(ctx);
//new Chart(ctx).Line(data);
//modify this
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).PolarArea(data);
}
Meteor.startup(function() {
drawChart();
});

Categories

Resources