Chart.js switch x / y axis on a line chart

Say I have a line chart: https://jsfiddle.net/13fyhL4j/

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.js"></script>

<canvas id="myChart" width="400" height="400"></canvas>

JS:

var ctx = document.getElementById("myChart");
var yLabels = [0, 2, 3, 6, 7];
var xLabels = ['A', 'B', 'C', 'D', 'E'];

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: xLabels,
        datasets: [
            {
                type: 'line',
                label: 'Line',
                data: yLabels,
                fill: false,                
            }
        ]
    },
    options:{
        scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'x label'
                        },

                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'y label'
                        },

                    }]
                }
    }
});

Here, the x axis has a category scale, and the y axis has a linear scale. I need to swap the axis, however I cannot find how to make the linear x axis and y axis.

Image explanation

It is necessary to change not only the axis values, but also the graph itself.

+4
source share
1 answer

I could not find anything that indicates that you can do this with a line graph, but you can do it with a spread. The first step is to abstract the axis properties from xAxesand yAxes:

const xAxis = [{
    /*type: 'time', time: { displayFormats: {} }, whatever*/
}];

const revenueAxis = [{
    /*scaleLabel: {}, ticks: {}, whatever*/
}];

, :

let swapAxes = true;
const xValues = [1,2,3,4,5];
const yValues = [5,4,3,2,1];
let data = [];

const zipper = (a, b) => {
    for (let i of a) data.push({x: a[i-1], y: b[i-1]});
    return data;
}

data = condition ? zipper(yValues , xValues) : zipper(xValues, yValues );

, zipper() x y . ( , x y), , .

:

const options = {
    /*Whatever options you have*/,
    scales: {
        xAxes: condition ? yAxis : xAxis,
        yAxes: condition ? xAxis : yAxis
    }
}

, , , , condition , .

0

Source: https://habr.com/ru/post/1658777/


All Articles