iakwvina
iakwvina

Reputation: 83

chartjs: How to remove specific label

I have a Bar Chart with these data and options:

var data = {
    labels: periodnames,
    datasets: [          
        {
            yAxisID: "bar-stacked",
            data: rcash,
            backgroundColor: "#FFCE56",                  
            label:""
        },
    {
        yAxisID:"bar-stacked",
        data: pcash,
        backgroundColor: "#FFCE56",
        label: "cash"           

    }       

    ]

};

var options = {        
    animation: {
        animateScale: true
    },        
    scales: {
        xAxes: [{
        stacked: true,
    }],        
        yAxes: [ 
            {
                display:false,
                id: "line-axis",                  

            },
            {
            id: "bar-stacked",
            stacked: true,                

        }            
        ]
    }
}

finactivityGraphChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: options
});

The result chart is this: enter image description here

My problem is that I don't want to show the first dataset's label. If I don't define it, it shows the yellow box with the value "undefine" next to it. I suppose that I must modify the Chart.js file. Any suggestions?

Upvotes: 4

Views: 5318

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32859

This could be achieved, using the filter function of legend­*'s* label.

see Legend Label Configuration

In short, add the following in your chart options ...

legend: {
   labels: {
      filter: function(label) {
         if (label.text === 'cash') return true;
      }
   }
},

ᴅᴇᴍᴏ

var ctx = document.querySelector('#c').getContext('2d');
var data = {
   labels: ['Jan', 'Feb', 'Mar'],
   datasets: [{
      yAxisID: "bar-stacked",
      data: [1, 2, 3],
      backgroundColor: "#FFCE56",
      label: "gold"
   }, {
      yAxisID: "bar-stacked",
      data: [-1, -2, -3],
      backgroundColor: "#FFCE56",
      label: "cash"
   }]
};
var options = {
   legend: {
      labels: {
         filter: function(label) {
            if (label.text === 'cash') return true; //only show when the label is cash
         }
      }
   },
   animation: {
      animateScale: true
   },
   scales: {
      xAxes: [{
         stacked: true,
      }],
      yAxes: [{
         display: false,
         id: "line-axis",
      }, {
         id: "bar-stacked",
         stacked: true,
      }]
   }
}
finactivityGraphChart = new Chart(ctx, {
   type: 'bar',
   data: data,
   options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
<canvas id="c"></canvas>

Upvotes: 9

Related Questions