How can I show JSON data in Chart.js with Javascript if static values are working but dynamic from mySQL are not? - javascript

I have JSON data in the following form:
{
"labels": ["12.11.2016", "13.11.2016", "14.11.2016", ...],
"temperature": ["12", "35", "27", ...],
"humidity": ["56", "70", "87", ...]
}
and want to show it in Chart.js.
I already found this example but it somehow isn't working...
My code for Chart.js is the following:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="/node_modules/chart.js/dist/Chart.bundle.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
canvas{
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
<title>Temperatur und Feuchtigkeit</title>
</head>
<body>
<div style="width: 100%;">
<canvas id="canvas"></canvas>
</div>
<script>
var data;
$.get('GetTestData.php', function(dataGet) {
data = JSON.parse(dataGet);
//console.log(data['labels']);
});
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var randomColorFactor = function() {
return Math.round(Math.random() * 255);
};
var randomColor = function(opacity) {
return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.9') + ')';
};
var config = {
type: 'line',
data: {
//labels: ["11.11.2016", "12.11.2016", "13.11.2016", "14.11.2016", "15.11.2016", "16.11.2016", "17.11.2016"],
labels: labels
datasets: [{
label: "Temperatur",
//data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()],
data: temperature
fill: false
}//,
//{
// label: "Feuchtigkeit",
// data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()],
// fill: false
//}]
},
options: {
responsive: true,
title:{
display:true,
text:'Temperatur und Feuchtigkeit'
},
tooltips: {
mode: 'label'
},
hover: {
mode: 'dataset'
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Datum'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Wert'
},
ticks: {
suggestedMin: -20,
suggestedMax: 250,
}
}],
}
}
};
var labels = [], temperature=[], humidity=[];
data['labels'].forEach(function(singleResult) {
labels.push(singleResult);
});
data['temperature'].forEach(function(singleResult) {
temperature.push(singleResult);
});
data['humidity'].forEach(function(singleResult) {
humidity.push(singleResult);
});
$.each(config.data.datasets, function(i, dataset) {
dataset.borderColor = randomColor(1.0);
dataset.backgroundColor = randomColor(1.0);
dataset.pointBorderColor = randomColor(1.0);
dataset.pointBackgroundColor = randomColor(1.0);
dataset.pointBorderWidth = 1;
});
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
</script>
</body>
</html>
With static values I get an very nice graph like this:
But the dynamic data load (like in the above code) is not working :/ Does anyone have an idea here?
The error I'm getting is:
SyntaxError: missing } after property list[Weitere Informationen]

I now managed to resolve this on my own, code is below:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="/node_modules/chart.js/dist/Chart.bundle.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
canvas{
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
<title>Temperatur und Feuchtigkeit</title>
</head>
<body>
<div style="width: 100%;">
<canvas id="canvas"></canvas>
</div>
<script>
var data = [], labels = [], temperature=[], humidity=[];
$.get('GetTestData.php', function(dataGet) {
data = JSON.parse(dataGet);
data['labels'].forEach(function(singleResult) {
labels.push(singleResult);
});
data['temperature'].forEach(function(singleResult) {
temperature.push(singleResult);
});
data['humidity'].forEach(function(singleResult) {
humidity.push(singleResult);
});
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
});
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var randomColorFactor = function() {
return Math.round(Math.random() * 255);
};
var randomColor = function(opacity) {
return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.9') + ')';
};
var config = {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "Temperatur",
data: temperature,
fill: false
},
{
label: "Feuchtigkeit",
data: humidity,
fill: false
}]
},
options: {
responsive: true,
title:{
display:true,
text:'Temperatur und Feuchtigkeit'
},
tooltips: {
mode: 'label'
},
hover: {
mode: 'dataset'
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Datum'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Wert'
},
ticks: {
suggestedMin: -20,
suggestedMax: 250,
}
}],
}
}
};
$.each(config.data.datasets, function(i, dataset) {
dataset.borderColor = randomColor(1.0);
dataset.backgroundColor = randomColor(1.0);
dataset.pointBorderColor = randomColor(1.0);
dataset.pointBackgroundColor = randomColor(1.0);
dataset.pointBorderWidth = 1;
});
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
</script>
</body>
</html>
Result looks as following:

Related

Get X-coordinates for bars in chart.js 4

I use Chart.js v4.2.1
<html>
<head>
<meta charset="utf-8" />
<title>Bar chart</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div>
<canvas id="barchart"></canvas>
</div>
</body>
<script type="text/javascript">
var canvas = document.getElementById('barchart');
var chart = new Chart(canvas,
{
type: 'bar',
data:
{
labels: ["Audi", "VW", "KIA"],
datasets:
[
{
label: "Cars",
backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f"],
data: [2601, 4769, 602],
},
],
},
});
</script>
</html>
To get number of bars I execute chart.data.datasets[0].data.length and get 3.
To get the Y-value for the first bar I do chart.data.datasets[0].data[0] and get 2601.
How do I get the X-values (X-coordinates) for the bars?
(I am not interested in using any plugin).
Added:
Here is a sample where chart.scales.x is defined but chart.scales.y is not.
This happen when I add yAxisID which I need in my complete work.
<html>
<head>
<meta charset="utf-8" />
<title>Bar chart</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div>
<canvas id="barchart"></canvas>
<div id="debug"></div>
</div>
<script type="text/javascript">
var canvas = document.getElementById('barchart');
var chart = new Chart(canvas,
{
type: 'bar',
data:
{
labels: ["Audi", "VW", "KIA"],
datasets:
[
{
label: "Cars",
backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f"],
data: [2601, 4769, 602],
yAxisID: "cars",
},
],
},
options:
{
scales:
{
cars:
{
position: "left",
ticks:
{
color: "red",
},
grid:
{
display: true,
},
},
},
},
});
var dataSets = chart.data.datasets;
var xPos = chart.scales.x.getPixelForValue(dataSets[0].data[0]);
try
{
var yPos = chart.scales.cars.getPixelForValue(dataSets[0].data[0]); // --> here y is undefined
document.getElementById("debug").innerHTML = "xPos=" + xPos + ", yPos=" + yPos;
}
catch(e)
{
document.getElementById("debug").innerHTML = "xPos=" + xPos + "<br>" + e;
}
</script>
</body>
</html>
You can use the following code: chartInstance.scales.x.getPixelForValue(chart instance.data.labels[labelIndex]

Render images as labels on Y axis

I'm using chart.js to graph my data.
I'm wondering if I can show the flag image/icon PNG for the labels.
function drawChart(obj, columnName, type = 'bar', selectedVal){
var ajax = $.ajax({url: '/query/' + obj + '/'+ columnName + '/' + selectedVal });
ajax.done(function (response) {
console.log('Response from API >>',response);
$('.lds-ripple').fadeOut();
var selector = `chart-${columnName}`;
var chartHtml = `<div class="col-sm-6"><canvas class="chart" id="${selector}" height="200"></canvas></div>`;
$('.charts').append(chartHtml);
keys = [];
values = [];
var length = 0
$.each(response, function(key,val) {
//console.log(key+val);
length++;
if(length<15){
keys.push(key);
values.push(val);
}
});
var showLegend = false;
if(type == 'doughnut' || type == 'radar' || type == 'polarArea' || type == 'pie'){
showLegend = true;
}
let chart = document.getElementById(selector).getContext('2d');
let xAxisTitle = columnName;
var sumOfAllValues = values.reduce((a, b) => a + b, 0);
Chart.defaults.global.defaultFontColor = "#fff";
var ticksDisplay = true;
if(columnName == 'country'){
ticksDisplay = false;
}
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png'];
new Chart(chart, {
type: type, // bar, horizontalBar, pie, line, doughnut, radar, polarArea
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
xAxis.ticks.forEach((value, index) => {
var x = xAxis.getPixelForTick(index);
var y = yAxis.getPixelForTick(index);
var image = new Image();
image.src = images[index],
ctx.drawImage(image, x - 12, yAxis.bottom + 10);
// ctx.drawImage(image, x + 12, yAxis.left - 10);
});
}
}],
data:{
labels: keys,
datasets:[{
label:'Count',
data:values,
borderWidth:2,
hoverBorderWidth:2,
hoverBorderColor:'#fff',
color:'#fff',
backgroundColor: neonBgColors,
borderColor: neonBgBorders,
defaultFontColor: 'white'
}
]
},
options:{
title:{
display:true,
fontSize: 20,
text: columnName + '(' + sumOfAllValues + ')'
},
legend:{
display:showLegend,
position:'right',
labels:{
fontColor:'#000'
}
},
scales: {
xAxes: [{
ticks: {
precision:0,
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: xAxisTitle + ' (' + sumOfAllValues + ')'
}
}],
yAxes: [{
ticks: {
precision:0,
beginAtZero: true,
display: ticksDisplay,
},
scaleLabel: {
display: true,
// labelString: 'Visitor Count'
}
}]
},
layout: {
padding: {
bottom: 30
}
},
}
});
});
}
I kept getting
I adapted the code of this answer and came up with the following solution for your case.
const labels = ['Red Vans', 'Blue Vans', 'Green Vans', 'Gray Vans'];
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png']
.map(png => {
const image = new Image();
image.src = png;
return image;
});
const values = [48, 56, 33, 44];
new Chart(document.getElementById("myChart"), {
type: "horizontalBar",
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
yAxis.ticks.forEach((value, index) => {
var y = yAxis.getPixelForTick(index);
ctx.drawImage(images[index], xAxis.left - 40, y - 10);
});
}
}],
data: {
labels: labels,
datasets: [{
label: 'My Dataset',
data: values,
backgroundColor: ['red', 'blue', 'green', 'lightgray']
}]
},
options: {
responsive: true,
layout: {
padding: {
left: 50
}
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
display: false
}
}],
xAxes: [{
ticks: {
beginAtZero: true
}
}],
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Chartjs doughnut with multiple dataset issue in legend creation

I am using chartjs & creating a donut chart with multiple datasets. So I have to show individual labels & also the legends.
There was some issue in displaying labels for multiple datasets so I used a hack from here.
However, I have to show legends as well & I am unable to show it properly.
Here's my fiddle of what i have tried.
https://jsfiddle.net/pyva3fos/
HTML :
<div id="canvas-holder" style="width:100%">
<canvas id="myChart" width="400" height="400" />
</div>
Script :
var ctx = $("#myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Market ", "J1", "J2","Market","J share"],
datasets: [{
data: [61, 11,27],
backgroundColor: [
'#00205A',
'#97BAFF',
'#D9D9D9'
],
labels: [
'Market Share',
'J1',
'J2'
]
}, {
data: [61, 39],
backgroundColor: [
'#00205A',
'#747474',
],
labels: [
'Market Share ',
'J Share',
],
}, ]
},
options: {
responsive: true,
legend: {
display: true,
position:'bottom'
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ': ' + dataset.data[index];
}
}
}
}
});
Used the legendCallback function to create a separate legend.
https://jsfiddle.net/ztnb3h7y/
HTML :
<div id="canvas-holder" style="width:100%">
<canvas id="myChart" width="400" height="400" />
</div>
<div id="chartjs-legend" style="width:100%;" >
</div>
CSS :
.Mylegend { list-style: none; }
.Mylegend li { float: left; margin-right: 10px; }
.Mylegend span
{ border: 1px solid #ccc; float: left; width: 15px; height: 12px; margin: 2px; }
JS :
function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i].label == obj.label ) {
return true;
}
}
return false;
}
var ctx = $("#myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Market ", "J1", "J2","Market","J Share"],
datasets: [{
data: [61, 11,27],
backgroundColor: [
'#00205A',
'#97BAFF',
'#D9D9D9',
'#00205A',
'#747474',
],
labels: [
'Market Share',
'J1',
'J2'
]
}, {
data: [61, 39],
backgroundColor: [
'#00205A',
'#747474',
],
labels: [
'Market Share',
'J Share',
],
}, ]
},
options: {
responsive: true,
showAllTooltips: true,
legendCallback: function(chart) {
var text = [];
var legs = [];
for( var j=0; j<chart.data.datasets.length;j++)
{
for (var i = 0; i < chart.data.datasets[j].data.length; i++)
{
var newd = { label: chart.data.datasets[j].labels[i] , color: chart.data.datasets[j].backgroundColor[i] };
if( !containsObject (newd,legs) )
{
legs.push(newd);
}
}
}
text.push('<ul class="Mylegend ' + chart.id + '-legend">');
for( var k =0;k<legs.length;k++)
{
text.push('<li><span style="background-color:' + legs[k].color + '"></span>');
text.push(legs[k].label);
text.push('</li>');
}
text.push('</ul>');
return text.join("");
},
legend: {
display: false,
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ': ' + dataset.data[index];
}
}
}
}
});
$("#chartjs-legend").html(myChart.generateLegend());

Horizontal stacked angular bar charts

I am trying to implement an Angular horizontal stacked bar chart- Something like this example.
However, I want just one bar that is stacked.
I am working with AngularJS and Chart.js. I have the example showing on the page.
In the PieController, ChartData contains:
{"data":["63","38"],"labels":["Ford","GM"]}
In the example, instead of the label on the outside, I would like the label and then the number to be inside the chart. Like [=====Ford 63====|===GM 38===] the equals represent bar colors. There will be more data points than the current two.
Here is my page
<div ng-controller="PieController">
data {{ChartData}} //testing purposes
<div ng-init="getBarChart()">
<canvas id="Chart1"></canvas>
</div>
Here is my JavaScript controller
app.controller('PieController', function($scope, ChartService) {
$scope.getBarChart = function(){
ChartService.get({name: 'main'}, function(data) {
$scope.ChartData = data;
var barOptions_stacked = {
tooltips: {
enabled: false
},
hover: {
animationDuration: 0
},
scales: {
xAxes: [{
ticks: {
beginAtZero: true,
fontFamily: "'Open Sans Bold', sans-serif",
fontSize: 11
},
scaleLabel: {
display: false
},
gridLines: {},
stacked: true
}],
yAxes: [{
gridLines: {
display: false,
color: "#fff",
zeroLineColor: "#fff",
zeroLineWidth: 0
},
ticks: {
fontFamily: "'Open Sans Bold', sans-serif",
fontSize: 11
},
stacked: true
}]
},
legend: {
display: false
},
animation: {
onComplete: function () {
var chartInstance = this.chart;
var ctx = chartInstance.ctx;
ctx.textAlign = "left";
ctx.font = "9px Open Sans";
ctx.fillStyle = "#fff";
Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
Chart.helpers.each(meta.data.forEach(function (bar, index) {
data = dataset.data[index];
if (i == 0) {
ctx.fillText(data, 50, bar._model.y + 4);
} else {
ctx.fillText(data, bar._model.x - 25, bar._model.y + 4);
}
}), this)
}), this);
}
},
pointLabelFontFamily: "Quadon Extra Bold",
scaleFontFamily: "Quadon Extra Bold",
};
var ctx = document.getElementById("Chart1");
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["2014", "2013", "2012", "2011"],
datasets: [{
data: [727, 589, 537, 543, 574],
backgroundColor: "rgba(63,103,126,1)",
hoverBackgroundColor: "rgba(50,90,100,1)"
}, {
data: [238, 553, 746, 884, 903],
backgroundColor: "rgba(163,103,126,1)",
hoverBackgroundColor: "rgba(140,85,100,1)"
}, {
data: [1238, 553, 746, 884, 903],
backgroundColor: "rgba(63,203,226,1)",
hoverBackgroundColor: "rgba(46,185,235,1)"
}]
},
options: barOptions_stacked,
})
});//end chat service.get
}
});
Instead of hard coding in the dataset which is what its doing now, is there a way I can use the data "ChartData" that I outlined in the beginning of the post?
I'm not sure how to do it or if its even possible.
In order to get the label to show in the bar, reference the labels property of $scope.ChartData:
ctx.fillText($scope.ChartData.labels[index] +" "+ data, 50, bar._model.y + 4);
Instead of hard coding in the dataset which is what its doing now, is there a way I can use the data "ChartData" that I outlined in the beginning of the post?
Use properties from the data variable (supplied by the ChartService get function) i.e. data.labels and data.data instead of the hard-coded values.
So update the labels line from:
labels: ["2014", "2013", "2012", "2011"],
To this:
labels: data.labels,
And similarly for the datasets:
datasets: [{
data: data.data,
So when creating the Chart it should look like this:
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: data.labels,
datasets: [{
data: data.data,
backgroundColor: "rgba(63,103,126,1)",
hoverBackgroundColor: "rgba(50,90,100,1)"
}]
},
options: barOptions_stacked,
});
Expand the code snippet below for a demonstration.
Note: there is currently an issue with the resize-listener, blocked by a CORS issue - I am trying to find a way to disable that.
Update:
Per your comment about stacking the bars (horizontally) - yes that is possible. Just have one element in the datasets array for each item. One simple way to have this is to use Array.map() to create an array similar to the example:
var bgColors = [
"rgba(63,103,126,1)",
"rgba(50,90,100,1)"
];
var hoverBgColors = [
"rgba(50,90,100,1)",
"rgba(140,85,100,1)"
];
var datasets = data.data.map(function(value, index) {
return {
data: [value],
backgroundColor: bgColors[index],
hoverBackgroundColor: hoverBgColors[index]
}
});
Then use variable datasets when creating the Chart object:
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: data.labels,
datasets: datasets
},
options: barOptions_stacked,
});
Also, there is some weird math going on for the location of the second label but the helper function can be updated like below (I tried dividing the x value by 75 but that may need to be adjusted - I am not sure what "appropriate" values are for that ...):
if (i == 0) {
ctx.fillText($scope.ChartData.labels[i] + " " + data, 50, bar._model.y + 4);
} else {
ctx.fillText($scope.ChartData.labels[i] + " " + data, (bar._model.x - 25) / 75, bar._model.y + 4);
}
var app = angular.module('myApp', []);
app.factory('ChartService', function() {
return { //dummy chart service
get: function(obj, callback) {
var data = {
"data": ["63", "38"],
"labels": ["Ford", "GM"]
};
callback(data);
}
};
});
app.controller('PieController', function($scope, ChartService) {
$scope.getBarChart = function() {
ChartService.get({
name: 'main'
}, function(data) {
$scope.ChartData = data;
var barOptions_stacked = {
tooltips: {
enabled: false
},
hover: {
animationDuration: 0
},
scales: {
xAxes: [{
ticks: {
beginAtZero: true,
fontFamily: "'Open Sans Bold', sans-serif",
fontSize: 11
},
scaleLabel: {
display: false
},
gridLines: {},
stacked: true
}],
yAxes: [{
gridLines: {
display: false,
color: "#fff",
zeroLineColor: "#fff",
zeroLineWidth: 0
},
ticks: {
fontFamily: "'Open Sans Bold', sans-serif",
fontSize: 11
},
stacked: true
}]
},
legend: {
display: false
},
animation: {
onComplete: function() {
var chartInstance = this.chart;
var ctx = chartInstance.ctx;
ctx.textAlign = "left";
ctx.font = "9px Open Sans";
ctx.fillStyle = "#fff";
Chart.helpers.each(this.data.datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
Chart.helpers.each(meta.data.forEach(function(bar, index) {
data = dataset.data[index];
if (i == 0) {
ctx.fillText($scope.ChartData.labels[i] + " " + data, 50, bar._model.y + 4);
} else {
ctx.fillText($scope.ChartData.labels[i] + " " + data, (bar._model.x - 25) / 75, bar._model.y + 4);
}
}), this)
}), this);
}
},
pointLabelFontFamily: "Quadon Extra Bold",
scaleFontFamily: "Quadon Extra Bold",
};
var ctx = document.getElementById("Chart1");
var bgColors = [
"rgba(63,103,126,1)",
"rgba(50,90,100,1)"
];
var hoverBgColors = [
"rgba(50,90,100,1)",
"rgba(140,85,100,1)"
];
var datasets = data.data.map(function(value, index) {
return {
data: [value],
backgroundColor: bgColors[index],
hoverBackgroundColor: hoverBgColors[index]
}
});
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
//use empty labels because the labels are on the bars
labels: data.labels.map(function() {
return '';
}),
datasets: datasets
},
options: barOptions_stacked,
})
}); //end chat service.get
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="PieController">
data {{ChartData}} //testing purposes
<div ng-init="getBarChart()">
<canvas id="Chart1"></canvas>

Using json file as data source for chart.js

I am attempting to include some json values in a bar chart. I have the json logging to the console but not sure how to include in the data property for the chart. Here is the source json...
{time: "2016-07-03T21:29:57.987Z", temperature: 25.2, pressure: 98241, altitude: 259.98737254818553}
Thanks
<!doctype html>
<html>
<head>
<title>WeatherPush</title>
<script src="../dist/jquery.min.js"></script>
<script src="../dist/Chart.bundle.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div id='d1' style="position:absolute; top:50px; left:0px; z-index:1">
<canvas id='canvas' width='250' height='500'>
Your browser does not support HTML5 Canvas.
</canvas>
</div>
<div id='d1' style="position:absolute; top:50px; left:300px; z-index:1">
<canvas id='canvas2' width='250' height='500'>
Your browser does not support HTML5 Canvas.
</canvas>
</div>
<div id='d1' style="position:absolute; top:50px; left:600px; z-index:1">
<canvas id='canvas3' width='250' height='500'>
Your browser does not support HTML5 Canvas.
</canvas>
</div>
<script>
var jsonObjGraph;
var getDataPromise = $.getJSON('../data.json', function(data) {
jsonObjGraph = data;
console.log(jsonObjGraph);
});
getDataPromise.done(function () {
// done
});
getDataPromise.fail(function () {
// fail;
});
var barChartData = {
labels : ["Temperature"],
datasets : [
{
label: 'Temperature',
data : []
}
]
}
var barChartData2 = {
labels : ["Pressure"],
datasets : [
{
label: 'Pressure',
data : []
}
]
}
var barChartData3 = {
labels : ["Altitude"],
datasets : [
{
label: 'Altitude',
data : []
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
elements: {
rectangle: {
backgroundColor: "rgba(151,187,205,0.5)",
borderWidth: 2,
borderColor: 'gray',
}
},
responsive: true,
legend: {
position: 'right',
display: false,
},
title: {
display: false,
text: 'Temperature'
}
}
});
var ctx2 = document.getElementById("canvas2").getContext("2d");
window.myBar = new Chart(ctx2, {
type: 'bar',
data: barChartData2,
options: {
elements: {
rectangle: {
backgroundColor: "rgba(151,187,205,0.5)",
borderWidth: 2,
borderColor: 'gray',
}
},
responsive: true,
legend: {
display: false,
position: 'right',
},
title: {
display: false,
text: 'Pressure'
}
}
});
var ctx3 = document.getElementById("canvas3").getContext("2d");
window.myBar = new Chart(ctx3, {
type: 'bar',
data: barChartData3,
options: {
elements: {
rectangle: {
backgroundColor: "rgba(151,187,205,0.5)",
borderWidth: 2,
borderColor: 'gray',
}
},
responsive: true,
legend: {
display: false,
position: 'right',
},
title: {
display: false,
text: 'Pressure'
}
}
});
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<title>WeatherPush</title>
<script src="../dist/jquery.min.js"></script>
<script src="../dist/Chart.bundle.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div id='d1' style="position:absolute; top:50px; left:0px; z-index:1">
<canvas id='canvas' width='250' height='500'>
Your browser does not support HTML5 Canvas.
</canvas>
</div>
<div id='d1' style="position:absolute; top:50px; left:300px; z-index:1">
<canvas id='canvas2' width='250' height='500'>
Your browser does not support HTML5 Canvas.
</canvas>
</div>
<div id='d1' style="position:absolute; top:50px; left:600px; z-index:1">
<canvas id='canvas3' width='250' height='500'>
Your browser does not support HTML5 Canvas.
</canvas>
</div>
<button id="updateDataset">Update Datasets</button>
<script>
$.getJSON("data.json", function (data) {
time = data.time
temp = data.temperature
press = data.pressure
alt = data.altitude
console.log(time)
var barChartData = {
labels: ["Temperature"],
datasets: [
{
label: 'Temperature',
data: [temp]
}
]
};
var barChartData2 = {
labels : ["Pressure"],
datasets : [
{
label: 'Pressure',
data : [press]
}
]
};
var barChartData3 = {
labels : ["Altitude"],
datasets : [
{
label: 'Altitude',
data : [alt]
}
]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
elements: {
rectangle: {
backgroundColor: "rgba(151,187,205,0.5)",
borderWidth: 2,
borderColor: 'gray',
}
},
responsive: true,
legend: {
display: false,
position: 'right',
},
title: {
display: true,
text: time
}
}
}
);
var ctx2 = document.getElementById("canvas2").getContext("2d");
window.myBar = new Chart(ctx2, {
type: 'bar',
data: barChartData2,
options: {
elements: {
rectangle: {
backgroundColor: "rgba(151,187,205,0.5)",
borderWidth: 2,
borderColor: 'gray',
}
},
responsive: true,
legend: {
display: false,
position: 'right',
},
title: {
display: true,
text: time
}
}
});
var ctx3 = document.getElementById("canvas3").getContext("2d");
window.myBar = new Chart(ctx3, {
type: 'bar',
data: barChartData3,
options: {
elements: {
rectangle: {
backgroundColor: "rgba(151,187,205,0.5)",
borderWidth: 2,
borderColor: 'gray',
}
},
responsive: true,
legend: {
display: false,
position: 'right',
},
title: {
display: true,
text: time
}
}
});
})
</script>
</body>
</html>

Categories

Resources