简体   繁体   中英

In Chart.js, how do I hide certain axis labels from a stacked bar chart?

I'm developing a dashboard that will show charts with ticket counts. I'm using Chart.js to render the charts. Here's an example:

堆积条形图屏幕截图

In the above screenshot, Blocker and Critical bars don't appear as they have a value of zero. However, Chart.js still renders a zero where they would be. I think this may confuse end users, so I'd like to hide it (while still showing that category in the legend).

The following passage from the bar chart documentation makes me think this is possible with _custom , but I haven't been able to get it working:

{x, y, _custom} where _custom is an optional object defining stacked bar properties: {start, end, barStart, barEnd, min, max}. start and end are the input values. Those two are repeated in barStart (closer to origin), barEnd (further from origin), min and max.

Does anyone know if this is possible?

For reference, here are my current config options:

        options: {
                scales: { // make this a stacked chart
                    xAxes: [{
                        stacked: true
                    }],
                    yAxes: [{
                        stacked: true
                    }]
                },
                legend: {
                    labels: {
                        boxWidth: 20 // how wide boxes on legend are
                    }
                },
                tooltips: { 
                    callbacks: {
                        footer: (tooltip_items, data) => { // add a total count to tooltips
                            let total = 0;
                            tooltip_items.forEach(element => total = total + parseInt(element.value));
                            return 'Total: ' + total;
                        }
                    }
                }
            }

My coworker figured it out. You just need to add this to the options array:

plugins: {
   datalabels: {
      display: function(context) {
         return context.dataset.data[context.dataIndex] > 0; // only return if greater than zero
      }
   }
}

Here's how it ends up looking:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM