Animated Bar Chart with D3

Learn how to create an interactive animated bar chart with D3.js, complete with smooth transitions and hover effects. Enhance your data visualizations by incorporating dynamic animations and displaying values on mouse events.



Enhance your bar chart visualization by adding transitions on mouse events. Let's add some event handling on hover of the individual bars and display values.

Example: Animated Bar Chart

HTML

<!doctype html>
<html>
<head>
<style>
.bar {
    fill: steelblue;
}
.highlight {
    fill: orange;
}
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<svg width="600" height="500"></svg>
<script>
var svg = d3.select("svg"),
    margin = 200,
    width = svg.attr("width") - margin,
    height = svg.attr("height") - margin;

svg.append("text")
    .attr("transform", "translate(100,0)")
    .attr("x", 50)
    .attr("y", 50)
    .attr("font-size", "24px")
    .text("XYZ Foods Stock Price");

var x = d3.scaleBand().range([0, width]).padding(0.4),
    y = d3.scaleLinear().range([height, 0]);

var g = svg.append("g")
        .attr("transform", "translate(" + 100 + "," + 100 + ")");

d3.csv("xyz.csv", function(error, data) {
    if (error) {
        throw error;
    }

    x.domain(data.map(function(d) { return d.year; }));
    y.domain([0, d3.max(data, function(d) { return d.value; })]);

    g.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x))
      .append("text")
      .attr("y", height - 250)
      .attr("x", width - 100)
      .attr("text-anchor", "end")
      .attr("stroke", "black")
      .text("Year");

    g.append("g")
      .call(d3.axisLeft(y).tickFormat(function(d){
          return "$" + d;
      }).ticks(10))
      .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", "-5.1em")
      .attr("text-anchor", "end")
      .attr("stroke", "black")
      .text("Stock Price");

    g.selectAll(".bar")
      .data(data)
      .enter().append("rect")
      .attr("class", "bar")
      .on("mouseover", onMouseOver)
      .on("mouseout", onMouseOut)
      .attr("x", function(d) { return x(d.year); })
      .attr("y", function(d) { return y(d.value); })
      .attr("width", x.bandwidth())
      .transition()
      .ease(d3.easeLinear)
      .duration(400)
      .delay(function (d, i) {
          return i * 50;
      })
      .attr("height", function(d) { return height - y(d.value); });
});

function onMouseOver(d, i) {
    d3.select(this).attr('class', 'highlight');
    d3.select(this)
      .transition()
      .duration(400)
      .attr('width', x.bandwidth() + 5)
      .attr("y", function(d) { return y(d.value) - 10; })
      .attr("height", function(d) { return height - y(d.value) + 10; });

    g.append("text")
      .attr('class', 'val')
      .attr('x', function() { return x(d.year); })
      .attr('y', function() { return y(d.value) - 15; })
      .text(function() { return '$' + d.value; });
}

function onMouseOut(d, i) {
    d3.select(this).attr('class', 'bar');
    d3.select(this)
      .transition()
      .duration(400)
      .attr('width', x.bandwidth())
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); });

    d3.selectAll('.val').remove();
}
</script>
</body>
</html>

Explanation: Event Handlers

mouseover Event:

The onMouseOver function changes the bar color to orange, increases the bar width and height with a transition duration of 400 milliseconds, and adds a text element displaying the value.

JavaScript

function onMouseOver(d, i) {
d3.select(this).attr('class', 'highlight');
d3.select(this)
.transition()
.duration(400)
.attr('width', x.bandwidth() + 5)
.attr("y", function(d) { return y(d.value) - 10; })
.attr("height", function(d) { return height - y(d.value) + 10; });

g.append("text")
.attr('class', 'val')
.attr('x', function() { return x(d.year); })
.attr('y', function() { return y(d.value) - 15; })
.text(function() { return '$' + d.value; });
}

mouseout Event:

The onMouseOut function reverts the bar color to the original, restores the original width, height, and y value of the bar, and removes the text value.

JavaScript

function onMouseOut(d, i) {
d3.select(this).attr('class', 'bar');
d3.select(this)
.transition()
.duration(400)
.attr('width', x.bandwidth())
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); });

d3.selectAll('.val').remove();
}

These event handlers add dynamic behavior to the bar chart, making it interactive and visually engaging.