Chart.js-如何将标签的值显示为X和Y值的百分比-当前始终为100%

时间:2019-02-28 00:11:28

标签: javascript chart.js percentage chart.js2

我正在使用Chart.js以及Chart.js插件(图表标签)。我想在条形图的顶部显示标签,并在标签中显示x值相对于y值的百分比(例如16为17的94%),但标签值始终为100 %(似乎正在以16x = 100的比例计算16y)。

我没有找到没有插件的方法,所以我不确定插件是否是问题,或者图表配置是否错误。

任何建议/帮助都将受到赞赏!这是一个带有代码的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
                }
            }
        }
});

这是一个截图,说明了我要做什么: Figure 1: All labels showing 100% instead of actual value

2 个答案:

答案 0 :(得分:2)

您可以创建自己的渲染函数,如下所示:

...

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

...

下面是示例代码: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);
}

...

try/catch块仅用于自动从数据集中获取最大值。

插件文档以及可以添加到render的所有其他可能的设置位于:https://github.com/emn178/chartjs-plugin-labels

答案 1 :(得分:0)

我不确定我是否完全了解您要实现的目标,但是您可以使用回调函数沿yAxes生成所需的结果,类似于:

yAxes:[{
    ticks:{
        callback:function(value,index,values){
            return ((value / index) * 100)+'% ';
        }
    }
}]