JSFiddle - React, Tailwind, and code Playground

by jtr13

HTML

<h3>Add a circle</h3>

JavaScript

var w = 250;
  var h = 250;
          
// Create SVG          
  var svg = d3.select("body")
    .append("svg")
      .attr("width", w)
      .attr("height", h);

// Create background rectangle          
  svg.append("rect")
      .attr("x", "0")
      .attr("y", "0")
      .attr("width", w)
      .attr("height", h)
      .attr("fill", "aliceblue");

  var dataset = [170, 220, 40, 120, 0, 300];

  var xScale = d3.scaleBand()
      .domain(d3.range(dataset.length))
      .range([0, w]);
      
  var yScale = d3.scaleLinear()
      .domain([0, 300])
      .range([75, 200])
  
  var rad = xScale.bandwidth()/2
  
// Join data  
  var circ = svg.selectAll("circle")
      .data(dataset);

// Create initial circles
  circ.enter().append("circle")
      .attr("cx", (d, i) => xScale(i)+rad)
      .attr("cy", d => yScale(d))
      .attr("r", rad)
      .attr("fill", "blue");

// Trigger update on click
    d3.select("h3")
        .on("click", function () {

// Create new data value        
      var newvalue = Math.floor(Math.random()*300);
        
      dataset.push(newvalue);

      xScale.domain(d3.range(dataset.length));
        
      rad = xScale.bandwidth()/2;
 
// Join data, store update selection      
      circ = svg.selectAll("circle")
          .data(dataset);
    
// Add new circle and store entering circle selection        
      var newcirc = circ.enter().append("circle")
          .attr("cx", "0")
          .attr("cy", "25")
          .attr("r", rad)
          .attr("fill", "red");

// Entering circle transition        
      newcirc    
          .transition()
          .duration(1000)
          .attr("cx", (d, i) => xScale(i)+rad)
          .on("end", function () {
      
// Merge entering circle with existing circles, transition all        
      circ = newcirc.merge(circ)
          .transition()
          .duration(1000)
          .attr("cx", (d, i) => xScale(i)+rad)
          .attr("cy", d => yScale(d))
          .attr("r", rad)
         ...