Justin Maat
Justin Maat

Reputation: 1975

Chart.js How to invert (swap) axes?

Taking from inspiration from this question, I am trying to figure out how to swap the axes of a Line chart in Chart.js.

For instance, in Highcharts we have this example, although it's an area chart.

Is it possible to "swap" the X and Y axis on a line chart?

datasets: [
    {
        label: "data1a",
        data: [1,2,3,4,5,1,2,3]
    }
]
yAxes: [
   {
     type: "linear",
     display: true,
     position: "left",
    }
]

Here's my fiddle modified from the above link. I'm basically trying to move it so the graph looks rotated 90 degrees. I tried changing the y position to 'top' but it still doesn't look correct.

Upvotes: 9

Views: 7064

Answers (2)

ThomaSEK
ThomaSEK

Reputation: 21

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',
        },
      ],
    }
  }
})

Upvotes: 2

dralth
dralth

Reputation: 159

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/

Upvotes: 1

Related Questions