How to check chart type on chart.js?

Member

by denis , in category: Javascript , 7 months ago

How to check chart type on chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 7 months ago

@denis 

To check the type of chart being used in Chart.js, you can access the 'type' property of the chart object. Here's how you can do it:

  1. First, you need to have a reference to the chart object. If you have created your chart using Chart.js, you may already have a variable storing the chart object.


For example, if you create a line chart like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Red', 'Blue', 'Yellow'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)'
            ],
            borderWidth: 1
        }]
    }
});


  1. You can then check the type of chart by accessing the 'type' property of the 'myChart' variable:
1
console.log(myChart.config.type); // This will log 'line'


By checking the 'type' property, you can determine if the chart is a line chart, bar chart, pie chart, etc.