19

I am creating line charts with 2 y-axes. one of those axes has two datasets but both run from the range of 0-100. The higher number being the better one. The second y-axis is usually lower in range (often in the single digits) and the best result is 1.

How can I invert the second y-axis so that 1 is at the top of the chart?

(I will try to find a solution myself, but at 5k+ lines in chart.js, it might take a while )

Thanks ^_^

GreysonTyrus
  • 687
  • 1
  • 6
  • 15

4 Answers4

30

Dev 2.0 of chart js supports an option to reverse the ticks when setting up the axis so your declaration of the second axis would become

{
    type: "invertedLinear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
    display: true,
    position: "right",
    id: "y-axis-2",
    ticks: {
        reverse: true
    },
    // grid line settings
    gridLines: {
        drawOnChartArea: false, // only want the grid lines for one axis to show up
    }
}

Here it is in action https://jsfiddle.net/nwc8ys34/15/

Quince
  • 14,790
  • 6
  • 60
  • 69
23

Using v 2.7.0, and the following seems to work:

options: {
  scales: {
    yAxes: [{
      ticks: {
        reverse: true,
      }
    }]
  }
}
Aniko Litvanyi
  • 2,109
  • 1
  • 21
  • 25
Stephen Paul
  • 37,253
  • 15
  • 92
  • 74
3

In v3 the scale configs have been changed so the desired behaviour can be accomplished like so:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [40, 80, 100, 70, 60, 80],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange',
        yAxisID: 'y2'
      }
    ]
  },
  options: {
    scales: {
      y: {},
      y2: {
        position: 'right',
        reverse: true
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
0

Chart.js 4:

datasets: [{
    label: "Strength",
    yAxisID: "y1",
    data: mappedData.sigStrength
}, {
    label: "Bars",
    yAxisID: "y2",
    data: mappedData.sigBars
}]
scales: {
    y1: {
        type: "linear",
        display: true,
        position: "left",
        reverse: true
    },
    y2: {
        type: "linear",
        display: true,
        position: "right",
        ticks: {
            stepSize: 1
        }
    }
},
lendoo
  • 332
  • 4
  • 5