Chart.js - How To Show Value of Label as Percent of X and Y Values - Currently Always 100%

问题: I am using Chart.js along with a Chart.js plugin, chart-labels. I am wanting to show the labels at the top of the bar chart, and in the label show the percentage of the x v...

问题:

I am using Chart.js along with a Chart.js plugin, chart-labels. I am wanting to show the labels at the top of the bar chart, and in the label show the percentage of the x value in relation to the y value (e.g., 16 is 94% of 17), but the label values are always 100% (which it seems like it is calculating 16y by 16x = 100).

I haven't found a way to do this without the plugin, so I'm not sure if the plugin is the issue or not, or if the chart configuration is wrong.

Any advice/help is appreciated! Here is a JSBin with the code: https://jsbin.com/jeqesapobi/edit?html,js,output

HTML and 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
                }
            }
        }
});

Here's a screenshot illustrating what I'm going for: Figure 1: All labels showing 100% instead of actual value


回答1:

I'm not sure I have a complete grasp of what you're trying to achieve, but you could use a callback function to generate the desired result along the yAxes, similar to this:

yAxes:[{
    ticks:{
        callback:function(value,index,values){
            return ((value / index) * 100)+'% ';
        }
    }
}]
  • 发表于 2019-03-01 03:02
  • 阅读 ( 336 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除