Chart.js line graph change x axis seperation - javascript

I am currently creating a system to read data from a mysql database in json format and display this data in a chart.js line graph. The values will be inserted into the database when they are received from the transmitter every minute. The data values in the format are DateTimeOfRecording (mysql DATETIME), Temperature and humidity. I have managed to get the graph to display the data.
However, the graphical seperation between timestamps is the same, no matter what the time difference is between them. Is there any way of scaling them so that, for example, if recording of the data is missed, then a gap will be created in the chart, instead of the next value being placed directly after?
This is my javascript file for creating the chart:
$(document).ready(function(){
$.ajax({
url : "http://"+self.location.host+"/chartjs/tests/ChartDataTest.php",
type : "GET",
success : function(data){
console.log(data);
var Temperature = [];
var RecordingDateTime = [];
var Humidity = [];
for(var i in data)
{
RecordingDateTime.push(data[i].RecordingDateTime);
Temperature.push(data[i].Temperature);
Humidity.push(data[i].Humidity);
}
var chartdata =
{
labels: RecordingDateTime,
datasets:
[
{
label: "Temperature",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(230, 0, 0, 0.75)",
borderColor: "rgba(230, 0, 0, 1)",
pointHoverBackgroundColor: "rgba(230, 0, 0, 1)",
pointHoverBorderColor: "rgba(230, 0, 0, 1)",
data: Temperature
},
{
label: "Humidity",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(59, 89, 152, 0.75)",
borderColor: "rgba(59, 89, 152, 1)",
pointHoverBackgroundColor: "rgba(59, 89, 152, 1)",
pointHoverBorderColor: "rgba(59, 89, 152, 1)",
data: Humidity
}
]
};
var ctx = $("#mycanvas");
var LineGraph = new Chart(ctx,
{
type: 'line',
data: chartdata
});
},
error : function(data)
{
}
});
});

I think you need to specify your x-axis as using the type of time.
Try something like this...
var ctx = $("#mycanvas");
var LineGraph = new Chart(ctx,
{
type: 'line',
data: chartdata,
options: {
scales: {
xAxes: [
{
type: "time",
time: {
format: timeFormat,
round: 'minute',
}
}],
},
}
});

Related

chart.js is not drawing the line graph for the firestore dataset

Actually, I have got data from the Firestore and trying to show up in the line graph using chart.js.
Graph labels and data are showing up correctly in the X and Y positions accordingly. But it is not drawing the line on the graph.
So far I did:
.jsp file -->
<div>
<canvas id="myChart" style="padding-top: 40px; height: 6px; width: 36px" height="6" width="36"></canvas>
</div>
.js file -->
$(document).ready(function(){
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
var docRef = db.collection('Users').doc('6158614499').collection('Data').orderBy("Date", "desc");
var timeOptions = {hourCycle: 'h23', hour: '2-digit', minute:'2-digit'};
var dateOptions = { day: 'numeric', month: 'numeric' };
var labelsDateArray = [];
var dataValuesArray = [];
docRef.get().then((querySnapshot) => {
querySnapshot.forEach((doc)=>{
var one = doc.data();
var date = one.Date.toDate().toLocaleDateString('en-CA', dateOptions) + "~" + one.Date.toDate().toLocaleTimeString( [], timeOptions);
labelsDateArray.push(date);
var value = one.FacilityCode;
dataValuesArray.push(value);
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labelsDateArray,
datasets: [{
label: 'Kefa-Firestore-Dataset',
fill: false,
showLine: true,
lineTension: 0.1,
backgroundColor: "rgba (75, 192, 192,0.4)",
borderColor: "rgba(139, 0, 0, 1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(139, 0, 0, 0.5)",
pointBackgroundColor: "red",
pointBorderWidth: 2,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(0, 0, 0, 1)",
pointHoverBorderColor: "rgba(0, 0, 0, 1)",
pointHoverBorderWidth: 5,
pointRadius: 3,
pointHitRadius: 10,
data: dataValuesArray,
}]
},
});
}).catch((error) => {
console.log("Error getting document:", error);
});
});
Output is like this:
So, in order to draw the line what should I change, anyone can help please?!

update chart in chart js without reloading the page

i trying to create a chart when users search and it works but the problem when user search again it throw Uncaught Error: Canvas is already in use and when i try to destroy it it throw another error says that destroy is not function, I need a way to make the chart change when user serach without the need to reload the page
my code
var endpoint = "/api/chart/data";
myform.addEventListener("submit", function (e) {
e.preventDefault();
var name = document.querySelector("#name").value;
var amount = document.querySelector("#amount").value;
$.ajax({
method: "GET",
url: endpoint + "?name=" + name + "&amount=" + amount,
success: function (data) {
labels = data.labels;
data = data.data;
console.log("success");
console.log(name);
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "bar",
data: {
labels:labels,
datasets: [
{
label: "# of Votes",
data: data,
backgroundColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)",
],
borderColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)",
],
borderWidth: 1,
borderRadius: 5,
},
],
},
options: {
responsive: true,
scales: {
x: {
min: -100,
max: 100,
ticks: {
color: '#fff',
},
beginAtZero: true,
},
y: {
ticks: {
color: '#fff',
},
beginAtZero: true,
},
},
},
});
},
error:function(){
console.error('enter valid data')
}
});
});
The problem is that the myChart variable is declared inside the scope of the AJAX success function. The variable only exists within the function body during its execution. When the user performs a new search, the success function is invoked again but the initially created myChart variable does no longer exist.
You can solve your problem by creating myChart at the beginning in the global scope as follows.
var myChart = new Chart('myChart', {
type: "bar",
data: {
labels: [], // initialize with an empty array
datasets: [{
label: "# of Votes",
data: [], // initialize with an empty array
...
});
Your event listener and AJAX request would then look as shown below. Note that I set the labels and data on the existing chart and call myChart.update() afterwards. This is cleanest and the most efficient way to deal with new data. For further details, please consult Updating Charts from chart.js documentation.
var endpoint = "/api/chart/data";
myform.addEventListener("submit", function(e) {
e.preventDefault();
var name = document.querySelector("#name").value;
var amount = document.querySelector("#amount").value;
$.ajax({
method: "GET",
url: endpoint + "?name=" + name + "&amount=" + amount,
success: function(data) {
myChart.data.labels = data.labels;
myChart.data.datasets[0].data = data.data;
myChart.update();
},
error: function() {
console.error('enter valid data')
}
});
});

Hiding xAxis labels when using Chart.js

I am using chart.js to create a linegraph from data in a locally hosted mysql DB.
I am able to pull this data and display it as intended, however despite following documentation and advice given else where I am unable to hide the xAxis Labels. The code I am using is below - any help would be much appriacated.
var chardata = {
labels: time,
datasets: [
{
label: "System health",
fill: false,
backgroundColor: "rgba(123, 192, 67, 0.75)",
borderColor: "rgba(123, 192, 67, 1)",
pointHoverBackgroundColor: "rgba(123, 192, 67, 1)",
pointHoverBorderColor: "rgba(123, 192, 67, 1)",
data: health_score
}
]
};
var ctx = $("#mycanvas");
var options = {
type: 'line',
data: chardata,
options: {
scales: {
xAxes: [{
ticks: {
display: false
}
}]
}
}
};
var LineGraph = new Chart(ctx, options);
Cheers
..
var options = {
type: 'line',
data: chardata,
options: {
scales: {
xAxes: [{
display: false,
ticks: {
display: false
}
}]
}
}
};
..

Chart.js changing the color of the max value bar

I'm new to JS, I want to create a bar chart where the column with the max value has a different color compared to the others. I can create the chart but I don't manage to access the single column properties. I have been looking for answers on the web but none of the solutions I have found so far helped me. The workflow is the following:
I ask the user for a text input,
Once the user press a button the script calls a function in python (I use python flask) that returns me an array of values and labels,
Then a chart appears on the webpage with these values and labels.
Everything works fine, I'm just not able to change the color of a single bar.
Here is the JS:
$(function() {
$('a#process_input').bind('click', function() {
$.getJSON('/background_process', {
smile: $('input[name="text_string"]').val(),
}, function(data) {
$("#result").text(data.output);
var labels = data.labels;
var values = data.values;
Chart.defaults.global.responsive = false;
var chartData = {
labels : labels,
datasets : [{
label: 'data_label',
fill: true,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data : values,
scaleShowLabels: true,
spanGaps: false
}]
}
// get chart canvas
var ctx = document.getElementById("myCanvas").getContext("2d");
// create the chart using the chart canvas
var myChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scaleShowValues: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
autoSkip: false
}
}]
}
}
});
});
});
});
Here is an example of what I mean:
I think the easiest way to do it is by defining backgroundColor for each bars. Then you can find the max index and change the color. Here is a simplified example:
function argMax(array) {
return array.map((x, i) => [x, i]).reduce((r, a) => (a[0] > r[0] ? a : r))[1];
}
// dummy data
var data = [12, 19, 1, 14, 3, 10, 9];
var labels = data.map((x, i) => i.toString());
// other data color
var color = data.map(x => 'rgba(75,192,192,0.4)');
// change max color
color[argMax(data)] = 'red';
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'value',
data: data,
backgroundColor: color,
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.0.0-beta/Chart.js"></script>
<canvas id="myChart" width="600" height="300"></canvas>
backgroundColor: "rgba(75,192,192,0.4)"
instead of giving it a single color, you can add an array:
backgroundColor:["rgba(255, 99, 132, 0.2)","rgba(255, 159, 64, 0.2)","rgba(255, 205, 86, 0.2)"]
Example:
new Chart(document.getElementById("chartjs-1"), {
"type": "bar",
"data": {
"labels": ["First", "Second", "Third", "Fourth"],
"datasets": [{
"label": "Example Dataset",
"data": [65, 59, 80, 31],
"fill": false,
"backgroundColor": ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 99, 132, 0.2)"],
"borderColor": ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 99, 132)", "rgb(255, 99, 132)"],
"borderWidth": 1
}]
},
"options": {
"scales": {
"yAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chartjs-1" class="chartjs">https://stackoverflow.com/posts/51843404/edit#
In the documentation [] denotes which properties accept also arrays (backgroundColor - Color/Color[])

Update the Chartjs push data with ajax

This is the code that I have created to render chart with Chart.js library:
$(document).ready(function(){
$.ajax({
url : "data.php",
type : "JSON",
success : function(data){
var lung = data.length;
console.log(data);
var timestamp_utc = [];
var temperature = [];
for(var i in data) {
timestamp_utc.push(data[i].timestamp_utc);
temperature.push(data[i].temperature);
}
var config_temp = {
labels: timestamp_utc.slice(lung-10, lung),
datasets: [
{
label: "temperature",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(0, 169, 252, 0.75)",
borderColor: "rgba(0, 169, 252, 1)",
pointRadius: "5",
pointColor: "rgba(0, 169, 252, 1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "rgba(0, 169, 252, 1)",
pointHoverBorderColor: "rgba(0, 169, 252, 1)",
data: temperature.slice(lung-10, lung)
}]
};
var ctx_temp = $("#mycanvas");
var LineGraph_temp = new Chart(ctx_temp, {
type: 'line',
data: config_temp
});
},
error : function(data) {
}
});
});
I want to update graph every 15 minutes.
how can I do that?
You can use setInterval method to execute the code which renders the chart with updated data.
var pollInterval = 15000; //change this value as needed
function renderChart() {
// put your existing code to render the chart here
}
$(function () {
window.setInterval(renderChart, pollInterval);
});

Categories