Search code examples
javascriptd3.jsparallel-coordinates

d3.js Rearranging columns of data for plot


I've been trying for a while but I am unsure of what keyword I need to search for. Anyways, I am interested in changing how the data in d3 is loaded so I can rearrange columns in plots. In R terms, what I am looking for would be about the equivalent of changing factor levels to be able to rearrange columns in a bar plot.

For example, in the link to a block below, I want to manually set which order the parallel coordinates are. Currently, it shows economy, cylinders, to year left to right. I want to do something like year, weight, displacement, etc.

https://bl.ocks.org/jasondavies/1341281


Solution

  • The order of the columns is determined by d3.keys(cars[0]) in this snippet:

    x.domain(dimensions = d3.keys(cars[0]).filter(function(d) {
        return d != "name" && (y[d] = d3.scale.linear()
            .domain(d3.extent(cars, function(p) {
                return +p[d];
            }))
            .range([height, 0]));
    }));
    

    For instance, here is the same code, but using...

    d3.keys(cars[0]).sort()
    

    ... to sort the array alphabetically: https://bl.ocks.org/anonymous/9fb7329fed0e2ea539bab5bc5a47a16c

    So, if you want a specific order, you can simply pass the desired array:

    x.domain(dimensions = ["year", , "weight (lb)", "name", "displacement (cc)", "economy (mpg)", "cylinders", "power (hp)", "0-60 mph (s)"].filter(function(d) {
        return d != "name" && (y[d] = d3.scale.linear()
            .domain(d3.extent(cars, function(p) {
                return +p[d];
            }))
            .range([height, 0]));
    }));
    

    Here is the blocks: https://bl.ocks.org/anonymous/4f1798a5e658df7986f70effa030497c