首页 > 解决方案 > 使用 chart.js 创建条形图,其中每个条形的空间相同,调整了整体图表大小

问题描述

这是我的 Javascript 选项和两个显示我创建的图表示例的屏幕截图。条的宽度设置为 50 像素。但是图表的整体大小是相同的,即使一张图表有两个条形图,而另外五个。这意味着有五个条的图表比有两个条的图表更紧,即使实际的条都是 50 像素。我正在寻找这两个图表之间的更多一致性,以便只有两个条形图的图表总体上会是一个“更短”的图表,其间距与具有五个条形图的图表相匹配。用chart.js可以吗?

options: {
    aspectRatio: 3,
    legend: {
        display: false
    },
    scales: {
        xAxes: [{
            barThickness: 50,
            ticks: {
                beginAtZero: true,
                suggestedMax: maxAxisX
            }
        }],
        yAxes: [{
            maxBarThickness: 50,
            ticks: {
                beginAtZero: true
            }
        }]
    }
}

截图 2

截图 1

标签: javascriptchartschart.js

解决方案


插件核心 API提供了一系列可用于执行自定义代码的钩子。您可以使用挂钩来根据图表中包含的条数来定义父beforeRender 级的高度。此函数还必须考虑图表顶部和下方所需的空间,尤其是在绘制 xAxis 刻度时。canvasdiv

plugins: [{
  beforeRender: chart => {
    if (!chart.config.options.nonChartAreaHeight) {
      var yAxis = chart.scales['y-axis-0'];
      chart.config.options.nonChartAreaHeight = chart.chart.height - (yAxis.bottom - yAxis.top);
    }
    const barThickness = chart.config.data.datasets[0].barThickness;
    const chartAreaHeight = (chart.config.data.labels.length * barThickness * 2);
    document.getElementById("chartWrapper").style.height = (chartAreaHeight + chart.config.options.nonChartAreaHeight) + 'px';
  }
}],

请注意aspectRatio,我们需要定义而不是定义选项maintainAspectRatio: false

请查看下面生成两个图表的代码示例。此解决方案使用 Chart.js (2.9.3) 的最新稳定版本。

new Chart('myChart', {
  type: 'horizontalBar',
  plugins: [{
    beforeRender : chart => {        
      if (!chart.config.options.nonChartAreaHeight) {
        var yAxis = chart.scales['y-axis-0'];
        chart.config.options.nonChartAreaHeight = chart.chart.height - (yAxis.bottom - yAxis.top);
      }
      const barThickness = chart.config.data.datasets[0].barThickness;
      const chartAreaHeight = (chart.config.data.labels.length * barThickness * 2);
      document.getElementById("chartWrapper").style.height = (chartAreaHeight + chart.config.options.nonChartAreaHeight) + 'px';      
    }
  }],
  data: {
    labels: ['1', '2', '3', '4'],
    datasets: [{
      barThickness: 20,
      data: [100, 90, 80, 70]
    }]
  },
  options: {
    maintainAspectRatio: false,
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
div {  
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div id="chartWrapper">
  <canvas id="myChart"></canvas>
</div>


推荐阅读