Change axis title dynamically - Javascript Chart.js

Javascript examples for Chart.js:Axis

Description

Change axis title dynamically

Demo Code

ResultView the demo in separate window

<html lang="en">
   <head> 
      <title>Chart.js Dynamically Change Scale Title</title> 
   </head> 
   <body translate="no"> 
      <div style="width: 50%"> 
         <canvas id="canvas"></canvas> 
         <button id="changeTitle">Change Title</button> 
      </div> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script> 
      <script>
      window.chartColors = {//  ww  w. j a v  a  2s  . c o m
   red: 'rgb(255, 99, 132)',
   orange: 'rgb(255, 159, 64)',
   yellow: 'rgb(255, 205, 86)',
   green: 'rgb(75, 192, 192)',
   blue: 'rgb(54, 162, 235)',
   purple: 'rgb(153, 102, 255)',
   grey: 'rgb(231,233,237)'
};
window.randomScalingFactor = function() {
   return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 10000);
}
var barChartData = {
  labels: ["Car","Recharge","Food"],
  datasets: [{
    label: 'Students',
    backgroundColor: window.chartColors.red,
    yAxisID: 'y-axis-0',
    data: [
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
    ]
  }]
};
var title = "Total Riders";
var alternateTitle = "Riders < Age 30";
var xAxesOptions = [{
  id: 'y-axis-0',
  display: true,
  type: 'linear',
  position: 'left',
  scaleLabel: {
    display: true,
    labelString: title
  }
}];
var myBar;
window.onload = function() {
  myBar = new Chart(document.getElementById("canvas").getContext("2d"), {
    type: 'bar',
    data: barChartData,
    options: {
      title:{
        display: true,
        text: "Chart.js - Dynamically Change Scale Title"
      },
      tooltips: {
        mode: 'index',
        intersect: false
      },
      responsive: true,
      scales: {
        yAxes: xAxesOptions
      }
    }
  });
};
document.getElementById('changeTitle').addEventListener('click', function() {
  if (myBar.options.scales.yAxes[0].scaleLabel.labelString === title) {
    myBar.options.scales.yAxes[0].scaleLabel.labelString = alternateTitle;
  } else {
    myBar.options.scales.yAxes[0].scaleLabel.labelString = title;
  }
  myBar.update();
});
      //# sourceURL=pen.js
    
      </script>  
   </body>
</html>

Related Tutorials