在chartjs中从柱到柱绘制点线

问题描述 投票:0回答:1

我想在栏后与下一个栏前创建线连接,如下图所示

chart.js
1个回答
0
投票

您可以使用自定义chartjs插件创建线条连接器,然后使用chartjs提供的画布在beforeDatasetsDraw回调上绘制线条,

使用

bar._model.y
获取每个条形的顶部位置

使用

bar._model.base
获取每个条形的底部位置

var options = {
  type: 'bar',
  data: {
    labels: ["a", "b", "c", "d", "e", "f"],
    datasets: [
        {
          label: 'A',
          data: [[12,14], [14,24],[10,12]],
        borderWidth: 1
        },
        ]
  },
  options: {
    scales: {
        yAxes: [{
        ticks: {
                    reverse: false
        }
      }]
    }
  }
}



const barConnector = {
  id: 'barConnector',
  beforeDatasetsDraw: function(chart, args, plugins){
    const { ctx, chartArea } = chart;
    ctx.save();
    const datasets = chart.config.data.datasets;

    datasets.forEach((dataset, datasetIndex) => {
      dataset.data.forEach((data, dataIndex) => {
        if(dataIndex === dataset.data.length - 1) return;
        const bar = chart.getDatasetMeta(datasetIndex).data[dataIndex];
        const barX = bar._model.x;
        const barY = bar._model.y;

        const nextBar = chart.getDatasetMeta(datasetIndex).data[dataIndex + 1];
        const nextBarX = nextBar?._model.x;
        const nextBarY = nextBar?._model.base;
        
        ctx.beginPath();
        ctx.moveTo(barX+46, barY);
        ctx.lineTo(nextBarX-46, nextBarY);
        ctx.strokeStyle = dataset.backgroundColor;
        ctx.lineWidth = 2;
        ctx.stroke();
      })
    });
  }
}

options.plugins = [barConnector]

var ctx = document.getElementById('chart-js').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<body>
    <canvas id="chart-js" width="600" height="400"></canvas>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.