Trying to understanding code example for marimekko graph

232 Views Asked by At

I'm going through Mike Bostock's code for the marimekko graph, shown here: https://bl.ocks.org/mbostock/1005090

I have a couple of questions about code segments that I don't understand:

var sum = segments.reduce(function(v, p) {
  return (p.offset = v) + (p.sum = p.values.reduceRight(function(v, d) {
    d.parent = p;
    return (d.offset = v) + d.value;
 }, 0));
}, 0);

This one, I gather is related to calculating the translation of the bars, but I really don't understand what it is calculating or doing. What are v and p? I know what d and i are as function arguments, but haven't seen v and p.

How would I go about changing the x-axis tick labels to not be percentages but rather to be the absolute value of the sum of the segment?
I think I need to update the x function to change the domain of the value to be equal to the sum of the markets within the segment but each market is different so I can just do a max on the data like I've seen in examples.

1

There are 1 best solutions below

0
On

The v is the previous (v)alue that's passed in for each iteration over the array of data to generate the overall sum. The p is the (p)arent (as seen by the inner reduceRight function.)

The purpose of the the overall reduction is to determine a single (total) summed value to divide the per-market segments' offset by to position the per-market segment on the x-axis. It also returns per-segment sums p.sum (in the parent) to determine the y-offset for each segment.

The data is transformed into something like this:

key: "Almond lovers"

offset: 0

sum: 6400

values: Array (4)
0 {market: "Auburn, AL", segment: "Almond lovers", value: 3840, parent: Object, offset: 2560}
1 {market: "Birmingham, AL", segment: "Almond lovers", value: 1600, parent: Object, offset: 960}
2 {market: "Gainesville, FL", segment: "Almond lovers", value: 640, parent: Object, offset: 320}
3 {market: "Durham, NC", segment: "Almond lovers", value: 320, parent: Object, offset: 0}