Circling back around to this and I thought I had this worked out but apparently I do not. I am somewhat new to charts. I want the graph to show a line from zero even if there is no data for that month. This is a bit lengthy and I apologize for all of the code, but without it you will not understand what it is doing.
Here is my Controller Json:
var type3 = "Equipment";
var types3 = acct.TransactionType.Where(a => a.Type == type3).FirstOrDefault();
var q2 = from t in acct.Transaction.Where(t => t.Type == types3.TypeId && t.TransactionDate.Year.ToString() == currentYear)
group t by new
{
t.TransactionDate.Year,
t.TransactionDate.Month,
type = t.Type
} into g
select new
{
Total2 = g.Sum(t => t.CreditAmount) ?? 0
};
I have this same code for 2 other items I am showing. They show a graph from Zero. This is because in January at some point there is data. So It starts at 0. This particular area does not have any data in January and only has data in one month. So it doesn't even show a Dot for that month. In between 2 months if there is no data it will dip to zero.
I fixed that issue with adding ?? 0 above.
It appears to only have an effect if there is data before and after the time. So I am wondering if there is a way to show a line all the way across from zero to the point where there is data and then dip back down to zero after with plot dots.
Here is my java script code for the CHTML Page.
function SalesByMonth() {
$.ajax({
url: '#Url.Action("GetChartData", "Dashboard", new { Year = "year" })'.replace('year', currentYear),
data: JSON,
contentType: "application/json; charset=utf-8",
method: "get",
dataType: "json",
error: function (_, err) {
console.log(_, err)
},
success: function (response) {
console.log(response);
var jsonresult = response
//var labels = jsonresult.result.map(function (e) {
// return e.Months;
//});
var data = jsonresult.result1.map(function (e) {
return e.Total;
});
var data2 = jsonresult.result2.map(function (e) {
return e.Total2;
});
var data3 = jsonresult.result3.map(function (e) {
return e.Total3;
});
var ctx = document.getElementById("monthlySalesChart").getContext("2d");
var cpieChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [{
label: 'Parts Sales',
backgroundColor: 'rgb(204, 102, 0)',
borderColor: 'rgb(204, 102, 0)',
fill: false,
//strokeColor: 'rgb(210, 214, 222)',
//pointColor: 'rgb(210, 214, 222)',
//pointStrokeColor: '#c1c7d1',
//pointHighlightFill: '#fff',
//pointHighlightStroke: 'rgb(220,220,220)',
data: data,
borderWidth: 1
},
{
label: 'Service Sales',
backgroundColor: 'rgb(210, 214, 250)',
borderColor: 'rgb(210, 214, 250)',
fill: false,
//strokeColor: 'rgb(210, 214, 222)',
//pointColor: 'rgb(210, 214, 222)',
//pointStrokeColor: '#c1c7d1',
//pointHighlightFill: '#fff',
//pointHighlightStroke: 'rgb(220,220,220)',
data: data2,
borderWidth: 1
},
{
label: 'Machine Sales',
backgroundColor: 'rgb(0,102,204)',
borderColor: 'rgb(0,102,204)',
fill: false,
//strokeColor: 'rgba(60,141,188,0.8)',
//pointColor: '#3b8bba',
//pointStrokeColor: 'rgba(60,141,188,1)',
//pointHighlightFill: '#fff',
//pointHighlightStroke: 'rgba(60,141,188,1)',
data: data3,
borderWidth: 1
}],
},
options: {
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
//gridLines: {
// display: false
//},
ticks: {
beginAtZero: true,
//min: 200,
max: 80000,
stepSize: 2000,
callback: function (value, index, values) {
value = value.toString();
value = value.split(/(?=(?:...)*$)/);
value = value.join(',');
return '$' + value + '.00';
}
}
}]
}
}
});
}
});
};
If you need anything else let me know.
Thanks for your help!
UPDATE: If it helps I am using Chart.js v2.9.3
UPDATE: Found 1 Error.
Where it has Total2 = g.sum(t => t.CreditAmount) ?? 0 Should be Total3 = g.sum(t => t.CreditAmount) ?? 0. I already had a Total2 in a prev code block. However I am now getting a Tick but it is showing up on January and not May like it should. Date in the database is correct. So I am not sure why it is coming up in January.
UPDATE: The Only thing that I can figure out is that since there is only 1 entry in the database under that type, It doesn't have anything else to compare it too in the same month. It only returns 1 record for that. So I need to find out how to check the date and simply have a zero for that month show up regardless of the amount of records.
Related
Have been trying to add a range selector to my chart.
This is what I added to my php file.
<div id="range-selector">
<input type="button" id="30m" class="period ui-button" value="30m" />
<input type="button" id="1h" class="period ui-button" value="1h"/>
<input type="button" id="6h" class="period ui-button" value="6h"/>
<input type="button" id="12h" class="period ui-button" value="12h"/>
<input type="button" id="24h" class="period ui-button" value="24h"/>
</div>
this is my chart.js file
var fanspeedlabels = [], fanspeed = [], temp = [];
function updateFanSpeedData() {
function formatDate(itemdate) {
return moment(itemdate).format("MMM Do HH:mm");
}
$.ajax({
url: 'api.php?getFanSpeed24hrs&PHP',
dataType: 'json'
}).done(function (results) {
results.forEach(function (packet) {
if (fanspeedlabels.indexOf(formatDate(packet.start_time)) === -1) {
fanspeedlabels.push(formatDate(packet.start_time));
fanspeed.push(parseFloat(packet.fanspeed));
temp.push(parseFloat(packet.temp));
}
});
fanspeedChart.update();
fanspeeddata = results;
});
}
setInterval(function () {
// console.log('updateFanSpeedData');
// updateFanSpeedData();
}, 6000);
var fanspeedChartctx = document.getElementById("fanspeedChart");
var newfanspeed = fanspeed + "%";
var fanspeedChart = new Chart(fanspeedChartctx, {
type: 'line',
data: {
labels: fanspeedlabels,
datasets: [{
label: 'FanSpeed',
data: fanspeed,
backgroundColor: 'rgb(60, 141, 188)',
fill: false,
borderColor: 'rgb(60, 141, 188)',
borderWidth: 1,
cubicInterpolationMode: 'monotone',
yAxisID: "y-axis-1"
},
{
label: 'Temp',
data: temp,
backgroundColor: 'rgba(255, 99, 132, 1)',
fill: false,
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1,
yAxisID: "y-axis-1"
}
]
},
options: {
hover: {
animationDuration: 0 // duration of animations when hovering an item
},
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
yAxes: [{
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "left",
id: "y-axis-1",
ticks : {
min: 0,
max: 100
}
},
{
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
ticks : {
min: 0,
max: 100
}
}
],
xAxes: [
{
display: true,
scaleLabel: {
display: true
},
ticks: {
maxRotation: 0,
minRotation: 0
}
}
]
},
tooltips: {
enabled: true,
mode: "x-axis",
intersect: false,
callbacks: {
label: function(t, d) {
var xLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel;
if(t.datasetIndex === 0) {
return 'Fan Speed: ' + yLabel.toFixed(0) + '%';
}
else if (t.datasetIndex === 1) {
return 'CPU Temp: ' + yLabel.toFixed(0) + '°C';
}
}
}
}
}
});
$(".period").click( function() {
var period = this.id;
minValue = new Date();
switch(period){
case "30m":
minValue.setMinutes(minValue.getMinutes() - 30);
break;
case "1h":
minValue.setHours(minValue.getHours() - 1);
break;
case "6h":
minValue.setHours(minValue.getHours() - 6);
break;
case "12h":
minValue.setHours(minValue.getHours() - 12);
break;
case "24h":
minValue.setHours(minValue.getHours() - 24);
break;
default:
minValue
}
var startdate = moment(minValue).format("MMM Do HH:mm");
fanspeedChart.options.scales.xAxes[0].ticks.max = startdate;
fanspeedChart.update();
});
updateFanSpeedData();
The buttons work, Did have a console.log and the dates change currently but it doesn't update the chart with the current start point.
Any Help would be great, Starting to feel like I'm Going backwards.
Update something I Found
As I have dug a little deeper. The code seems to work, but because the "startdate" does not equal the exact date from the database it does not work. If by some chance there is the same date in the database it works. Is there a way I can make it so if any date higher than this date add. Dates show up as "Feb 16 19:50". if it sets min as "Feb 16 19:49" it will not work. Have tried suggestedMin aswell
As I worked out, as the min didn't match any dates from my database, needed a way to get the closest date to the date provided.
Added this and all working great now.
let closest = Infinity;
fanspeedlabels.forEach(function(d) {
const date = new Date(d);
if (date >= now && (date < new Date(closest) || date < closest)) {
closest = d;
}
});
fanspeedChart.options.scales.xAxes[0].ticks.min = closest;
fanspeedChart.update();
I am trying to display float bar on a browser.
But the item of float bar can not be found.
Is there no way to display it in Chart.js?
This page I found on GitHub was modifying Chart.js.
https://github.com/chartjs/Chart.js/pull/5262
http://pravopys.net/chartjs/samples/charts/bar/horizontal.html
However, I did not understand how to modify it.
Also, this page seemed to be trying to implement float bar support. However, it does not seem to be implemented yet.
https://github.com/chartjs/Chart.js/pull/6056
I will put the code of the page of float bar introduced above.
However, even if this code was used, only the lower part was displayed.
I think that it is also necessary to modify Chart.js itself.
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
window.randomScalingFactor = function() {
// return Math.round(Samples.utils.rand(-100, 100));
return (Math.random()*200 - 100);
};
if (document.location.hostname.match(/^(www\.)?chartjs\.org$/)) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-28909194-3', 'auto');
ga('send', 'pageview');
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var color = Chart.helpers.color;
var horizontalBarChartData = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset 1',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
borderWidth: 1,
data: [
[20, 70],
[-20,-70],
[getRandomInt(10,50), getRandomInt(50,100)],
[getRandomInt(10,50), getRandomInt(50,100)],
[getRandomInt(10,50), getRandomInt(50,100)],
[getRandomInt(10,50), getRandomInt(50,100)],
randomScalingFactor(),
randomScalingFactor()
]
}, {
label: 'Dataset 2',
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
data: [
[-10, 30],
[-20,-70],
[getRandomInt(-10,-50), getRandomInt(-50,-100)],
[getRandomInt(-10,-50), getRandomInt(-50,-100)],
[getRandomInt(-10,-50), getRandomInt(-50,-100)],
[getRandomInt(-10,-50), getRandomInt(-50,-100)],
randomScalingFactor(),
randomScalingFactor()
]
}]
};
console.log(horizontalBarChartData);
window.onload = function() {
console.log('t');
console.log(horizontalBarChartData);
let ctx = document.getElementById("Chart").getContext('2d');
window.myHorizontalBar = new Chart(ctx, {
type: 'horizontalBar',
data: horizontalBarChartData,
options: {
// Elements options apply to all of the options unless overridden in a dataset
// In this case, we are setting the border of each horizontal bar to be 2px wide
elements: {
rectangle: {
borderWidth: 2,
}
},
responsive: true,
legend: {
position: 'right',
},
title: {
display: true,
text: 'Chart.js Horizontal Bar Chart'
}
}
});
};
document.getElementById('randomizeData').addEventListener('click', function() {
var zero = Math.random() < 0.2 ? true : false;
horizontalBarChartData.datasets.forEach(function(dataset) {
dataset.data = dataset.data.map(function() {
return zero ? 0.0 : randomScalingFactor();
});
});
window.myHorizontalBar.update();
});
var colorNames = Object.keys(window.chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[horizontalBarChartData.datasets.length % colorNames.length];
var dsColor = window.chartColors[colorName];
var newDataset = {
label: 'Dataset ' + horizontalBarChartData.datasets.length,
backgroundColor: color(dsColor).alpha(0.5).rgbString(),
borderColor: dsColor,
data: []
};
for (var index = 0; index < horizontalBarChartData.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
}
horizontalBarChartData.datasets.push(newDataset);
window.myHorizontalBar.update();
});
document.getElementById('addData').addEventListener('click', function() {
if (horizontalBarChartData.datasets.length > 0) {
var month = MONTHS[horizontalBarChartData.labels.length % MONTHS.length];
horizontalBarChartData.labels.push(month);
for (var index = 0; index < horizontalBarChartData.datasets.length; ++index) {
horizontalBarChartData.datasets[index].data.push(randomScalingFactor());
}
window.myHorizontalBar.update();
}
});
document.getElementById('removeDataset').addEventListener('click', function() {
horizontalBarChartData.datasets.splice(0, 1);
window.myHorizontalBar.update();
});
document.getElementById('removeData').addEventListener('click', function() {
horizontalBarChartData.labels.splice(-1, 1); // remove the label first
horizontalBarChartData.datasets.forEach(function(dataset) {
dataset.data.pop();
});
window.myHorizontalBar.update();
});
I asked for a float bar. However, in fact, only a bar chart was displayed.
If you can not do it in Chart.js, I would appreciate it if you could show other possible libraries.
Floating bars are officially available since Chart.js v2.9.0. The feature was merged into chartjs:master with pull request #6056. Individual bars can now be specified with the syntax [min, max].
<html>
<head>
<title>Floating Bars</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div>
<canvas id="canvas" height="100"></canvas>
</div>
<script>
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: [1, 2, 3, 4, 5],
datasets: [{
label: 'data',
data: [[-3, 5], [2, 10], [1, 3], [-4, -1], [4, 8]],
backgroundColor: 'lightblue'
}]
},
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Horizontal Floating Bars'
}
}
});
};
</script>
</body>
</html>
My goal is to update my chart with new data from the server. Here's my code:
(function () {
'use strict';
let color = Chart.helpers.color;
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
let timeAxis = [{
type: 'time',
}];
let percentAxis = [{
ticks: {
beginAtZero: false,
callback: function(value) {
return Math.round(value * 1000) / 10 + '%';
}
}
}];
let buildChartObject = function (ctx, type, xAxes, yAxes) {
return new Chart(ctx, {
type: type,
data: null,
options: {
responsive: true,
title: {
display: true,
fontStyle: 'normal',
padding: 10,
fontSize: 12
},
scales: {
xAxes: xAxes,
yAxes: yAxes
},
legend: {
display: false
}
}
});
};
let loadChartData = function (endpoint, chart, params) {
$.ajax({
url: '/api/v1/' + endpoint,
method: 'GET',
dataType: 'json',
params: params,
success: function (d) {
let bgColors = null, bdColors = null;
if (chart.config.type === 'line') {
bgColors = color(window.chartColors.blue).alpha(0.5).rgbString();
bdColors = window.chartColors.blue;
} else {
bgColors = d.data.map(
(value) => value < 0 ? color(window.chartColors.red).alpha(0.5).rgbString() :
color(window.chartColors.green).alpha(0.5).rgbString()
);
bdColors = d.data.map(
(value) => value < 0 ? window.chartColors.red : window.chartColors.green
);
}
if (chart.options.scales.xAxes[0].type === 'time') {
let dateUnits = {
daily: 'day',
weekly: 'week',
monthly: 'month',
yearly: 'year'
};
chart.options.scales.xAxes[0].time.unit = dateUnits[d.params.convertTo];
}
chart.options.title.text = d.name;
chart.data.labels = d.index;
chart.data.datasets[0] = {
backgroundColor: bgColors,
borderColor: bdColors,
borderWidth: 1,
data: d.data
};
chart.update();
}
});
};
let loadCharts = function () {
let params = {
convertTo: $('#convert-to').val()
}
let returnsChart = buildChartObject($('#chart'), 'bar', timeAxis, percentAxis);
loadChartData('endpoint', returnsChart, params);
}
loadCharts();
$('#convert-to').on('change', function() {
loadCharts();
});
}());
The initial call to loadCharts() correctly populates the chart. However when when the #convert-to event is triggered, the loadCharts reloads the data but I have this flickering effect of both charts drawn on the same canvas. This is not a bug or a related issue, rather a canvas drawing one.
Have a look here: https://www.dropbox.com/s/9onofdazkvp9uas/clip.mov?dl=0
I've read countless threads on this and it seems like chart.update() should solve the issue. From the docs: "[update()] triggers an update of the chart. This can be safely called after updating the data object. This will update all scales, legends, and then re-render the chart."
What am I doing wrong?
You don't need to call buildChartObject(...) again when you are trying to just update the data for the chart. If you held onto a reference of the chart you would be fine to skip that call. Doing this will allow Chart.js to just update the chart when you call chart.update() instead of creating a new chart and then updating it.
...
let returnsChart = buildChartObject($('#chart'), 'bar', timeAxis, percentAxis);
let loadCharts = function () {
let params = {
convertTo: $('#convert-to').val()
};
loadChartData('endpoint', returnsChart, params);
}
loadCharts();
$('#convert-to').on('change', function() {
loadCharts();
});
...
I am trying to import a csv file and use it as the data source for my scatter chart in ChartJs. When I print dataPoints I get object arrays of the correct value so I know the ajax request is pulling properly. But I cant seem to pass these values into my datasets data as x and y values.
I was able to successfully pull the data and plug it into x and y values using canvasJS unfortunately that framework isn't free so I am trying to switch to chart.js. Ive tried plugging in data: [{dataPoints: pullData()}] or data: pullData() or data: [dataPoints] and plenty of other combinations but none seem to work. I am familiar with coding in swift and java but I'm particularly new to Javascript. Any help would be greatly appreciated!
const CHART = document.getElementById("scatterChart");
console.log(CHART);
var scatterChart = new Chart(CHART, {
type: 'scatter',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{
x: -10,
y: 0
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}],
borderColor: 'black',
borderWidth: 1,
pointBackgroundColor: '#00bcd6',
pointRadius: 5,
pointHoverRadius: 5,
fill: false,
tension: 0.5,
showLine: true
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}],
yAxes: [{
type: 'linear',
position: 'left'
}]
}
}
});
window.onload = function(){
$.ajax({
type: "GET",
url: "mockData.csv",
dataType: "text",
success: function (result){
var data = $.csv.toArrays(result);
var dataPoints = [];
for (var i = 0; i < data.length; i++)
dataPoints.push({
x: data[i][0],
y: data[i][1]
});
console.log(dataPoints)
return dataPoints
}
})
};
My goal is to plot the points from the csv (which is just 5 rows and 2 columns of basic numbers) but instead no points show up. Where as when I hand jam the values into x and y everything shows up fine.
You need to move the creation of the chart to inside the success function of the ajax call, or pass dataPoints into some other function that creates the chart.
After #terpinmd suggestion I was able to resolve the problem. Below is the code solution:
function getDataPointsFromCSV(csv) {
var dataPoints = csvLines = points = [];
for (var i = 0; i < csv.length; i++)
dataPoints.push({
x: csv[i][0],
y: csv[i][1]
});
console.log(dataPoints)
return dataPoints
}
window.onload = function(){
var dataPoints = [];
$.ajax({
type: "GET",
url: "mockData.csv",
dataType: "text",
success: function (result){
var data = $.csv.toArrays(result);
const CHART = document.getElementById("scatterChart");
console.log(CHART);
var scatterChart = new Chart(CHART, {
type: 'scatter',
data: {
datasets: [{
label: 'Scatter Dataset',
data: getDataPointsFromCSV(data),
borderColor: 'black',
borderWidth: 1,
pointBackgroundColor: '#00bcd6',
pointRadius: 5,
pointHoverRadius: 5,
fill: false,
tension: 0.5,
showLine: true
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}],
yAxes: [{
type: 'linear',
position: 'left'
}]
}
}
});
}
})
};
Wondering if anyone can help me out please.
I'm having trouble getting a Chart.js LineChart (with AJAX data) to refresh every "X" seconds. I've tried to put the code below in a function inside a setInterval and eventhough it does refresh, it redraws itself in a "zoomed-in" manner...
I want the chart to refresh itself every 10 seconds.
Code:
$.ajax({
type: "POST",
url: '#Url.Action("ChartRT")',
contentType: "application/json",
dataType: "json",
success:
function (chartsdata_RT) {
var aData = chartsdata_RT;
var aLabels = aData.map(c => c.Period);
var aDatasets1 = aData.map(c => c.FAILED);
var aDatasets2 = aData.map(c => c.OTHER);
var aDatasets3 = aData.map(c => c.DELIVERED);
var aDatasets4 = aData.map(c => c.PENDING);
var dataT = {
labels: aLabels,
datasets: [
{
label: "FAILED",
data: aDatasets1,
borderColor: '#ff0000',
backgroundColor: "rgba(255, 0, 0, 0.3)",
fill: 'true'
},
{
label: "OTHER",
data: aDatasets2,
borderColor: '#3366ff',
backgroundColor: "rgba(32, 162, 219, 0.3)",
},
{
label: "DELIVERED",
data: aDatasets3,
borderColor: '#009900',
backgroundColor: "rgba(0, 102, 0, 0.3)",
},
{
label: "PENDING",
data: aDatasets4,
borderColor: '#ff9900',
backgroundColor: "rgba(255, 153, 219, 0.3)",
}
]
};
var ctx = $("#chart_last2hours").get(0).getContext("2d");
ctx.canvas.height = "50";
var myNewChart = new Chart(ctx, {
type: 'line',
data: dataT,
options: {
legend: {
display: true,
position: 'right',
fullWidth: false,
labels: {
fontColor: '#484848',
fontsize: 10,
boxWidth: 20,
padding: 5,
lineWideth: 0
}
}
}
});
}
});
ended wrapping the above code in a function (drawChartRT). I then:
1) Call the function drawChartRT() to draw the LineChart.
2) Inside a setInterval remove and add the canvas and call the function drawChartRT().
drawChartRT();
setInterval(function () {
$("canvas#chart_last2hours").remove();
$("#chartdiv_rt").append('<canvas id="chart_last2hours" height="200"></canvas>');
var div = document.getElementById("chart_last2hours");
//console.log(div);
drawChartRT();
}, 10000);
Works like a charm!
Thanks. José