ChartJS to change axes label - Javascript Chart.js

Javascript examples for Chart.js:Axis

Description

ChartJS to change axes label

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>ChartJS label/ticks callback</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/* w w  w . j  a  va  2s.  c  o  m*/
percent = true;
var percents_array = [10, 20, 30, 40];
var ctx = document.getElementById("percents").getContext('2d');
var percents_chart = new Chart(ctx, {
  type: 'horizontalBar',
  data: {
    labels: ["Category 1", "Category 2", "Category 3", "Category 4"],
    datasets: [{
      backgroundColor: ["red", "blue", "yellow", "green"],
      label: "Count",
      data: percents_array
    }]
  },
  options: {
    scales: {
      yAxes: [{
        gridLines: {
          color: "rgba(0,0,0,0)"
        }
      }],
      xAxes: [{
        ticks: {
          beginAtZero: true,
          callback: function (value, index, values) {
           if (percent)
            return addCommas(value) + "%";
          else
            return addCommas(value);
          }
        }
      }]
    },
    plugins: {
      datalabels: {
        display: true,
        color: "#fff",
        formatter: function (value, context) {
           if (percent)
             return value + "%";
          else
             return value;
        }
      }
    },
    legend: {
      display: false
    },
    tooltips: {
      mode: 'index',
      intersect: false,
      callbacks: {
        label: function (tooltipItems, data) {
           if (percent)
             return addCommas(tooltipItems.xLabel) + "%";
          else
             return addCommas(tooltipItems.xLabel);
        }
      }
    },
    hover: {
      mode: 'nearest',
      intersect: true
    },
    responsive: true,
    title: {
      fontSize: "16",
      display: true,
      text: 'Categories by percentage'
    }
  }
});
percents_chart.percent = percent;
function addCommas(v) {return v;}
togglePercent = function() {
   percent = !percent;
  percents_chart.update();
}
    }

      </script> 
   </head> 
   <body> 
      <button onclick="togglePercent()">change</button> 
      <canvas id="percents" height="300" width="800"></canvas>  
   </body>
</html>

Related Tutorials