Joy*_*rex 5 javascript percentage chart.js chart.js2
我正在使用 Chart.js 和 Chart.js 插件图表标签。我想在条形图顶部显示标签,并在标签中显示 x 值相对于 y 值的百分比(例如,16 是 17 的 94%),但标签值始终为 100 %(看起来像是在计算 16y x 16x = 100)。
我还没有找到没有插件的方法来做到这一点,所以我不确定插件是否有问题,或者图表配置是否错误。
任何建议/帮助表示赞赏!这是带有代码的 JSBin:https ://jsbin.com/dawenetuya/edit?html,js,output
HTML 和 JS:
<div style="width: 100%;"><canvas id="myChart"></canvas></div>
var colors = '#cd1127';
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Asset Taxes", "Excluded Assets", "Personal Injury and Property Damage", "Offsite Disposal", "Royalties", "Litigation", "Employment", "Operating Expenses"],
datasets: [{
data: [16, 14, 17, 13, 15, 12, 9, 11],
backgroundColor: '#cd1127',
borderColor: '#cd1127',
borderWidth: 1
}]
},
options: {
responsive: true,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 18,
beginAtZero:true
}
}]
},
plugins: {
labels: {
render: 'percentage',
showActualPercentages: true
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
您可以像这样创建自己的渲染函数:
...
render: function (args) {
let max = 17; //This is the default 100% that will be used if no Max value is found
try {
//Try to get the actual 100% and overwrite the old max value
max = Object.values(args.dataset.data).map((num) => {
return +num; //Convert num to integer
});
max = Math.max.apply(null, max);
} catch (e) {}
return Math.round(args.value * 100 / max);
}
...
Run Code Online (Sandbox Code Playgroud)
这是示例代码: https: //jsbin.com/hihexutuyu/1/edit
您实际上可以擦除该try/catch块并仅定义max值,它将起作用。它看起来像这样:
...
render: function (args) {
let max = 17; //Custom maximum value
return Math.round(args.value * 100 / max);
}
...
Run Code Online (Sandbox Code Playgroud)
该try/catch块只是自动从数据集中获取最大值。
插件文档以及可以添加的所有其他可能的设置render位于: https: //github.com/emn178/chartjs-plugin-labels。
| 归档时间: |
|
| 查看次数: |
7237 次 |
| 最近记录: |