Data not displaying in Chart JS from PHP JSON - javascript

Hi I'm trying to display a dynamic line chart using Chartjs with data pulled from SQL using PHP in JSON format. The data is successfully selected but does not successfully display just a blank chart, any help is appreciated.
$(document).ready(function() {
var dataPointsA = []
var dataPointsB = []
$.ajax({
type: 'GET',
url: 'data.php',
dataType: 'json',
success: function(field) {
for (var i = 0; i < field.length; i++) {
dataPointsA.push({
x: field[i].datetime,
y: field[i].roomtemp
});
dataPointsB.push({
x: field[i].datetime,
y: field[i].tanktemp
});
}
console.log(field);
var chartdata = {
title: {
text: "Fish Tank Monitor"
},
data: [{
type: "line",
name: "line1",
dataPoints: dataPointsA
}, {
type: "line",
name: "line2",
dataPoints: dataPointsB
}, ]
};
console.log(chartdata);
var ctx = mycanvas.getContext('2d');
var barGraph = new Chart(ctx, {
type: 'line',
data: chartdata,
backgroundColor: 'rgba(0, 119, 204, 0.3)'
});
}
});
});
Example JSON
[{"datetime":"2018-07-28 22:33:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:32:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:31:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:30:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:29:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:28:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:27:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:26:00.000","roomtemp":26.8,"tanktemp":28.4},{"datetime":"2018-07-28 22:25:00.000","roomtemp":26.9,"tanktemp":28.4},{"datetime":"2018-07-28 22:24:00.000","roomtemp":26.9,"tanktemp":28.4}]

I think its happeing due to incorrect date time format. datetime key you used is acting as a string. I think you need to apply one date and time filter

Related

Storing Highcharts in array issue

I am plotting a number of highcharts dynamically in a loop and pushing each highchart to an array. So that while clicking on an external button, I can export the charts. But while pushing charts to array, only the last entry is properly set with options.
i had a reference to a fiddle that suggests to clone the options. [https://jsfiddle.net/ndb21y1w/][2]
https://www.highcharts.com/forum/viewtopic.php?t=38574
The fiddle have same series data plotted on all the charts. How to solve this if the data is different for each chart populated. Thanks for any help in advance.
Adding more clarity to question :
The data is populated dynamically in loop. My code logic is like:
counter i;
setInterval(function() {
//logic to populated data...
//It is a multiline chart, so three sets of arrays are populated.
//filling data1[], data2[] and data3[] .
drawChart(data1, data2, data3);
if(condition true) clearInterval();
i++;
});
drawChart(data1, data2, data3) {
var chart = new Highcharts.Chart({
title: {
text: "title",
},
xAxis: {
categories: [1,2,3,4...],
},
series: [{
type: 'line',
data: data1,
}, {
type: 'line',
data: data2,
}, {
type: 'line',
data: data3,
},
});
chartArray.push(chart);
}
This chartArray is where I mentioned to get the last entry only properly.
To create a chart you have to pass an HTML element that will be a chart container. In your code that what's missing. Check the demo I have prepared to reproduce this issue: https://jsfiddle.net/BlackLabel/c60y1t2v/
Code:
var chartArray = [],
counter = 1,
dataArr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
],
containers = document.getElementById('containers');
function drawChart(data) {
var cnt = document.createElement('div'),
cntId = 'container' + counter++,
chart;
cnt.setAttribute('id', cntId);
containers.appendChild(cnt);
chart = new Highcharts.Chart(cntId, {
title: {
text: "title",
},
xAxis: {
categories: [1, 2, 3, 4],
},
series: [{
type: 'line',
data: data,
}]
});
return chart;
}
dataArr.forEach(function(data) {
var chart = drawChart(data);
chartArray.push(chart);
});
You need to define options each time you use a new chart. Reinitialize the OriginalOptions every time you create a new chart.
const options = [...Array(5)].map(() => {
const originalOptions = {
series: [{
data: [], // some random data
type: 'column'
}]
}
return Object.assign(originalOptions)
})
Fiddle
Updated:
For dynamically repopulating the chart, you have to initialize an empty chart and then add new series + redraw whenever your data is populated.
Your redraw function will look something like this:
var i = 0;
var data = [];
var chart = new Highcharts.Chart('container',{
series: []
});
var interval = setInterval(function() {
i++;
data[i] = [i*10 + 1, i*10+2, i*10+3];
drawChart(data[i]);
if(i > 2) clearInterval(interval);
},1000);
function drawChart(data) {
var series = {
type: 'line',
data: data
}
chart.addSeries(series, false);
chart.redraw();
}
See Updated Fiddle
To Print HTML as PDF you can use this software "wkhtmltopdf"
in Linux you need to use this command :
sudo apt-get install wkhtmltopdf
There are many library based on "wkhtmltopdf" in many languages so you can use it.
Library for PHP : https://github.com/mikehaertl/phpwkhtmltopdf
Store chart options in Array then map over to Initialize Highchart for each options.
var chartArray = [];
function drawChart(data1, data2, data3, i) {
// Create container for charts
const el = document.createElement('div');
document.body.appendChild(el).setAttribute("id", "container"+i);
// Create charts
var chart = new Highcharts.chart(el, {
series: [{
type: 'line',
data: data1,
}, {
type: 'line',
data: data2,
}, {
type: 'line',
data: data3,
}]
});
chartArray.push(chart);
console.log(chartArray);
}
var counter = 0;
var delayTime = 2000;
var timer = setInterval(function(){
var data1 = [30, 70, 50];
var data2 = [40, 70, 60];
var data3 = [10, 90, 20];
drawChart(data1, data2, data3, counter);
if(counter == 2){
clearInterval(timer);
}
counter++;
},delayTime);
<script src="https://code.highcharts.com/highcharts.js"></script>

How can I plot data from an external JSON file to a chart.js graph?

I would like to chart data from an external JSON file using chart.js. As an example, the json file here lists movies ("title") and ratings ("rt_score"). I'd like to be able to show each movie and its rating without including the static JSON in the .js file, but rather using the $.ajax call method to refer to the /films endpoint.
I'd like to have:
labels: labelsVariable
data: dataVariable
Here is a fiddle with the setup so far with static data.
Here's my HTML:
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js">
</script>
</body>
Here's the js that successfully generates a bar chart like I want, but with static data in "labels" and "data" instead of referencing the JSON file.
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Castle in the Sky', 'Grave of the Fireflies'],
datasets: [{
label: 'rating',
data: [95, 97],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
Instead of using the static data and labels, how can I reference the external JSON file using the $.ajax call method?
Based on what I've read, I may have to use "map" to break down the objects into arrays that contain labels and data?
Thank you in advance.
I think you are looking for Ajax request to fill your chart.
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var ctx_live = document.getElementById("mycanvas");
var myChart = new Chart(ctx_live, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 1,
borderColor:'#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Chart.js - Dynamically Update Chart Via Ajax Requests",
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
var postId = 1;
var getData = function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/' + postId + '/comments',
success: function(data) {
myChart.data.labels.push("Post " + postId++);
myChart.data.datasets[0].data.push(getRandomIntInclusive(1, 25));
// re-render the chart
myChart.update();
}
});
};
setInterval(getData, 3000);
see live example here.
Load the json chart data dynamically and set it when you are creating the graph. There are many ways you can load the chart json data. However, I believe the JQuery getJSON function is more relevant to you.
$.getJSON( "chartdata/test.json", function( data ) {
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
I figured it out. Here's what worked. I had to use .map to set up the data properly inside variables and then use those variables as data and labels.
function renderChart(data, labels) {
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'This week',
data: data,
}]
},
});
}
function getChartData() {
$("#loadingMessage").html('<img src="./giphy.gif" alt="" srcset="">');
$.ajax({
url: "https://ghibliapi.herokuapp.com/films",
success: function (result) {
var data = result.map(x=>x.rt_score);
var labels = result.map(x=>x.title);
renderChart(data, labels);
console.log(data);
},
});
$("#renderBtn").click(
function () {
getChartData();
});

How to add text to chart.js data?

I need help to add a text after the data that shows the graph, the code I have is the following:
var ctx = document.getElementById("chart-area");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["label1", "label2", "label3", "label4"],
datasets: [{
data: [ 10, 20, 30, 40 ]
}]
}
}
It shows me the information like this:
label1: 10
But i need to add text after that, something like:
label1: 10 Mb
Please, I don't know how to add it, I already tried several ways
ChartJs does not provide any format label feature you have to play with it.
Initialize chart configuration with empty array then update it when you pushing data.
From this reference https://github.com/chartjs/Chart.js/issues/2738
here is fiddle link: http://jsfiddle.net/qsnpsxz5/7/
chart.config.data.labels.push("A label");
chart.config.data.labels.push("A label2");
chart.config.data.datasets[0].data.push(10);
chart.config.data.datasets[0].data.push(20);
chart.update();
Try using this script
var ctx = document.getElementById("chart-area");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["label1", "label2", "label3", "label4"],
datasets: [
{ data: [ 10, 20, 30, 40 ] }
]
},
options: {
tooltips: {
enabled: true,
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label;
var val = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return label + ' : ' + val + ' Mb';
}
}
}
}
});

Pushing data from json to Chart.js labels and data

I am using the Chart.js lib to make charts.
I have a json array that I am getting from a database.
Here is the console log of it: Data
I need to get the address, speed, and speed limit for every element in the list and use it in a chart.
My current code is as follows:
function ShowChart() {
var popCanvas = document.getElementById("speedLimitsChart");
console.dir(speeddata);
var labels = speeddata.map(function (e) {
return e.Adress;
});
var speed = speeddata.map(function (e) {
return e.Speed;
});
var speedlimits = speeddata.map(function (e) {
return e.SpeedLimits;
});
console.dir(labels);
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
labels: labels
});
}
But in the result I only have the first element in my chart, and there are no labels.
Here is the output screen: Chart
I checked speed, speedlimits and labels and all of them have 2 elements. Can you please advise where my problem might be?
I found where is my problem
I need to write labels inside of data
Like this
var barChart = new Chart(popCanvas, {
type: 'bar',
data: {
labels: labels ,
datasets: [{
label: 'Speed',
data: speed,
backgroundColor: '#1E90FF'
}, {
label: 'Speed Limits',
data: speedlimits,
backgroundColor: '#B22222',
type: 'line'
}],
},
});

hide legend labels if zero data in jquery pie chart

I am trying to plot a pie chart with data set containing zero values.But pie chart shows only labels till data gets updated.
What if I wanted to show empty pie chart.
I have given:
var data = [
{
label: "Series1",
data: 0,
url: "http://stackoverflow.com"},
{
label: "Series2",
data: 0,
url: "http://serverfault.com"},
{
label: "Serie3",
data: 0,
url: "http://superuser.com"},
{
label: "Series4",
data: 0,
url: "http://www.google.com"},
{
label: "Series5",
data: 0,
url: "http://www.oprah.com"},
{
label: "Series6",
data: 0,
url: "http://www.realultimatepower.net/"}
];
var options = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
}
};
var plot = $.plot($("#graphLoaderDiv"), data, options);
Modify your label formatter function to return null if the series percent is zero.
After digging deeper I realized The best possible solution is to not to show pie chart if your data set values are zero.You either can do it editing following plugin or adding check inside your plotting function.
Download jquery.flot.pie.js from here
http://code.google.com/p/flot/issues/detail?id=530
Go to line No 411 and modify code as follows.
if( isNaN(angle) ) {
//var html = html = '<span class="pieLabel" id="pieLabelNoData" style="position:absolute;top:20px;left:5px;">There is no available data.</span>';
//html = target.append(html);
target.hide();
}
you can show empty data like this
$piedata="[{label:'no data',data:1}]";

Categories

Resources