chuckieDub
chuckieDub

Reputation: 1835

How to use same data / labels on two y axes in Chart.js

I have one set of data I'm using in angular-chart.js, but I want both y-axis to use the same data set (for the labels, I don't wish to chart the same data twice). If I just duplicate the code for both y axes, the left axes shows the correct data, while the right axes shows a scale from -1 at the minimum to 1 max.

...
scales: {
    yAxes: [{
        id: 'y-axis-1',
        type: 'linear',
        display: true,
        position: 'left',
        ticks: {
          beginAtZero: false,
          callback: function(value, index, values) {
            if (parseInt(value) >= 1000) {
              return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            } else {
              return '$' + value;
            }
          }
        }
      },
      {
        id: 'y-axis-2',
        type: 'linear',
        display: true,
        position: 'right',
        ticks: {
          beginAtZero: false,
          callback: function(value, index, values) {
            if (parseInt(value) >= 1000) {
              return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            } else {
              return '$' + value;
            }
          }
        }
      }
    ], ...

How to make the same labels show up on both y axes?

Upvotes: 2

Views: 2500

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32859

You can use the following chart plugin to show/use the same labels/ticks on two different y-axis :

Chart.plugins.register({
   beforeInit: function(chart) {
      chart.options.scales.yAxes[1].ticks.suggestedMin = Math.min.apply(this, chart.data.datasets[0].data);
      chart.options.scales.yAxes[1].ticks.suggestedMax = Math.max.apply(this, chart.data.datasets[0].data);
   }
});

- add this at the beginning of your script

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

Chart.plugins.register({
   beforeInit: function(chart) {
      chart.options.scales.yAxes[1].ticks.suggestedMin = Math.min.apply(this, chart.data.datasets[0].data);
      chart.options.scales.yAxes[1].ticks.suggestedMax = Math.max.apply(this, chart.data.datasets[0].data);
   }
});

var chart = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'LINE',
         data: [3, 1, 4, 2, 5],
         backgroundColor: 'rgba(0, 119, 290, 0.2)',
         borderColor: 'rgba(0, 119, 290, 0.6)',
         fill: false
      }]
   },
   options: {
      scales: {
         yAxes: [{
            id: 'y-axis-0',
            position: 'left',
            ticks: {
               stepSize: 1
            }
         }, {
            id: 'y-axis-1',
            position: 'right',
            ticks: {
               stepSize: 1
            }
         }]
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

Upvotes: 1

Related Questions