block by fogonwater 6bd6401a39d4aefadcb1

D3 bar chart tests

Full Screen

Just mucking about with D3. Trying to remember how it works.

index.html

<!DOCTYPE html>
<html lang="eng">
  <head>
    <meta charset="UTF-8">
    <style>
      body {text-align:center}
      svg { font-family: Courier;}
    </style>
    <title>Labelled Bar Chart</title>
    <script src="https://d3js.org/d3.v5.js"></script>
  </head>
  <body>
    <svg width=600 height=500>
    	<text class="title" x=0 y=30>This example is overly complicated. Simplify with scales.</text>
    </svg>
    <script type="text/javascript">
    console.clear()
    
    var data = [],
        num_elements = 20,
        max_value = 30
    
     // Generate some data
    for (var i = 0; i < num_elements; i++) {
        var newNum = Math.ceil( Math.random() * max_value );
        data.push(newNum);
    }

    const svg = d3.select("svg"),
  		width = +svg.attr("width"),
  		height = +svg.attr("height"),
      margin= 20
      barPadding = 1,
      barSpan = width / data.length
    
    y = d3.scaleLinear()
				.range([height-margin, margin])
    		.domain([0, max_value])

    svg.selectAll("rect")
        .data(data)
        .enter()
        .append("rect")
        .attr("x", (d, i) => i * barSpan)
        .attr("y", d => height - y(d))
        //.attr("y", d => height - (d * 4))
        .attr("width", barSpan - barPadding)
        .attr("height", d => y(d))
        .attr("fill", d => d == Math.max.apply(Math, data) ? "crimson" : '#B0A6A4');

    svg.selectAll("text")
        .data(data)
        .enter()
        .append("text")
        .text(d => d > 4 ? d : '')
        .attr("x", (d, i) => 
              i * (width / data.length) + (width / data.length - barPadding) / 2
        )
        .attr("y", d => height - (d * 4) + 14)
        .attr("font-family", "sans-serif")
        .attr("font-size", "11px")
        .attr("fill", "white")
        .attr("text-anchor", "middle");

    </script>
  </body>
</html>