0

首先,如果我的问题与其他问题略有相同,我深表歉意。我搜索了一个解决方案,发现了 3 个类似的问题,但没有一个对我有用,因为我找到的示例使用 Chart.js v1。

我看到了一个示例,它使用一个函数scaleLabel来格式化数字,如下所示:

var options = {
    animation: false,
    scaleLabel: function(label){
        return  '$' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
};

但是,上面的代码在新的 Chart.js v2 中不再有效。

如何格式化 Chart.js v2 中的比例数字?

这是我的代码:https ://jsfiddle.net/2n7xc7j7/

4

3 回答 3

0

添加选项配置时,您需要确保将设置嵌套在正确的部分中。您可以通过向刻度配置部分添加一个callback函数来格式化刻度数字:yAxes

options = {
    scales: {
        yAxes: [{
            ticks: {
                callback: function(value) {
                    return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                }
            }
        }]
    }
};

JSFiddle 演示:https ://jsfiddle.net/2n7xc7j7/1/

于 2017-05-18T16:59:36.537 回答
0

在 V3 中locale添加了该属性。这样一来,工具提示上的所有数字都会自动以该国家/地区代码的数字格式正确格式化:

// Element
const ctx = document.getElementById("myChart")

// Data
const data = {
  labels: ['First', 'Second', 'Third', 'Fourth'],
  datasets: [{
    label: 'Sample',
    data: [2982, 1039, 3200, 2300],
    backgroundColor: "rgba(90, 150, 220, 0.85)",
    borderColor: "rgba(70, 120, 180, 1)",
    borderWidth: 2
  }],
}

// Options
const options = {
  locale: 'en-US'
};

const chart_trans_hari = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: options
});
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>

于 2021-11-02T23:45:08.707 回答
-1

我这样做了:

http://profwtelles.ddns.net/grafico2.html

    var canvas = document.getElementById('chart');
    new Chart(canvas, {
        type: 'line',
        data: {
            labels: ['1', '2', '3', '4', '5'],
            datasets: [{
                label: 'A',
                yAxisID: 'A',
                data: [100, 96, 84, 76, 69]
            }, {
                label: 'B',
                yAxisID: 'B',
                data: [1, 1, 1, 1, 0]
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    id: 'A',
                    type: 'linear',
                    position: 'left',
                }, {
                    id: 'B',
                    type: 'linear',
                    position: 'right',
                    ticks: {
                        max: 1,
                        min: 0
                    }
                }]
            }
        }
    });

我希望能帮助你。此致

于 2017-11-06T10:46:07.307 回答