Update chartjs chart within random data once per second - javascript

Below is my attempt to update a chart once per second with random data and dynamically repaint the chart. The function adddata() pushes random data to the data array but the chart UI is not updating and appears static. How to update the chart dynamically when new data is added ?
src:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<div class="chart-container" style="position: absolute; height:20vh; width:40vw">
<canvas id="myChart1"></canvas>
<input onclick="adddata()" type="button" value="Add Data">
</div>
$(document).ready(function () {
var canvas1 = document.getElementById('myChart1');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
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: 5,
pointHitRadius: 10,
data: [65, 59, 80, 0, 56, 55, 40],
}
]
};
function adddata() {
setInterval(function () {
console.log('invoking' + Math.random() * 10)
myLineChart.data.datasets[0].data.push(Math.floor(Math.random() * 10))
myLineChart.update();
}, 1000)
}
var option = {
showLines: true
};
var myLineChart = Chart.Line(canvas1, {
data: data,
options: option
});
adddata();
});
fiddle src: https://jsfiddle.net/adrianfiddleuser/jq1pzkrs/6/
The function is called once per second, on console following is dispayed:

Right now you're adding an extra slot to the dataset (you need to have the same amount of labels as data in the dataset, so if you want to add more data - also add more labels) - try replacing a data instead, like:
$(document).ready(function () {
var canvas1 = document.getElementById('myChart1');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
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: 5,
pointHitRadius: 10,
data: [65, 59, 80, 0, 56, 55, 40],
}
]
};
function adddata() {
setInterval(function () {
let randomIndex = Math.floor(Math.random() * Math.floor(myLineChart.data.datasets[0].data.length));
myLineChart.data.datasets[0].data[randomIndex] = Math.floor(Math.random() * 100);
myLineChart.update();
}, 1000)
}
var myLineChart = Chart.Line(canvas1, {
data: data,
options: option
});
var option = {
showLines: true
};
adddata();
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<div class="chart-container" style="position: absolute; height:20vh; width:40vw">
<canvas id="myChart1"></canvas>
<input onclick="adddata()" type="button" value="Add Data">
</div>
You can read more about in the documentation: https://www.chartjs.org/docs/latest/developers/updates.html

Related

How to remove title color box in Chart.js

I am using chart js ( https://www.chartjs.org/ ) for charts. I checked all option in document but did not find how to hide title color box. Please see attached image
Adding the following should hide the legend (I hope by title color box you mean legend):
legend:
{
display: false
}
var canvas = document.getElementById('myChart');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
fill: false,
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: 5,
pointHitRadius: 10,
data: [65, 59, 80, 0, 56, 55, 40],
}]
};
function adddata() {
myLineChart.data.datasets[0].data[7] = 60;
myLineChart.data.labels[7] = "Newly Added";
myLineChart.update();
}
var option = {
showLines: true,
legend: {
display: false
}
};
var myLineChart = Chart.Line(canvas, {
data: data,
options: option
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>
<input type="button" value="Add Data" onclick="adddata()">
Extending Peadar's answer with the options and plugins sections:
type: 'bar',
data: data,
options: {
plugins: {
legend: {
display: false,
} } }
That box is the legend. You can turn it off via the legend flag: https://www.chartjs.org/docs/latest/configuration/legend.html
var myChart = new Chart(ctx, {
type: 'bar',
legend: {
display: false
}
var chart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
plugins: {
legend: {
display: false
}
}
}
For vue-chartjs, I added this in the options object
options: {
legend: {
display: false
}
}

Update Chart JS data dynamically and add new data, remove old data to create timeline "like" chart

I'm building a realtime Chart JS chart which is meant to show data and update every few seconds, I attach my chart JS code below, which randomises data on page load, I have a labels array which I need to change to whatever the current date/time is, and after every X number of items it removes the previous so that the graph is essentially a timeline showing real time stats, I'm first trying to figure out how to get my chart to update data every few seconds and aren't sure how to do this:
$(document).ready(function(){
// Random data on page load
var datasetValue = [];
var count = 70;
for (var j = 0; j < count; j++) {
datasetValue[j] = {
data: [
Math.round(Math.random() * 100),
Math.round(Math.random() * 100)-10,
Math.round(Math.random() * 100),
Math.round(Math.random() * 100)-10,
Math.round(Math.random() * 100),
Math.round(Math.random() * 100)-10,
Math.round(Math.random() * 100)
]
}
}
var mydata = {
datasets: datasetValue
}
// Our chart
var ctx = document.getElementById('status-chart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "Max",
fill: false,
borderColor: '#f44336',
data: mydata.datasets[1].data,
}, {
label: "Free",
fill: false,
borderColor: '#4CAF50',
data: mydata.datasets[3].data,
}, {
label: "Total",
fill: false,
borderColor: '#607D8B',
data: mydata.datasets[2].data,
}, {
label: "Used",
fill: false,
borderColor: '#2196F3',
data: mydata.datasets[4].data,
}]
},
options: {
legend: {
display: true,
labels: {
fontColor: '#000'
}
}
}
});
});
you can use chart.update() method with assigning a new dataset
<canvas id="myChart" width="400" height="250"></canvas>
<input type="button" value="New Data" onclick="RandomData()">
var canvas = document.getElementById('myChart');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My dataset",
fill: false,
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: 5,
pointHitRadius: 10,
data: [65, 59, 80, 0, 56, 55, 40],
}
]
};
function RandomData(){
var newData=[];
for(var i=0;i<7;i++){
newData.push(Math.round(Math.random() * 100))
}
myLineChart.data.datasets[0].data =newData;
myLineChart.update();
}
var option = {
showLines: true
};
var myLineChart = Chart.Line(canvas,{
data:data,
options:option
});
please see a demo here

Update or Insert a new value charts

function method() {
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
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: [65, 59, 80, 81, 56, 55, 40],
spanGaps: false,
}
]
},
options: {
responsive: false,
}
});
I added a function to add a new value on the chart
function addvalue() {
myChart.data.labels.concat("August");
myChart.data.datasets[0].data.concat(55);
myChart.update();
but compiler say me "myChart is not declared" How can I draw the chart in this case?
I've just started with canvas and these charts
As Mihai has pointed out, read deeply into MDN's documentation about functions and about scope.
Your code needs to export or make the myChart variable accessible to other functions. Here is the quick and dirty fix - you need to decide what is best for your app.
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
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: [65, 59, 80, 81, 56, 55, 40],
spanGaps: false,
}
]
},
options: {
responsive: false,
}
});
This is global scope (not the best), but it will allow your other function to access it:
function addvalue() {
// myChart is now globally accessible
myChart.data.labels.concat("August");
myChart.data.datasets[0].data.concat(55);
myChart.update();
}
Without knowing more context I can't specifically say to do something better (like require your chart into other code)
Scope is important and also you want to return something
function method() {
return new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
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: [65, 59, 80, 81, 56, 55, 40],
spanGaps: false,
}
]
},
options: {
responsive: false,
}
});
var myChart = method();
function addvalue(myChart) {
myChart.data.labels.concat("August");
myChart.data.datasets[0].data.concat(55);
myChart.update();
return myChart;
}

How to create a linechart with Chart.JS (not filled)

I am trying to create a line chart with chart.js library, my goal is that the chart should be a single line, the area under it MUST NOT BE FILLED.
But whatever color I put, I dont see that its getting refreshed.
this is the JS that generates the chart.
<table style="width: 100%">
<tr>
<td style="width: 50%; text-align: center">
<canvas id="canvasForLineChart" height="200" width="400">Chart is Loading...</canvas>
</td>
</tr>
</table>
<script type="text/javascript">
////////////////////////////////////////////////////////////////////////////////////////////////////////
//Line Chart JSON Config (Line Chart Has fixed 1 data series here)
var lineChartData = {
//labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
fill: false,
lineTension: 0.1,
//backgroundColor: "#000000",
//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: [0]
}
]
}
//LineChart Update method
function UpdateLineChart(data) {
//Set data returned from Server
//lineChartData.datasets[0].fillColor = data.colorString;
lineChartData.datasets[0].data = data.lineChartData;
lineChartData.labels = data.hora;
//Update the Pie Chart
var canvasForLineChart = document.getElementById("canvasForLineChart");
var context2DLine = canvasForLineChart.getContext("2d");
new Chart(context2DLine).Line(lineChartData);
}
</script>
But my result is this:
And I want something like this:
According to the Chart JS Docs, you'll want to specify:
fill: false
in your chart options. Your code would look something like this:
function UpdateLineChart(data) {
//Set data returned from Server
lineChartData.datasets[0].data = data.lineChartData;
lineChartData.labels = data.hora;
//Update the Pie Chart
var canvasForLineChart = document.getElementById("canvasForLineChart");
var context2DLine = canvasForLineChart.getContext("2d");
var myChart = new Chart(context2DLine, {
data: {
datasets: [{
fill: false,
lineTension: 0.1,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [0]
}]
}
});
}
backgroundColor 'rgba(0,0,0,0.1)'
That should set your opacity to .1, you can go to zero I think but you should test it. I see you commented out the border color you had set to 1 opacity which is solid.
fill: false
should do the work, where do you call the UpdateLineChart function?

Chart.js not rendering unless i set a timeout

Well, i have the same issue that this guy: Chart.js not showing in my view , for him it solved to set a timeout but for me that's no even possible to introduce in my web, i don't want to work with timeouts.I'm working to create web-components for chart.js.There's any way to wait the chart to get render without setting a timeout?, that the waiting time is the render time
My code is:
flexygo.ui.wc.flxChart = function () {
return {
htmlItem: null,
moduleId: null,
refresh: function () {
this.init();
},
init: function () {
var ctx = this;
ctx.htmlItem.html('<canvas id="myChart2" height="400" width="800" style="width:800px;height:400px;"></canvas>');
ctx.render();
},
render: function () {
var ctx = this;
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
fill: false,
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: [65, 59, 80, 81, 56, 55, 40],
spanGaps: false,
}]
};
window.onload = function () {
var myChart = new Chart(ctx.htmlItem[0].childNodes[0], {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
display: false
}]
}
}
});
}
},
translate: function (str) {
return flexygo.localization.translate(str);
},
startLoading: function () {
this.htmlItem.parents('flx-module').find('.icon-sincronize').addClass('icon-spin txt-outstanding');
},
stopLoading: function () {
this.htmlItem.parents('flx-module').find('.icon-sincronize').removeClass('icon-spin txt-outstanding');
},
}
creating the chart we can use either htmlitem[0].childnodes[0] or document.getElementById('myChart2')
i solved it adding encapsulating the canvar into a div, so the canva resizes with my page, i changed:
from:
ctx.htmlItem.html('<canvas id="myChart2" height="400" width="800" style="width:800px;height:400px;"></canvas>');
to
ctx.htmlItem.html('<div><canvas id="myChart2" height="400" width="800" style="width:800px;height:400px;"></canvas></div>');
a now it works

Categories