chartjs条之间的水平线,而不是顶部到顶部

kxe2p93d  于 2023-04-30  发布在  Chart.js
关注(0)|答案(1)|浏览(189)

我有一个图表(粗蓝色条)垂直酒吧我试图得到水平线之间的酒吧像下面的图片。....
我试着在chartjs网站上找,但找不到答案。

5rgfhyps

5rgfhyps1#

我认为你需要一个自定义插件来做到这一点。
下面是一个原型:

const plugin = {
  id: 'lineToBar',
  afterDraw(chart) {
    const ctx = chart.ctx;
    const meta = chart.getDatasetMeta(0);
    const data = meta.data;
    const count = data.length;
    ctx.save();
    ctx.lineWidth = 2;
    for (let i = 0; i<(count-1); i++) {
      const k = i + 1;
      const from = data[i];
      const x = from.x + from.width /2;
      const to = data[k];
      const x2 = to.x - to.width / 2;
      ctx.strokeStyle = from.options.backgroundColor;
      ctx.beginPath();
      ctx.moveTo(x, from.y + ctx.lineWidth / 2);
      ctx.lineTo(x2, from.y + ctx.lineWidth / 2);
      if (from.y < to.y) {
        ctx.lineTo(x2, to.y);
      }
      ctx.stroke();
    }
    const last = data[count-1];
    const area = chart.chartArea;
    ctx.strokeStyle = last.options.backgroundColor;
    ctx.beginPath();
    ctx.moveTo(last.x + last.width /2, last.y + ctx.lineWidth / 2);
    ctx.lineTo(area.right, last.y + ctx.lineWidth / 2);
    ctx.stroke();
    ctx.restore();
  }
};
const labels2 = ["A", "B", "C", "D", "E", "F", "G"];
const config2 = {
  type: 'bar',
  plugins: [plugin],
  data: {
    labels: labels2,
    datasets: [{
      label: 'ds',
      data: labels2.map(() => Math.random() * 100)
    }]
  },
  options: {
  }
};
const chart = new Chart(
  document.getElementById('myChart'),
  config2
);
document.getElementById("randomize").addEventListener('click', function() {
  const data = labels2.map(() => Math.random() * 100);
  chart.data.datasets[0].data = data;
  chart.update();
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<html>
  <head>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.2.1/dist/chart.umd.min.js"></script>
  </head>  
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600px" height="400px"/>
    </div>
    <button id="randomize">Randomize</button>
  </body>
</html>

相关问题