我有一个图表(粗蓝色条)垂直酒吧我试图得到水平线之间的酒吧像下面的图片。....我试着在chartjs网站上找,但找不到答案。
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>
1条答案
按热度按时间5rgfhyps1#
我认为你需要一个自定义插件来做到这一点。
下面是一个原型: