[Chartjs]-Chart.js How to invert (swap) axes?

2👍

The proposal by @dralth works fine with version 2.8.0, but for some reason showLines: true does not work anymore since version 2.9.0.

It is still possible showing the lines by using the showLine property for each dataset.

In case of @dralth’s example it works as follows (tested with version 2.9.3):

new Chart(document.getElementById('myChart'), {
  type: 'scatter',
  data: {
    datasets: [
      {
        label: 'My Dataset',
        data: [{x: 3, y: 2}, {x: 5, y: 7}, {x: 9, y: 10}],
        showLine: true
      },
    ],
  },
  options: {
    scales: {
      xAxes: [
        {
          type: 'linear',
          position: 'bottom',
        },
      ],
      yAxes: [
        {
          type: 'linear',
        },
      ],
    }
  }
})

1👍

I was able to accomplish this in Chart.js 2.8.0:

  1. Change data to a list of objects with x and y. Since the intention is to swap x and y axis, put the “x data” in the y variable and vise verse.
    eg. [{x: 3, y: 2}, {x: 5, y: 7}, {x: 9, y: 10}]

  2. Set the chart type to ‘scatter’

  3. Add showLines: true to the options

The outcome is a line chart where the line can be horizontal, vertical, or even double back on itself. The orientation of the line is defined by which values you put in x and which you put in y.

Here’s an example configuration:

new Chart(document.getElementById('myChart'), {
  type: 'scatter',
  data: {
    datasets: [
      {
        label: 'My Dataset',
        data: [{x: 3, y: 2}, {x: 5, y: 7}, {x: 9, y: 10}],
      },
    ],
  },
  options: {
    showLines: true,
    scales: {
      xAxes: [
        {
          type: 'linear',
          position: 'bottom',
        },
      ],
      yAxes: [
        {
          type: 'linear',
        },
      ],
    }
  }
})

If you’re using an older version of Chart.js that doesn’t have scatter plots, you can use this plugin: http://dima117.github.io/Chart.Scatter/

Leave a comment