Reputation: 43
I am building external buttons to toggle the visibility of data from chartjs, but it will only works when the screen size changed. So, I found that can use mychart.update() to solve the problem. But it get me the error that I stated in the title.
Here is my chart:
var myRadarChart = {
type: 'radar',
data: {
labels: lbl,
datasets: [
{
label: 'Houses',
data: yh,
backgroundColor:['rgba(0, 123, 255, 0.5)'],
borderColor: ['rgba(0, 123, 255, 0.8)'],
hidden:false
},
{
label: 'Apartments',
data: ya,
backgroundColor:['rgba(40,167,69, 0.5)'],
borderColor: ['rgba(40,167,69, 0.8)'],
hidden:false
},
{
label: 'Rooms',
data: yr,
backgroundColor:['rgba(218, 17, 61,0.5)'],
borderColor: ['rgba(218,17,61,0.8)'],
hidden:false
}
]
},
options: {
legend:{
display:true,
onHover: function(event, legendItem) {
document.getElementById("myRadarChart").style.cursor = 'pointer';},
},
maintainAspectRatio:false,
scale: {
angleLines: {
display: true
},
ticks: {
suggestedMin: 0,
suggestedMax: 0
}
}
}
};
var ctx = document.getElementById('myRadarChart').getContext('2d');
new Chart(ctx, myRadarChart);
And how I trying to do is:
//Onclick
function getData(dontHide){
switch(dontHide){
case 0:
myRadarChart.data.datasets[0].hidden=false;
myRadarChart.data.datasets[1].hidden=true;
myRadarChart.data.datasets[2].hidden=true;
myRadarChart.update();
break;
case 1:
myRadarChart.data.datasets[0].hidden=true;
myRadarChart.data.datasets[1].hidden=false;
myRadarChart.data.datasets[2].hidden=true;
myRadarChart.update();
break;
case 2:
myRadarChart.data.datasets[0].hidden=true;
myRadarChart.data.datasets[1].hidden=true;
myRadarChart.data.datasets[2].hidden=false;
myRadarChart.update();
break;
}
}
Or is there alternative ways to perform something like this?
Upvotes: 3
Views: 7789
Reputation: 50664
Your issue is that you're trying to call the .update()
method on your graph's config object, not your actual graph instance. As you can see, myRadarChart
is just an object, it doesn't have a method called update()
on it. However, the graph you create when doing new Chart(ctx, myRadarChart);
does give you the .update()
method.
To fix your issue, you'll need to first store the instance of your graph somewhere:
var radarGraph = new Chart(ctx, myRadarChart);
Then update the graph's data (rather than your config object directly):
radarGraph.data.datasets[0].hidden = false;
...
Then call the update method on your radarGraph
object:
radarGraph.update();
Upvotes: 3