Bar*_*ski 4 bar-chart chart.js
我想知道有没有办法在ChartJs(条形图)条形图中显示零值?
我的意思是这样的:https://jsfiddle.net/vrg5cnk5/16/,所以第二个栏就是零级的蓝色边框.
我已使用此代码:
ticks: {
beginAtZero: true,
min: 0,
suggestedMin: 0
}
Run Code Online (Sandbox Code Playgroud)
但我并不感到惊讶它不起作用.
提前致谢
tal*_*alz 10
只需minBarLength在数据集中指定条形应具有的最小长度(以像素为单位)。请参阅文档。
工作示例:
var $chartCanvas = $('myCanvas');
var barChart = new Chart(myCanvas, {
type: 'bar',
data: {
labels: ['Accepted Answer', 'Top rated answer', 'This Answer'],
datasets:[{
data: [0, 3, 10],
minBarLength: 7, // This is the important line!
}]
},
options: {
title: {
display: true,
text: 'helpfulness of answers to this questions'
},
legend: {
display: false
}
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="myCanvas"></canvas>Run Code Online (Sandbox Code Playgroud)
深入研究插件系统后,如果你使用Chart.js> = 2.5,你可以编写一个插件来实现它.以下是数据为零时绘制线条的示例.
这是我的代码:
const zeroCompensation = {
renderZeroCompensation: function (chartInstance, d) {
// get postion info from _view
const view = d._view
const context = chartInstance.chart.ctx
// the view.x is the centeral point of the bar, so we need minus half width of the bar.
const startX = view.x - view.width / 2
// common canvas API, Check it out on MDN
context.beginPath();
// set line color, you can do more custom settings here.
context.strokeStyle = '#aaaaaa';
context.moveTo(startX, view.y);
// draw the line!
context.lineTo(startX + view.width, view.y);
// bam? you will see the lines.
context.stroke();
},
afterDatasetsDraw: function (chart, easing) {
// get data meta, we need the location info in _view property.
const meta = chart.getDatasetMeta(0)
// also you need get datasets to find which item is 0.
const dataSet = chart.config.data.datasets[0].data
meta.data.forEach((d, index) => {
// for the item which value is 0, reander a line.
if(dataSet[index] === 0) {
this.renderZeroCompensation(chart, d)
}
})
}
};
Run Code Online (Sandbox Code Playgroud)
以下是如何向Chart.js添加插件
var chart1 = new Chart(ctx, {
plugins: [plugin]
});
Run Code Online (Sandbox Code Playgroud)
官方文档不清楚他们的插件API,你可以在console.log中找到你想要的东西.
无法配置chart.js来执行此操作,但是您可以改用hack。只需将0 bar的值设置为非常小的数字(例如0.1)即可。
data: [2, 0.1, 3, 1]
Run Code Online (Sandbox Code Playgroud)
这是您的一个例子。
如果使用工具提示,则还必须添加一些逻辑,以便该工具栏的工具提示仍显示值为0。您可以使用label回调来执行此操作。
label: function(tooltipItem, data) {
var value = data.datasets[0].data[tooltipItem.index];
var label = data.labels[tooltipItem.index];
if (value === 0.1) {
value = 0;
}
return label + ': ' + value + ' %';
}
Run Code Online (Sandbox Code Playgroud)
这是将所有内容放在一起的示例。
| 归档时间: |
|
| 查看次数: |
7874 次 |
| 最近记录: |