ChartJS条形图固定宽度的动态数据集

时间:2017-08-28 07:25:18

标签: javascript jquery html5-canvas chart.js

我正在使用ChartJs来创建条形图。 数据集是动态的。因为数据集是动态的,所以条的宽度也在变化。

仅适用于一个标签的示例条宽度
enter image description here

许多标签的条宽 enter image description here

如何固定条形宽度而不管标签数量

我使用以下选项。

xAxes: [{
    barPercentage: 1,
    categoryPercentage: 0.3
}]

1 个答案:

答案 0 :(得分:2)

您可以将“categoryPercentage”划分为尽可能多的列,并乘以当前数据集中的列数

https://jsfiddle.net/qrwvvtxs/2/

var barChartData1 = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: 'Dataset 1',
    data: [3,2,7,4,5,7,6]
  }, {
    label: 'Dataset 2',
    backgroundColor: "#faa",
    data: [11,13,21,13,16,21,18]
  }]
};
var barChartData2 = {
  labels: ["January"],
  datasets: [{
    label: 'Dataset 1',
    data: [6]
  }, {
    label: 'Dataset 2',
    backgroundColor: "#faa",
    data: [11]
  }]
};

var ctx1 = document.getElementById("canvas1").getContext("2d");
var ctx2 = document.getElementById("canvas2").getContext("2d");
var myBar1 = new Chart(ctx1, {
  type: 'bar',
  data: barChartData1,
  options: {
    responsive: true,
    scales: {
      xAxes: [{
          barPercentage: 1,
          categoryPercentage: 0.5 / 10 * barChartData1.datasets[0].data.length
      }],
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    }
  }
});
var myBar2 = new Chart(ctx2, {
  type: 'bar',
  data: barChartData2,
  options: {
    responsive: true,
    scales: {
      xAxes: [{
          barPercentage: 1,
          categoryPercentage: 0.5 / 10 * barChartData2.datasets[0].data.length
      }],
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>