0

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • look at line 1: v an p are function arguments – rioV8 Dec 12 '18 at 22:44
  • I can see that they are function arguments but I don't know what they refer to in the context of the broader code. Normally when I see a function I look to see what arguments are passed to the function when the function is called but the function is not really called in the code. "sum" is called but that doesn't have any arguments when called. – Chris_engagingdata Dec 12 '18 at 23:07
  • have you looked at `reduce()`? – rioV8 Dec 12 '18 at 23:27
  • I have looked a little bit at reduce() but I have two issues that I can't quite overcome: 1) the code above has two nested functions with arguments that I don't know) and 2) d3 calls these functions on data that is bound to objects but I don't know how to audit these functions that same way I would with regular javascript. – Chris_engagingdata Dec 13 '18 at 18:55

1 Answers1

0

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}
NtroP
  • 1
  • 3