block by nbremer 47a2cd67b6bcfd7007335e432fa64663

Simple click to change location scatterplot

Full Screen

Built with blockbuilder.org

index.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <style>
    body { text-align: center; }
    svg { margin-top: 50px; }
  </style>
</head>

<body>
  <script>
var dataset = [
    {x: 5,   y: 20}, 
    {x: 480, y: 300}, 
    {x: 250, y: 50}, 
    {x: 100, y: 380}, 
    {x: 330, y: 470},
    {x: 430, y: 150}, 
    {x: 475, y: 90}, 
    {x: 25,  y: 160}, 
    {x: 85,  y: 60}, 
    {x: 220, y: 220}
];

var height = 500;
    
//Create SVG element
var svg = d3.select("body").append("svg")
    .attr("width", 500)
    .attr("height", height);


//Create circles within the SVG
var circs = svg.selectAll("circle")
    .data(dataset)
    .enter().append("circle")
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; })
    .attr("r", 0)
    .style("fill", function(d) { return d3.hsl(d.y * 360 / height, 1, .5) })
    .on("mouseover", function(d){
        d3.select(this)
            .transition("growBig")
            .attr("r", Math.sqrt(d.y)*1.5);
    })
    .on("mouseout", function(d){
        d3.select(this)
            .transition("growSmall").duration(1000)
            .ease(d3.easeBounce)
            .attr("r", Math.sqrt(d.y));
    });
  
//Transition at the start to make the grow
circs
    .transition().duration(800)
    .attr("r", function(d) { return Math.sqrt(d.y); });

//On click, update with new data			
svg.on("click", function() {
    
    //New values for dataset
    dataset.forEach(function(d, i) {
        d.x = Math.floor(Math.random() * 470) + 15; //New random int for the x value
        d.y = Math.floor(Math.random() * 470) + 15; //New random int for the y value
    });
        
    //Update the position and radius of the circles, but not the color
    svg.selectAll("circle")
        .data(dataset)
        .transition("move").duration(1000)
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; })
        .attr("r", function(d) { return Math.sqrt(d.y); })
    		//Optionally you can also change the colors by uncommenting the line below
    	  //.style("fill", function(d) { return d3.hsl(d.y * 360 / height, 1, .5) })	
});

  </script>
</body>