chart.js - 折线图末尾的范围
解决方案
这可以通过自定义插件对 canvas 进行直接绘制调用来实现,我在下面提供了一个示例。请注意,代码根据您的屏幕截图做了很多假设,应将其视为起点,而不是完美的直接解决方案。
let myChart = new Chart(document.getElementById('chart'), {
type: 'line',
data: {
labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
datasets: [{
label: 'Group1',
data: [-1000, -2000, -2000, -3000, -4000, -3000, -5000],
backgroundColor: '#F48496'
}, {
label: 'Group2',
data: [-4000, -4000, -3000, -6000, -6000, -5000, -9000],
backgroundColor: '#61B2E9'
}]
},
options: {
maintainAspectRatio: false,
layout: {
padding: {
right: 100
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
},
plugins: {
afterRender: function(c) {
let
// calculate difference between values of last two points in first and second datasets.
d = c.config.data.datasets[0].data[c.config.data.datasets[0].data.length - 1] - c.config.data.datasets[1].data[c.config.data.datasets[1].data.length - 1],
// position of last point in first dataset.
xy0 = c.getDatasetMeta(0).data[c.getDatasetMeta(0).data.length - 1]._model,
// position of last point in second dataset.
xy1 = c.getDatasetMeta(1).data[c.getDatasetMeta(1).data.length - 1]._model;
c.ctx.save();
// draw the line.
c.ctx.strokeStyle = 'black';
c.ctx.beginPath();
c.ctx.moveTo(xy0.x + 10, xy0.y);
c.ctx.lineTo(xy0.x + 15, xy0.y); // draw the upper horizontal line.
c.ctx.lineTo(xy0.x + 15, xy1.y); // draw the vertical line.
c.ctx.lineTo(xy1.x + 10, xy1.y); // draw the lower horizontal line.
c.ctx.stroke();
// draw the text.
c.ctx.font = '20px sans-serif';
c.ctx.fillStyle = 'black';
c.ctx.fillText(
d, // text
c.chartArea.right + 25, // text x position
xy0.y + ((xy1.y - xy0.y) / 2) // text y position
);
c.ctx.restore();
}
}
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart"></canvas>
推荐阅读
- angular - 错误 TS2304:找不到名称“ImageCapture”并且已安装 @types/w3c-image-capture
- magento - 如何在magento 2.2中以编程方式通过观察者从购物车中删除简单产品?
- google-drive-api - 需要使用存储在我的应用程序中的 GDrive 编辑文件
- ms-access - 正确管理 Access 中的错误“参数太少。应为 1”
- excel - 如何在应用程序中按时传递变量?
- python - Python 在 Jupyter 上重定向 Sqoop 执行输出
- java - 如何在 tomcat 服务器上正确安装来自 sslforfree.com 的证书
- smartcard - 追加记录 APDU 得到 69、86 的错误响应,即使存在 EF 文件
- javascript - 如何将方法返回数据解析为角度5中另一个函数内的参数
- node.js - 发现错误后如何继续运行我的脚本?