首页 文章

ChartJS:在给甜甜圈赋值之前挂钩(图表中的绝对值和工具提示中的实际值)

提问于
浏览
0

由于ChartJS甜甜圈以一种奇怪的方式呈现负值(或者以我不需要的方式呈现),我想保留我在工具提示中的值,但是将值设置为甜甜圈本身的绝对值 .

在创建工具提示之前有一个回调来修改工具提示(http://www.chartjs.org/docs/#chart-configuration-tooltip-configuration),但我没有找到对实际值做同样的工具提示 .

我错过了什么或者我是否需要以某种方式破解?

1 回答

  • 1

    这是你如何实现这一目标......

    ♦使用原始数据中的绝对值创建临时数据数组,并在创建图表时使用该数据数组

    ♦对工具提示使用以下回调函数

    callbacks: {
        label: function(t, d) {
            return d.labels[t.index] + ': ' + data[t.index];
        }
    }
    

    var ctx = document.getElementById("chart").getContext("2d");
    
    // original data array
    var data = [1, -2, 3, -4];
    
    // temporary data array \w absolute values
    var temp_data = data.map(function(e) {
        return Math.abs(e);
    });
    
    var myDoughnut = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ["January", "February", "March", "April"],
            datasets: [{
                data: temp_data,
                backgroundColor: ['#ff3d67', '#ff9f40', '#ffcd56', '#4bc0c0'],
            }]
        },
        showDatapoints: true,
        options: {
            responsive: false,
            legend: false,
            tooltips: {
                displayColors: false,
                callbacks: {
                    label: function(t, d) {
                        return d.labels[t.index] + ': ' + data[t.index]; // 'data' represents the original data array
                    }
                }
            }
        }
    });
    
    body{margin-top:0;overflow:hidden}
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
    <canvas id="chart" width="218"></canvas>
    

相关问题