【问题标题】:In Chart.js, how do I hide certain axis labels from a stacked bar chart?在 Chart.js 中,如何从堆积条形图中隐藏某些轴标签?
【发布时间】:2021-01-28 20:49:16
【问题描述】:

我正在开发一个仪表板,它将显示带有票数的图表。我正在使用Chart.js 来呈现图表。这是一个例子:

在上面的屏幕截图中,Blocker 和 Critical 栏没有出现,因为它们的值为零。但是,Chart.js 仍然会在它们出现的地方呈现零。我认为这可能会让最终用户感到困惑,所以我想隐藏它(同时在图例中仍然显示该类别)。

bar chart documentation 中的以下段落让我认为_custom 可以做到这一点,但我无法让它发挥作用:

{x, y, _custom} 其中 _custom 是定义堆叠条形属性的可选对象:{start, end, barStart, barEnd, min, max}。 start 和 end 是输入值。这两个在 barStart(靠近原点)、barEnd(远离原点)、min 和 max 中重复。

有谁知道这是否可行?

作为参考,这是我当前的配置选项:

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

【问题讨论】:

标签: javascript charts chart.js


【解决方案1】:

我的同事想通了。您只需将其添加到选项数组中:

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

这是它最终的样子:

【讨论】:

    猜你喜欢
    • 2019-07-15
    • 1970-01-01
    • 2020-11-02
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    相关资源
    最近更新 更多