block by curran 3c49f6d1ea969a2f4279dd09844baa38

Bar Chart with Text First Attempt

Full Screen

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Shopping App Prototype</title>
    <script src="https://d3js.org/d3.v4.min.js"></script>
  </head>
  <body>
    <svg width="960" height="500"></svg>
    <script>
      const xValue = d => d.price;
      const yValue = d => d.name;
      const textValue = d => `${d.name} $${d.price}`
      const verticalSpacing = 45;

      const svg = d3.select('svg');
      const width = +svg.attr('width');
      const xScale = d3.scaleLinear().range([0, width]);
      const yScale = d3.scaleBand();

      function render(selection, data){
        xScale.domain([0, d3.max(data, xValue)]);
        yScale
          .domain(data.map(yValue))
          .range([0, verticalSpacing * data.length]);

        const rects = selection.selectAll('rect').data(data)
        rects.exit().remove();
        rects
          .enter().append('rect')
            .attr('x', 0)
            .attr('fill', 'steelblue')
          .merge(rects)
            .attr('y', d => yScale(yValue(d)))
            .attr('width', d => xScale(xValue(d)))
            .attr('height', yScale.bandwidth());

        const text = selection.selectAll('text').data(data)
        text.exit().remove();
        text
          .enter().append('text')
            .style('font-size', '32pt')
            .style('font-family', 'Sans-Serif')
            .attr('x', 250)
            .attr('dy', '0.32em')
          .merge(text)
            .attr('y', d => yScale(yValue(d)) + yScale.bandwidth() / 2)
            .text(textValue);
      }

      render(svg, [ { name: 'Milk', price: 3 } ]);

      setTimeout(() => {
        render(svg, [ { name: 'Milk', price: 3 }, { name: 'Eggs', price: 20 } ]);
      }, 1000);

      setTimeout(() => {
        render(svg, [ { name: 'Milk', price: 3 }, { name: 'Eggs', price: 2 } ]);
      }, 2000);

      setTimeout(() => {
        render(svg, [
          { name: 'Milk', price: 3 },
          { name: 'Eggs', price: 2 },
          { name: 'Cupcakes', price: 5 }
        ]);
      }, 3000);

      setTimeout(() => {
        render(svg, [ { name: 'Milk', price: 3 }, { name: 'Eggs', price: 2 } ]);
      }, 4000);
    </script>
  </body>
</html>