d3 stack - can I get transposed output

Hi!

If I use stack from d3-shape example I get structure like this:

[
  [[   0, 3840], [   0, 1600], [   0,  640], [   0,  320]], // apples
  [[3840, 5760], [1600, 3040], [ 640, 1600], [ 320,  800]], // bananas
  [[5760, 6720], [3040, 4000], [1600, 2240], [ 800, 1440]], // cherries
  [[6720, 7120], [4000, 4400], [2240, 2640], [1440, 1840]], // dates
]

But I’m more interested in transposed result. I want to get series of stacked bars, like this:

[
  [
    [   0, 3840], // first apples
    [3840, 5760], // first bananas
    [5760, 6720], // first cherries
    [6720, 7120], // first dates
  ], [
    [   0, 1600], // second apples
    [1600, 3040], // second bananas
    [3040, 4000], // second cherries
    [4000, 4400], // second dates
  ], [
    [   0,  640], // third apples
    [ 640, 1600], // third bananas
    [1600, 2240], // third cherries
    [2240, 2640], // third dates
  ], [
    [   0,  320] // fourth apples
    [ 320,  800], // fourth bananas
    [ 800, 1440], // fourth cherries
    [1440, 1840], // fourth dates
]

I know I can use something like transpose from nanoutils but I’m wondering if I can achieve same result tinkering with stack methods

Even better if I could still get rest of data - in this case month field. Just like with treemap layout, which creates data property for each node.

hi @solificati if you’re using d3 you can take advantage of the transpose function from d3-array

here are some examples

1 Like