13 Layouts

IDVW2, Chapter 13 Layouts (d3.stack() only, pp. 264-270)

13.1 Set up data and stack method

Open the JavaScript Console

  // try me in the Console   
    const w = 500;
    const h = 300;

    // original data
    const dataset = [
        { apples: 5, oranges: 10, grapes: 22 },
        { apples: 4, oranges: 12, grapes: 28 },
        { apples: 2, oranges: 19, grapes: 32 },
        { apples: 7, oranges: 23, grapes: 35 },
        { apples: 23, oranges: 17, grapes: 43 }
    ];

    // set up stack method
    const stack = d3.stack()
        .keys([ "apples", "oranges", "grapes" ])
        .order(d3.stackOrderDescending);  
        
    // data, stacked
    const series = stack(dataset);  

Try stack(dataset) in the Console.

13.2 Set up scales

    const xScale = d3.scaleBand()
        .domain(d3.range(dataset.length))
        .range([0, w])
        .paddingInner(0.05);
        
    const yScale = d3.scaleLinear()
        .domain([0, d3.max(dataset, d => d.apples + d.oranges + d.grapes)])
        .range([h, 0]); 
                
    const colors = d3.scaleOrdinal(d3.schemeCategory10);

Enter d3.schemeCategory10 in the Console.

Now try out the colors function. What is the domain?

See built-in color options here. Of course you are not limited to these and can use any appropriate color scheme.

13.3 Add groups

    //Create SVG element
    const svg = d3.select("#stacked")
        .append("svg")
        .attr("width", w)
        .attr("height", h);
    
// Add a group for each row of data
    const groups = svg.selectAll("g")
        .data(series)
                .enter()
                .append("g")
                .style("fill", (d, i) => colors(i));

[There’s a div with id “stacked” here.]

Why doesn’t anything show up yet? Right-click and Inspect to find out.

13.4 Add rectangles

// Add a rect for each data value
    const rects = groups.selectAll("rect")
        .data(d => d)
        .enter()
        .append("rect")
        .attr("x", (d, i) => xScale(i))
        .attr("y", d => yScale(d[1]))
        .attr("height", d => yScale(d[0]) - yScale(d[1]))
        .attr("width", xScale.bandwidth());
                        

13.5 Get the code

Code for download