首页 > 解决方案 > Angular Chartjs 重叠条形图与 Chartjs 版本 2.7

问题描述

我正在尝试编写一个角度页面,该页面将显示带有 chartjs 2.7 版的重叠条形图。我正在关注此网址上的代码

https://jsfiddle.net/17hvoa9t/11/

我发现它适用于chartjs ver 2.5,但我需要它才能与Chartjs 2.7一起使用

当我使用 chartjs 2.7 时,只有 1 个条形集重叠,而其他两个没有重叠。我一直在阅读有关 barPercentage 和 categoryPercentage 的charts.org,但尝试为这两个数据集设置它们,但它仍然不起作用。

这是渲染的页面

https://ibb.co/3YLTb2H

到目前为止,这是我的代码

ngOnInit() {
    var data = {
      labels: ["x1", "x2", "x3"],
      datasets: [{
        label: "First",
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderWidth: 1,
        data: [10, 20, 30],
        xAxisID: "bar-x-axis1",
      }, {
        label: "Second",
        backgroundColor: 'rgba(255, 206, 86, 0.2)',
        borderWidth: 1,
        data: [5, 30, 35],
        xAxisID: "bar-x-axis2",
      }]
    };

    var options = {
      scales: {
        xAxes: [{
          stacked: true,
          id: "bar-x-axis1",
          barThickness: 30,
          type: 'category',
          categoryPercentage: 0.8,
          barPercentage: 0.9,
          gridLines: {
            offsetGridLines: true
          }
        }, {
          display: false,
          stacked: true,
          id: "bar-x-axis2",
          barThickness: 70,
          // these are needed because the bar controller defaults set only the first x axis properties
          type: 'category',
          categoryPercentage: 0.8,
          barPercentage: 0.9,
          gridLines: {
            offsetGridLines: true
          }
        }],
        yAxes: [{
          stacked: false,
          ticks: {
            beginAtZero: true
          },
        }, {
          type: 'category',
          categoryPercentage: 0.8,
          barPercentage: 0.9,
          gridLines: {
            offsetGridLines: true
          }
        }

      ]

      }
    };

    var ctx = document.getElementById("myChart").getContext("2d");
    var myBarChart = new Chart(ctx, {
      type: 'bar',
      data: data,
      options: options
    });

  }

}


HTML

<canvas id="myChart" width="500" height="300"></canvas>

标签: angularchart.js

解决方案


您的第二个 x 轴需要offset设置为true

{
  display: false,
  stacked: true,
  id: "bar-x-axis2",
  barThickness: 70,
  // these are needed because the bar controller defaults set only the first x axis properties
  type: 'category',
  offset: true, // <-- This property needs added
  categoryPercentage: 0.8,
  barPercentage: 0.9,
  gridLines: {
    offsetGridLines: true
  }
}

chart.js笛卡尔坐标轴文档声明这默认为true,但这显然仅适用于第一个轴。

如果为 true,则会在两条边上添加额外的空间,并缩放轴以适合图表区域。默认情况下,此设置true用于条形图中的类别比例。


推荐阅读