score:70
with the approach you are taking (e.g. creating a new chart object each time the date range changes), then you must first destroy the previous chart and then create the new one.
you can use the .destroy()
prototype method to do this. here is exactly what the api states.
use this to destroy any chart instances that are created. this will clean up any references stored to the chart object within chart.js, along with any associated event listeners attached by chart.js. this must be called before the canvas is reused for a new chart.
therefore, your code would look something like this (notice that we destroy and re-create).
// define a variable to store the chart instance (this must be outside of your function)
var mychart;
function loadftprchart(startdate, enddate) {
var bcdata = {
labels: [],
datasets: [{
label: "pass %",
backgroundcolor: "#536a7f",
data: [],
stack: 1
}, {
label: "fail %",
backgroundcolor: "#e6e6e6",
data: [],
stack: 1
}, {
label: "auto %",
backgroundcolor: "#286090",
data: [],
stack: 2
}, {
label: "manual %",
backgroundcolor: "#f0f0f0",
data: [],
stack: 2
}]
};
$.getjson("content/ftpr_am_graph_ajax.php", {
startdate: startdate,
enddate: enddate,
location: "m"
})
.done(function(data) {
console.log("data", data);
$.each(data.aadata, function(key, val) {
if (val == "") {
return true
}
bcdata.labels.push("coater " + val[0]);
bcdata.datasets[0].data.push(parsefloat(val[2]));
bcdata.datasets[1].data.push(parsefloat(100 - val[2]));
bcdata.datasets[2].data.push(parsefloat(val[1]));
bcdata.datasets[3].data.push(parsefloat(100 - val[1]));
});
var option = {
responsive: true,
};
console.log("bcdata", bcdata);
// if the chart is not undefined (e.g. it has been created)
// then destory the old one so we can create a new one later
if (mychart) {
mychart.destroy();
}
var ctx = document.getelementbyid("mybarchart2").getcontext("2d");
mychart = new chart(ctx, {
type: 'groupablebar',
data: bcdata,
options: {
scales: {
yaxes: [{
ticks: {
max: 100,
},
stacked: true,
}]
}
}
});
});
}
with that said, it's expensive the destroy/create over and over and actually it isn't even necessary. there is another prototype method called .update()
that you can use to just re-render the chart if you have changed it's underlying data or label objects.
here is a jsfiddle showing an example of changing the underlying data and labels and then re-rendering the chart. i would highly recommend you take this approach instead.
here is how your code would look taking this better approach.
// define a variable to store the chart instance (this must be outside of your function)
var mychart;
function loadftprchart(startdate, enddate) {
var bcdata = {
labels: [],
datasets: [{
label: "pass %",
backgroundcolor: "#536a7f",
data: [],
stack: 1
}, {
label: "fail %",
backgroundcolor: "#e6e6e6",
data: [],
stack: 1
}, {
label: "auto %",
backgroundcolor: "#286090",
data: [],
stack: 2
}, {
label: "manual %",
backgroundcolor: "#f0f0f0",
data: [],
stack: 2
}]
};
$.getjson("content/ftpr_am_graph_ajax.php", {
startdate: startdate,
enddate: enddate,
location: "m"
})
.done(function(data) {
console.log("data", data);
$.each(data.aadata, function(key, val) {
if (val == "") {
return true
}
bcdata.labels.push("coater " + val[0]);
bcdata.datasets[0].data.push(parsefloat(val[2]));
bcdata.datasets[1].data.push(parsefloat(100 - val[2]));
bcdata.datasets[2].data.push(parsefloat(val[1]));
bcdata.datasets[3].data.push(parsefloat(100 - val[1]));
});
var option = {
responsive: true,
};
console.log("bcdata", bcdata);
// if the chart is not undefined (e.g. it has been created)
// then just update the underlying labels and data for each
// dataset and re-render the chart
if (mychart) {
mychart.data.labels = bcdata.labels;
mychart.data.datasets[0].data = bcdata.datasets[0].data;
mychart.data.datasets[1].data = bcdata.datasets[1].data;
mychart.data.datasets[2].data = bcdata.datasets[2].data;
mychart.data.datasets[3].data = bcdata.datasets[3].data;
mychart.update();
} else {
// otherwise, this is the first time we are loading so create the chart
var ctx = document.getelementbyid("mybarchart2").getcontext("2d");
mychart = new chart(ctx, {
type: 'groupablebar',
data: bcdata,
options: {
scales: {
yaxes: [{
ticks: {
max: 100,
},
stacked: true,
}]
}
}
});
}
});
}
score:0
the code of the provided samples by chartjs.org have shown that they don't destroy() the chart and create a new one. instead, they pop() the existing data from the chart and push() the new dataset to the graph and then update() the chart.
this code is from the chartjs.org website which removes the dataset from the chart by pop().
document.getelementbyid('removedataset').addeventlistener('click', function() {
horizontalbarchartdata.datasets.pop();
window.myhorizontalbar.update();
});
and this code is for adding the dataset to the chart by push():
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 + 1),
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();
});
the last step of these two code blocks is to update the chart.
generally speaking, it is necessary to pop the data that you want to remove from the chart and then push the new data and finally update the chart. therefore, the pervious data is not going to be shown when hovering.
score:0
i know this is old, but most of these didn't work in my situation, so i'm posting what worked for me.
i had two charts exhibiting this behavior, a z-stacked bar chart and a pie chart. i tried these to no avail:
mychart.destroy()
: this would work to change the values, but for some reason also affected the size and display values for my chartsoptions: { events: [] }
: as said in that post, this removes all tooltips on hover, which i still wantedinnerhtml
: i don't know if this is a newer feature of chartjs, but none of my charts ever had an innerhtml attribute apart from""
mychart.datasets.pop()
: this one is the spirit behind my solution, but in most cases i had more than one dataset, so i just removed them all:
if (mychart !== undefined) {
while (mychart.data.datasets.length > 0) {
mychart.data.datasets.pop();
}
}
i was also previously creating var mychart
with the function i was using to create the chart and organize the data. after moving that variable declaration outside the function and implementing the above within the function, they work like a charm!
score:0
what worked for me (maybe it's ineffective but this isn't a bit issue to me as it would only be done a few times per visit) - destroying and recreating the whole canvas object (using jquery).
$("#canvasid").remove();
$("<canvas>").attr({
id: "canvasid"
}).appendto("#canvasparent");
score:0
i could not get the "destroy()" to work at all. i struggled. i ended up removing the element altogether, then recreating on each update of data.
if(document.getelementbyid(chartid)) {
document.getelementbyid(chartid).remove();
}
var canvasparent;
// i had 2 charts, so a ternary to select the right element
chartid == 'fleet-fuel-chartcomp1' ? canvasparent = document.getelementbyid('canvas-node1') : canvasparent = document.getelementbyid('canvas-node2');
var canvas = document.createelement('canvas');
canvas.id = chartid;
canvasparent.appendchild(canvas);
var ffc = document.getelementbyid(chartid);
score:0
why this problem happened
this problem occurs, when we change the graph data by ajax. it will append the data in the graph. when we hover on that previous point it highligts the previous graph.
soluctions: it will work 100%.
$('#chart').html('');
$('#chart').html('<canvas id="chartcanvas" style="height: 350px;"></canvas>');
score:0
i tried all the suggestions above and they did not work, it turned out my function:
function initchart(data, label) {
if(!data){
data = sanitizedata({!! json_encode($subsequentsickdays) !!});
label = "employees with x amount of sickdays";
}
$('#chartjs-custom').html('');
$('#chartjs-custom').html('<canvas id="chart-absence" class="js-chart"></canvas>');
return $.hscore.components.hschartjs.init($('#chart-absence'), {
"type": "pie",
"data": setchartdata(data, label),
"options": options()
});
}
was being initialised twice on page load. one when i defined var chart = initchart()
and when i initialised it with initchart()
. after i removed initchart()
it worked. don't know why this would matter but hey, it works, hope this helps someone.
score:1
i was found the problem and my solution is remove them from html first and before load new chart then append canvas.
html
$('#chart').empty();
$('#chart').html('<canvas id="survey_result" width="400" height="200"></canvas>'); // then load chart.
var ctx = document.getelementbyid("survey_result");
<div id="chart" class="display>
</div>
score:1
declare mychart as a global variable
let mychart;
before graph creation just write
function piechart(pdata) {
// destroy previous created graph
if (mychart) {
mychart.destroy()
}
let ctx = document.getelementbyid("pie-chart").getcontext('2d');
mychart = new chart(ctx, {
type: 'doughnut',
data: {
labels: ['count'],
datasets: [{
backgroundcolor: [
"#2ecc71",
],
data: [pdata],
}]
},
});
}
why we adding this? because, if we create any graph at first time the mychart create a object, in that case when we rander it, it won't be change. that's why we need to destroy previous object and create new object for newer visualization.
score:2
after stackoverflowing for so many hours i found and easy solution to it no need to do so many changes ... just add this line in options section
events:[]
in the options section it is an quick solution to get rid from chartjs bar chart showing old data when hovering
if you need hovering event also then try to reinitialise or re-render the canvas adding if conditions this will fix for sure
score:8
there is a simple solution for this, which can be done in js itself.
let's say your html has something like below
<div id="chartcontainer">
<canvas id="mybarchart2"></canvas>
</div>
then in your script, you can add below lines of code before updating the data.
document.getelementbyid("chartcontainer").innerhtml = ' ';
document.getelementbyid("chartcontainer").innerhtml = '<canvas id="mybarchart2"></canvas>';
var ctx = document.getelementbyid("mybarchart2").getcontext("2d");
this solved my issue.
score:11
it will help you...
check whether mychart have already configurations or not, if it exist clear it with destroy(); method, and bind new configuration to canvas.
sample code..
if (window.mychart != undefined)
{
window.mychart.destroy();
}
window.mychart = new chart(ctx, mychartconfig);
score:14
this is chartjs trick i found
var ctxline = document.getelementbyid("line-chart").getcontext("2d");
if(window.bar != undefined)
window.bar.destroy();
window.bar = new chart(ctxline, {});
https://therichpost.com/solved-hovering-chartjs-bar-chart-showing-old-data
Source: stackoverflow.com
Related Query
- Chartjs Bar Chart showing old data when hovering
- Chartjs Bar Chart showing old data when hovering when use of ajax
- ng2-charts customize data and whole html content of tooltip displayed when hovering on bar chart
- ChartJS not showing data for time series bar chart
- ChartJS dynamic line chart ghosting back to old data when hovered on
- Chart Js , loading data on selection but bar graph displaying old values as well on hovering
- Chartjs - data format for bar chart with multi-level x-axes
- Line chart is showing under bar in combochart in chartjs
- ChartJS bar not showing up for simple data points
- ChartJS bar chart fixed width for dynamic data sets
- canvas fill text vanishes when hovering over chartjs pie chart
- Chart js shows old chart data when hover
- How to make chartJs stacked bar always rounded when data is 0?
- chart js chart bar chart not showing data from 0
- ChartJS bar chart - trigger hover even when the cursor is outside of the bar
- Bar Chart Not Stacking When Using ChartJs
- Problems hovering over ChartJS bar chart after being redrawn
- ChartJS 2.9.4 can't overlay line data on Horizontal Bar chart
- Artefacts when showing compact vertical bar chart in chart.js
- How to show the chartjs bar chart data values labels as text?
- ChartJS: Highlight dataset in a stacked bar chart when hovering over the legend?
- Chartjs bar chart appears empty when page loads
- Hovering over line chart shows old chart data issue in chart.js
- Chartjs - Stacked bar chart data order causes invisible other values
- chart js: when all the values passed to data are zeros, nothing is showing
- ChartJS showing old values when mouse over on Doughnut after updating values
- Dynamically loaded chart data not showing Chartjs React
- Show/hide All nested data in ChartJS Pie chart when outer is shown/hidden
- ChartJS Bar Chart not respecting disabled legend when using cdn
- ChartJS vertical bar chart - measure percentage of the data in each column based on a specified max
More Query from same tag
- Can you add an action to an element within the tooltip in chart.js?
- My chart.js canvas disappears after hide() function
- Chartjs: display value in html element when hovering a bar
- Pass data to Chart Js Laravel
- How to group chart labels together?
- How to create a stacked donut chart in Angular 5
- How do I align chart.js pie charts?
- Chartjs-node installation failing
- Add a custom label to the top or bottom of a stacked bar chart
- Append suffix to Chart.js dataset?
- How could I skip drawing empty/zero value and its value on tooltip
- How to use computed property with data from JSON in data object for time axis in Vue using Chart.js
- How to remove Chart.js legend
- chart.js how to display max value?
- Zoom is very slow in ChartJS Zoom Plugin
- Change background color of label Chart.js
- Chart.js Date and Time Bar Chart Not Rendering - Line Works Though
- Remove "label" in chart.js
- Why are more columns on one labels in Angular ChartJS?
- why isnt vue-chartjs receiving data from api?
- Chart JS not displaying graph
- Have all label in Chartjs be at fixed positions
- How to modify chartjs tooltip to add customized attribute
- MYSQL Query and Chart.js and PHP
- Javascript chart one number step
- Specific grid line in X axis in ChartJs
- vue-chartjs remove top rectangle (datasets label)
- Can't display chart.js after fadeOut the pageloader
- I need help on Optimization of Laravel Controller
- Chart.js - change which data the legend uses for the coloured box