带有Chartjs ver 2.7的Angular Chartjs重叠条形图

时间:2019-04-17 16:28:36

标签: angular chart.js

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

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

我发现它可以与Chartjs 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>

1 个答案:

答案 0 :(得分:1)

您的第二个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 cartesian axes docs声明默认为true,但这显然仅适用于第一个轴。

  

如果为true,则将额外的空间添加到两个边缘,并且将缩放轴以适合图表区域。默认情况下,条形图中的类别比例设置为true

相关问题