Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

javascript - 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:

stacked bar chart screenshot

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;
                        }
                    }
                }
            }

question from:https://stackoverflow.com/questions/65945027/in-chart-js-how-do-i-hide-certain-axis-labels-from-a-stacked-bar-chart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...