score:111
I had huge problems with this
First I tried .clear()
then I tried .destroy()
and I tried setting my chart reference to null
What finally fixed the issue for me: deleting the <canvas>
element and then reappending a new <canvas>
to the parent container
There's a million ways to do this:
var resetCanvas = function () {
$('#results-graph').remove(); // this is my <canvas> element
$('#graph-container').append('<canvas id="results-graph"><canvas>');
canvas = document.querySelector('#results-graph'); // why use jQuery?
ctx = canvas.getContext('2d');
ctx.canvas.width = $('#graph').width(); // resize to parent width
ctx.canvas.height = $('#graph').height(); // resize to parent height
var x = canvas.width/2;
var y = canvas.height/2;
ctx.font = '10pt Verdana';
ctx.textAlign = 'center';
ctx.fillText('This text is centered on the canvas', x, y);
};
score:0
The only solution I can find so far for myself is to re-initialize the chart from scratch:
var myLineChart = new Chart(ctx).Line(data, options);
However this seems a bit hokey to me. Any better, more standard solution anybody?
score:0
I had loads of trouble with this too. I have data and labels in separate arrays then I reinitialise the chart data. I added the line.destroy(); as suggested above which has done the trick
var ctx = document.getElementById("canvas").getContext("2d");
if(window.myLine){
window.myLine.destroy();
}
window.myLine = new Chart(ctx).Line(lineChartData, {
etc
etc
score:0
There is a way to do this without clearing the canvas or starting over, but you have to man handle the creation of the chart so that the data is in the same format for when you update.
Here is how I did it.
var ctx = document.getElementById("myChart").getContext("2d");
if (chartExists) {
for (i=0;i<10;i++){
myNewChart.scale.xLabels[i]=dbLabels[i];
myNewChart.datasets[0].bars[i].value=dbOnAir[i];
}
myNewChart.update();
}else{
console.log('chart doesnt exist');
myNewChart = new Chart(ctx).Bar(dataNew);
myNewChart.removeData();
for (i=0;i<10;i++){
myNewChart.addData([10],dbLabels[i]);
}
for (i=0;i<10;i++){
myNewChart.datasets[0].bars[i].value=dbOnAir[i];
}
myNewChart.update();
chartExists=true;
}
I basically scrap the data loaded in at creation, and then reform with the add data method. This means that I can then access all the points. Whenever I have tried to access the data structure that is created by the:
Chart(ctx).Bar(dataNew);
command, I can't access what I need. This means you can change all the data points, in the same way you created them, and also call update() without animating completely from scratch.
score:0
Chart JS 2.0
Just set chart.data.labels = [];
For example:
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
$chart.data.labels = [];
$.each(res.grouped, function(i,o) {
addData($chart, o.age, o.count);
});
$chart.update();
score:0
When creating the chart object you need to save the instance in a variable.
var currentChart = new Chart(ctx, ...);
And before loading new data, you need to destroy it:
currentChart.destroy();
score:0
Firstly, let a variable remember an instance of your chart.
let yourChart = new Chart(ctxBar, {
type: 'bar',
data: {
labels: labels,
datasets: datasets
},
});
Secondly, the thing I mostly struggled with was getting the data structure in the right format before updating the chart. So after looking at the data
key structure of chart js object:
data: {
labels: ['Jan', 'Feb'],
datasets: [{
label: 'Net sales',
data: data
}, {
label: 'Cost of goods sold',
data: data
}, {
label: 'Gross margin',
data: data
}]
}
Notice the data
key value is an object consisting of two keys, labels
and datasets
. labels
key' value is an array, while datasets
key' value is also an array with an object as value.
Therefore, to remove
labels and datasets from a chart instance I used:
yourChart.data.labels = [];
yourChart.data.datasets = [{}];
yourChart.update();
To add
labels and datasets to a chart instance I used:
yourChart.data.labels = ['label 1', 'label 2'];
yourChart.data.datasets = [{
label: 'column lables',
data: [450, 50],
backgroundColor: ["#dc3545", "#ffb759"]
}];
yourChart.update();
Prepare server side
The labels and datasets values can be prepared server side as follows (in my case php):
$datajs = function ($data, $bg_colour) // function emulating chart js datasets key value structure
{
return [
'data' => $data,
'backgroundColor' => $bg_colour
];
};
$datasets = [];
$labels = ['label 1', 'label 2'];
$datasets[] = $datajs([42,10], ["#dc3545", "#ffb759"]);
$datasets[] = $datajs([100,5], ["#dc3545", "#ffb759"]);
To just replace data from data key value from datasets (I did not test this)
yourChart.data.datasets.forEach((dataset) => {
dataset.data = [];
});
yourChart.update();
// if you have an array of arrays
let array = [[42,20],[58,68],[78,1]];
let length = yourChart.data.datasets.length;
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (i < length) {
yourChart.data.datasets[i].data = element;
} else {
yourChart.data.datasets[] = {data: element};
}
}
yourChart.update();
score:2
You need to clean old data. No need to re initialize:
for (i in myChartLine.datasets[0].points)
myChartLine.removeData();
score:2
If anyone is looking for how to do this in React. For a linechart, assuming you have a wrapper component around the chart:
(This assumes you are using v2. You do not need to use react-chartjs
. This is using the normal chart.js
package from npm.)
propTypes: {
data: React.PropTypes.shape({
datasets: React.PropTypes.arrayOf(
React.PropTypes.shape({
})
),
labels: React.PropTypes.array.isRequired
}).isRequired
},
componentDidMount () {
let chartCanvas = this.refs.chart;
let myChart = new Chart(chartCanvas, {
type: 'line',
data: this.props.data,
options: {
...
}
});
this.setState({chart: myChart});
},
componentDidUpdate () {
let chart = this.state.chart;
let data = this.props.data;
data.datasets.forEach((dataset, i) => chart.data.datasets[i].data = dataset.data);
chart.data.labels = data.labels;
chart.update();
},
render () {
return (
<canvas ref={'chart'} height={'400'} width={'600'}></canvas>
);
}
The componentDidUpdate
functionality allows you to update, add, or remove any data from the this.props.data
.
score:3
None of the above answers helped my particular situation in a very clean way with minimal code. I needed to remove all datasets and then loop to add in several datasets dynamically. So this snipped is for those that make it all the way to the bottom of the page without finding their answer :)
Note: make sure to call chart.update() once you have loaded all of your new data into the dataset object. Hope this helps somebody
function removeData(chart) {
chart.data.datasets.length = 0;
}
function addData(chart, data) {
chart.data.datasets.push(data);
}
score:3
Please Learn how Chart.js (version 2 here) works and do it for whatever attribute you want:
1.Please suppose you have a bar chart like the below in your HTML:
<canvas id="your-chart-id" height="your-height" width="your-width"></canvas>
2.Please suppose you have a javascript code that fills your chart first time (for example when page is loaded):
var ctx = document.getElementById('your-chart-id').getContext('2d');
var chartInstance = new Chart(ctx, {
type: 'bar',
data: {
labels: your-lables-array,
datasets: [{
data: your-data-array,
/*you can create random colors dynamically by ColorHash library [https://github.com/zenozeng/color-hash]*/
backgroundColor: your-lables-array.map(function (item) {
return colorHash.hex(item);
})
}]
},
options: {
maintainAspectRatio: false,
scales: {
yAxes: [ { ticks: {beginAtZero: true} } ]
},
title: {display: true, fontSize: 16, text: 'chart title'},
legend: {display: false}
}
});
Please suppose you want to update fully your dataset.
It is very simple. Please look at the above code and see how is the path from your chart variable to data and then follow the below path:
- select
chartInstance
var. - Then select
data node
inside thechartInstance
. - Then select
datasets node
inside thedata node
.
(note: As you can see, thedatasets node
is an array. so you have to specify which element of this array you want. here we have only one element in thedatasets node
. so we usedatasets[0]
- So select
datasets[0]
- Then select
data node
inside in thedatasets[0]
.
This steps gives you chartInstance.data.datasets[0].data
and you can set new data and update the chart:
chartInstance.data.datasets[0].data = NEW-your-data-array
//finally update chart var:
chartInstance.update();
Note: By following the above algorithm, you can simply achieve to each node you want.
score:4
I ran into the same issue, I have 6 pie charts on a page which can all be updated at the same time. I am using the following function to reset chart data.
// sets chart segment data for previously rendered charts
function _resetChartData(chart, new_segments) {
// remove all the segments
while (chart.segments.length) {
chart.removeData();
};
// add the new data fresh
new_segments.forEach (function (segment, index) {
chart.addData(segment, index);
});
};
// when I want to reset my data I call
_resetChartData(some_chart, new_data_segments);
some_chart.update();
score:4
I tried neaumusic solution, but later found out that the only problem with destroy is the scope.
var chart;
function renderGraph() {
// Destroy old graph
if (chart) {
chart.destroy();
}
// Render chart
chart = new Chart(
document.getElementById(idChartMainWrapperCanvas),
chartOptions
);
}
Moving my chart variable outside the function scope, got it working for me.
score:4
Not is necesary destroy the chart. Try with this
function removeData(chart) {
let total = chart.data.labels.length;
while (total >= 0) {
chart.data.labels.pop();
chart.data.datasets[0].data.pop();
total--;
}
chart.update();
}
score:6
According to docs, clear()
clears the canvas. Think of it as the Eraser tool in Paint. It has nothing to do with the data currently loaded in the chart instance.
Destroying the instance and creating a new one is wasteful. Instead, use API methods removeData()
and addData()
. These will add/remove a single segment to/from the chart instance. So if you want to load completely new data, just loop a chart data array, and call removeData(index)
(array indexes should correspond to current segment indexes). Then, use addData(index)
to fill it with the new data. I suggest wrapping the two methods for looping the data, as they expect a single segment index. I use resetChart
and updateChart
. Before continuing, make sure you check Chart.js
latest version and documentation. They may have added new methods for replacing the data completely.
score:8
I answered this here see How to clear a chart from a canvas so that hover events cannot be triggered?
But here is the solution:
var myPieChart=null;
function drawChart(objChart,data){
if(myPieChart!=null){
myPieChart.destroy();
}
// Get the context of the canvas element we want to select
var ctx = objChart.getContext("2d");
myPieChart = new Chart(ctx).Pie(data, {animateScale: true});
}
score:12
My solution to this is pretty simple. (VERSION 1.X)
getDataSet:function(valuesArr1,valuesArr2){
var dataset = [];
var arr1 = {
label: " (myvalues1)",
fillColor: "rgba(0, 138, 212,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(0, 138, 212,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: valuesArr1
};
var arr2 = {
label: " (myvalues2)",
fillColor: "rgba(255, 174, 087,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(255, 174, 087,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: valuesArr2
};
/*Example conditions*/
if(condition 1)
dataset.push(arr1);
}
if(condition 2){
dataset.push(arr1);
dataset.push(arr2);
}
return dataset;
}
var data = {
labels: mylabelone,
datasets: getDataSet()
};
if(myBarChart != null) // i initialize myBarChart var with null
myBarChart.destroy(); // if not null call destroy
myBarChart = new Chart(ctxmini).Bar(data, options);//render it again ...
No flickering or problems. getDataSet
is a function to control what dataset I need to present
score:18
ChartJS 2.6 supports data reference replacement (see Note in update(config) documentation). So when you have your Chart, you could basically just do this:
myChart.data.labels = ['1am', '2am', '3am', '4am'];
myChart.data.datasets[0].data = [0, 12, 35, 36];
myChart.update();
It doesn't do the animation you'd get from adding points, but existing points on the graph will be animated.
score:25
It is an old thread, but in the current version (as of 1-feb-2017), it easy to replace datasets plotted on chart.js:
suppose your new x-axis values are in array x and y-axis values are in array y, you can use below code to update the chart.
var x = [1,2,3];
var y = [1,1,1];
chart.data.datasets[0].data = y;
chart.data.labels = x;
chart.update();
score:47
With Chart.js V2.0 you can to do the following:
websiteChart.config.data = some_new_data;
websiteChart.update();
score:71
You need to destroy:
myLineChart.destroy();
Then re-initialize the chart:
var ctx = document.getElementById("myChartLine").getContext("2d");
myLineChart = new Chart(ctx).Line(data, options);
Source: stackoverflow.com
Related Query
- chart.js load totally new data
- Charts.js: Load new data set to an existing chart
- Chart.js load new data from saved JSON object
- Chart JS flicker when new data is added to chart (Vue)
- Chart.js: load new data on click
- Update Chart vue3-chart with new data
- How to load chart data to an appended canvas
- ChartJS chart is bugged after adding new data
- Load data from Google Analytics in a Chart.js chart
- How to load new chart (chartsjs) from api call with jquery?
- Update Chart JS data dynamically and add new data, remove old data to create timeline "like" chart
- How do I destroy/update Chart Data in this chart.js code example?
- Chart.js load new data
- Adding new data to empty Chart.js chart does not render new data correctly
- getting additional value fields from data source for dx.chartjs doughnut chart
- How can I add new data points to an existing chart with chart.js?
- How to load Json data onto a Charts.js chart
- Chart.js - How to set a line chart dataset as disabled on load
- Chartjs Bar Chart showing old data when hovering
- Chartjs random colors for each part of pie chart with data dynamically from database
- ChartJS New Lines '\n' in X axis Labels or Displaying More Information Around Chart or Tooltip with ChartJS V2
- ChartJS - Draw chart with label by month, data by day
- line chart with {x, y} point data displays only 2 values
- Chart JS data labels getting cut
- chart js tooltip how to control the data that show
- Chart.js Timeseries chart - formatting and missing data values
- Chart JS show multiple data points for the same label
- Add all data in the tooltip of Chart JS
- How to display data labels outside in pie chart with lines in ionic
- ng2-charts customize data and whole html content of tooltip displayed when hovering on bar chart
More Query from same tag
- How to show 2 populations types in one bar using chartjs?
- chart.js pie chart background colors: is there any way to generate them randomly?
- How to convert Json to Array In javascript for chart.js
- Moving the zerolines in ChartJS scatter chart
- Chart JS data labels getting cut
- Chart.js - disable tooltip when cursor moves outside the main canvas
- Save data from REST API Get method and use it one more time
- Chart.js v2 overwrite draw function
- Cannot read properties of null (reading 'getContext') at new EchartsDropdownComponent
- Chart js Backgroundimage Scaling
- How to unregister a chart plugin?
- Have text displayed instead of numerical values on y axis
- Chart.js chart onclick disables legend onclick
- How can I make bar charts symmetrical in chart.js?
- How to vary the thickness of doughnut chart, using ChartJs.?
- Google charts: Error: Row 0 has 1 columns, but must have 2
- chart.js 2 - Is it possible to format tick labels with HTML?
- Styling problems with Chart.Js
- Beginner in JS,Stuck with ChartJS and multiple filters and ways to display
- How to Remove axis Lines from chart in chart js
- What is the correct way to send 2 parameters in socket.io using lambdas? (I get undefined when printing in client and server)
- How do I add an image in the middle of Donut Chart?(Chart.js)
- how to render the same chart using Chart.js
- Ionic using multiple chart.js canvas in the same page
- Is it possible to add a javascript chart in a webview in Xamari.Forms
- Chart.js same Y axis on left and right
- How to get canvas/ctx object in Chart.js for an Angular project
- ChartJs chart won't update new values
- Using Javascript with MPDF
- How to set y axis to the max dataset value in Chartjs?