Search code examples
javascriptangularchart.js

Show only the first 2 bars on the Y-Axis using Chart.js?


I have a bar graph which needs to display a set of values like Total Likes (likes on Facebook+Twitter+LinkenIn...) Total Comments(comments on Facebook+Twitter+LinkenIn...)

My dataset currently holds Total Likes, Total Comments, Facebook Likes, Twitter likes etc) I need the Facebook Likes, Twitter likes etc in my dataset since I need to show them in a tool tip.

So how do I limit my bar chart to only the first two bars in the group? Havent found an option when I was going through the chart.js APIs.

Sample graph


Solution

  • You can do this after the chart has been initialized using setDatasetVisibility. From the chart.js API Docs:

    chart.setDatasetVisibility(1, false); // hides dataset at index 1
    chart.update(); // chart now renders with dataset hidden
    

    Or, you can set this option when you initially create the charts using the hidden attribute:

    const cfg = {
      type: 'bar',
      data: {
        datasets: [{
          label: 'Facebook',
          data: data,
          hidden: false
    
        }, {
          label: 'Instagram',
          data: data,
          hidden: true
        }]
      },
    };