animated bar chart d3 d3js


Here is an example of an animated bar chart using D3.js:

// Define the dimensions of the chart
var margin = { top: 20, right: 20, bottom: 30, left: 40 },
    width = 600 - margin.left - margin.right,
    height = 300 - - margin.bottom;

// Create the SVG object and set its dimensions
var svg ="body")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + + margin.bottom)
    .attr("transform", "translate(" + margin.left + "," + + ")");

// Define the data for the chart
var data = [
  {name: "Apples", value: 10},
  {name: "Bananas", value: 20},
  {name: "Oranges", value: 15},
  {name: "Grapes", value: 5},
  {name: "Pineapples", value: 25}

// Set up the x-scale
var xScale = d3.scaleBand()
    .range([0, width])
    .domain( { return; }));

// Set up the y-scale
var yScale = d3.scaleLinear()
    .range([height, 0])
    .domain([0, d3.max(data, function(d) { return d.value; })]);

// Add the x-axis to the chart
    .attr("transform", "translate(0," + height + ")")

// Add the y-axis to the chart

// Add the bars to the chart
var bars = svg.selectAll(".bar")
    .attr("class", "bar")
    .attr("x", function(d) { return xScale(; })
    .attr("width", xScale.bandwidth())
    .attr("y", height)
    .attr("height", 0);

// Animate the bars
  .attr("y", function(d) { return yScale(d.value); })
  .attr("height", function(d) { return height - yScale(d.value); });

In this example, we define the dimensions of the chart and create an SVG object to contain it. We then define an array of data for the chart, with each object representing a single bar.

Next, we define the x-scale and y-scale for the chart using the d3.scaleBand() and d3.scaleLinear() functions, respectively. We then add the x-axis and y-axis to the chart using the d3.axisBottom() and d3.axisLeft() functions, respectively.

To animate the bars, we first create the rect elements for each bar using the svg.selectAll(".bar").data(data).enter().append("rect") code block. We set the initial position of the bars off the bottom of the chart by setting the y attribute to height and the height attribute to 0.

Finally, we use the .transition() and .duration() methods to animate the bars by setting their y and height attributes based on the data values.