programing

Charts.js는 통화와 천 단위 구분자로 Y 축 서식 지정

copysource 2021. 1. 16. 20:39
반응형

Charts.js는 통화와 천 단위 구분자로 Y 축 서식 지정


내 사이트에 그래프를 표시하기 위해 Charts.js를 사용하고 있습니다. 현재 레이블은 긴 숫자 문자열 (예 : 123456)로 표시됩니다. 천 단위 구분 기호가있는 통화로 표시하고 싶습니다 (예 : $ 123,456).

scaleLabel 옵션을 사용하여 값 앞에 $ USD 기호를 넣습니다.

scaleLabel: "<%= ' $' + Number(value)%>"

및 쉼표 구분 기호를 삽입하는 함수 :

function(label){return label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");}

내가 원하는 것을 얻기 위해 함께 사용하는 방법을 모르겠습니다.

여기 바이올린이 있습니다 : http://jsfiddle.net/vy0yhd6m/79/

(현재 그래프는 위에 인용 된 두 JavaScript 중 하나를 제거하는 경우에만 작동합니다.)

모든 도움에 감사드립니다.


함수 내 레이블 구성에 통화 접두사를 포함 할 수 있어야합니다.

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

http://jsfiddle.net/vy0yhd6m/80/


저는 chart.js를 처음 사용하지만 Billy Moon의 답변이 최신 버전 2.1.6에서 작동하도록하기 위해해야 ​​할 일이 있습니다.

  var data = {
    labels: ["12 AM", "1 AM", "2 AM", "3 AM", "4 AM", "5 AM", "6 AM", "7 AM", "8 AM", "9 AM", "10 AM", "11 AM", "12 PM", "1 PM", "2 PM", "3 PM", "4 PM", "5 PM", "6 PM", "7 PM", "8 PM", "9 PM", "10 PM", "11 PM"],
    datasets: [
      {
        label: "Sales $",
        lineTension: 0,
        backgroundColor: "rgba(143,199,232,0.2)",
        borderColor: "rgba(108,108,108,1)",
        borderWidth: 1,
        pointBackgroundColor: "#535353",
        data: [65, 59, 80, 81, 56, 55, 59, 80, 81, 56, 55, 40, 59, 80, 81, 56, 55, 40, 59, 80, 81, 56, 55, 40]
      }
    ]
  };

  //var myChart =
  new Chart(document.getElementById('sales-summary-today'), {
    type: 'line',
    data: data,
    options: {
      animation: false,
      legend: {display: false},
      maintainAspectRatio: false,
      responsive: true,
      responsiveAnimationDuration: 0,
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true,
            callback: function(value, index, values) {
              if(parseInt(value) >= 1000){
                return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
              } else {
                return '$' + value;
              }
            }
          }
        }]
      }
    }
  });

다시 말하지만, 레이블 서식 지정 기능에 대한 크레딧은 Billy Moon의 답변으로 이동합니다.


나는 대부분 다른 사람들이 언급 한 것을 요약하고 있지만,이 정확한 (그리고 자주 접하는) 질문에 대한 가장 깨끗한 해결책은 USD 통화 형식으로 방법 을 활용 하는toLocaleString 것이라고 생각합니다 .

return value.toLocaleString("en-US",{style:"currency", currency:"USD"});

이것은 모든 최신 브라우저에서 작동합니다. 에 대한 Mozilla 문서toLocaleString 에는 다른 로케일, 통화 및 형식화 유형 (예 : 백분율)에 대한 특정 브라우저 호환성 및 옵션이 나열되어 있습니다.

참고 Chart.js 버전 2+ (2016 년 4 월에 릴리스 됨) 에서는callback 고급 눈금 형식 지정 방법사용해야합니다 .

var chartInstance = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
     scales: {
       yAxes: [{
         ticks: {
           callback: function(value, index, values) {
             return value.toLocaleString("en-US",{style:"currency", currency:"USD"});
           }
         }
       }]
     }
   }
 });

Chart.js 버전 1.X를 사용하는 경우 구문 은 다음과 같습니다.

var myLineChart = new Chart(ctx).Line(data, options);
var data = {
  ...
}
var options = {
  scaleLabel: function(label) {
    return value.toLocaleString("en-US",{style:"currency", currency:"USD"});
}

구문 변경참조한 Perry Tew 사용할 아이디어대해서는 mfink에 감사드립니다 toLocaleString.


Perry Tew의 대답에 추가하면 축에 음수 달러 금액이있는 경우 (예 : 손익 차트를 표시 할 때) 다음을 사용할 수 있습니다.

ticks: {
    callback: function(value, index, values) {
        if(parseInt(value) > 999){
            return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        } else if (parseInt(value) < -999) {
            return '-$' + Math.abs(value).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        } else {
            return '$' + value;
        }
    }
}

음수 통화를 표시하는 올바른 형식은-$ XXX이므로 -$앞에 추가 한 다음 Math.abs ()를 통해 실행하여 양수로 변환합니다.


chartjs v2.0에서는 다음과 같은 전역 옵션을 설정할 수 있습니다.

Chart.defaults.global.tooltips.callbacks.label = function(tooltipItem, data) {
    return tooltipItem.yLabel.toLocaleString("en-US");
};

Chart.scaleService.updateScaleDefaults('linear', {
    ticks: {
        callback: function (value, index, values) {
            return value.toLocaleString();
        }
    }
});

Angular 2+ (ng2-charts)에 Charts.js를 사용하는 경우 CurrencyPipe. 레이블 형식을 지정하는 방법은 다음과 같습니다.

page.ts 파일에 종속성을 삽입하십시오.

import { CurrencyPipe } from '@angular/common';

내 차트 옵션 내에서 호출하는 방법은 다음과 같습니다.

public chartOptions: any = {
        responsive: true,
        legend: {
            display: false,
            labels: {
                display: false
            }
        },
        tooltips: {
          enabled: true,
          mode: 'single',
          callbacks: {
            label: function(tooltipItem, data) {
              let label = data.labels[tooltipItem.index];
              let datasetLabel = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
              let currencyPipe = new CurrencyPipe('en');
              let formattedNumber = currencyPipe.transform(datasetLabel, 'USD', 'symbol');
              return label + ': ' + formattedNumber;
            }
          }
        }
    };

Using chartjs v2.8.0, after looking around the docs, I found it here.

Instead of making my own formatter, I'm using numeraljs to format the number. So this is what I do:

import numeral from 'numeral'

options: {
  scales: {
    yAxes: [{
      ticks: {
        callback: function (value, index, values) {
          // add comma as thousand separator
          return numeral(value).format('0,0')
        },
      }
    }]
  },
  tooltips: {
    callbacks: {
      label: function (tooltipItem, data) {
        var label = data.datasets[tooltipItem.datasetIndex].label || ''

        if (label) {
          label += ': '
        }
        label += numeral(tooltipItem.yLabel).format('0,0')
        return label
      },
    },
  },
}

You can use format('$ 0,0') to add currency symbol along with comma thousand separator.


There is a specific javascript function to convert a long number into a number formatted according to system settings: toLocaleString().

You can specify that the label of each tick (or of a specific tick identified by its number index) must be built by your own function, by adding "callback:" keyword inside tick options:

Before:

        ticks: {
                  max: maxAltitude,
                  min: 0
                }

After:

        ticks: {
                  max: maxAltitude,
                  min: 0, // <--- dont' foget to add this comma if you already have specified ticks options
                    callback:  
                      function(value, index, valuesArray) {
                          // value: currently processed tick label
                          // index of currently processed tick label
                          // valuesArray: array containing all predefined labels
                          return  value.toLocaleString(); 
                      } // Function end
                } // Ticks options end

Without the comments and without unused variables:

        ticks: {
                  max: maxAltitude,
                  min: 0, 
                  callback:  
                      function(value) {
                        return  value.toLocaleString(); 
                      }
                }

참조 URL : https://stackoverflow.com/questions/28523394/charts-js-formatting-y-axis-with-both-currency-and-thousands-separator

반응형