block by nbremer da7c187aee6c26981e33d9d8e3c1d3a9

Simple animated bar chart

Full Screen

Built with blockbuilder.org

index.html

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

<body>
  <script>
var dataset = [ 5, 10, 4, 7, 8, 12, 15, 3, 16, 18, 7, 19, 14, 7 ];
var totalHeight = 100;

var yScale = d3.scaleLinear()
    .domain([0, d3.max(dataset)])
    .range([0, totalHeight]);

var colorScale = d3.scaleLinear()
    .domain([0, d3.max(dataset)/2, d3.max(dataset)])
    .range(["#e89f84", "#BF4E24", "#6c2c14"]);
    
var svg = d3.select("body").append("svg")
		.attr("width", 300)
    .attr("height", 400);

var bars = svg.selectAll(".bars")
    .data(dataset)
    .enter().append("rect")
    .attr("class", "bars")
    .attr("width", 15)
    .attr("height", 0)
    .attr("x", function(d,i) { return i*20; })
    .attr("y", totalHeight)
    .style("fill", function(d) { return colorScale(d); });

bars.on("mouseover", function(d) {
        d3.select(this)
            .style("fill", "#D3D3D3");
    })
    .on("mouseout", function(d) {
        d3.select(this)
            .transition().duration(600)
            .style("fill", function(d) { return colorScale(d); });
    });
    
bars.transition().duration(500)
    .delay(function(d,i) { return i*200; })
    .attr("y", function(d) { return totalHeight - yScale(d); })
    .attr("height", function(d) { return yScale(d); });

  </script>
</body>