如何删除 Chartjs 条形图中那些值为零的条形图?

How to remove bars for those bars with zero value in Chartjs bar chart?

即使在使用 chartjs 创建的条形图中条形图的值为零,它们仍然显示可见条形图。这对我的目的具有误导性,我想将其删除并在那里不显示任何内容(这意味着,我仍然希望显示值为零的标签而不是栏)。我尝试更改 y 轴的最小值,但没有任何区别。下图显示了第 56、60 和 78 列的这个问题。有没有办法解决这个问题?谢谢!

这是我的脚本:

<div>
  <canvas id="canvas_bar" height="250", width = "300" ></canvas>
</div>

<script>
    var barChartData = {
        labels : [56, 60, 78, 90],
        datasets : [
        {   fillColor : "rgba(139,0,0,0.5)",
            strokeColor : "rgba(220,220,220,0.8)",
            data : [20.0, 0, 0, 50]  },

        {   fillColor : "rgba(1,187,205,0.5)",
            strokeColor : "rgba(151,187,205,0.8)",
            data : [0, 0.0, 40.0, 10]  }
        ]
    }
    window.onload = function(){
        var ctx = document.getElementById("canvas_bar").getContext("2d");
        window.myBar = new Chart(ctx).Bar(barChartData, {
            animation: false,
            responsive : false,
            barValueSpacing : 15,
            scaleShowVerticalLines: false,
        });
    }
</script>

默认情况下 barStrokeWidth 值为 2。

只需添加:

barStrokeWidth:0,

或:

barShowStroke : false,

在您的选择中。

http://www.chartjs.org/docs/#bar-chart-chart-options

//Boolean - If there is a stroke on each bar

barShowStroke : true,

//Number - Pixel width of the bar stroke

barStrokeWidth : 2,

如果barShowStroke : true

不工作尝试

barRadius: 0

2021 年 12 月更新:

  • barStrokeWidth 已弃用。
  • 我使用了 inflateAmount: 0(默认值为 auto),它为我解决了这个问题

文档:https://www.chartjs.org/docs/latest/charts/bar.html#dataset-properties

我发现您可以将 skipNull 属性 添加到数据集对象。值为 nullundefined 的柱不会采用任何 space.

https://www.chartjs.org/docs/3.2.0/charts/bar.html