Animated stacked bar charts with D3.js

Data

{
"hold":1234,
"paid":2345,
"overdue":0,
"label":"Feb"
}

Design

Size and margins

_chartMargin={left:40, top:25, bottom:45, right:0};
_chartSize.height=320-_chartMargin.top-_chartMargin.bottom;
_chartSize.width=880-_chartMargin.left-_chartMargin.right;
_chartD3=d3.select("svg#chart").append('g').attr("transform", "translate(" + _chartMargin.left + "," + _chartMargin.top + ")");

Scales and Axis

_x=d3.scale.ordinal().domain(d3.range(_data.length))
.rangeRoundBands([0, _chartSize.width],0);


_xAxis = d3.svg.axis()
.scale(_x)
.tickFormat(function(i) {
return _data[i].label;
})
.orient("bottom");
_y=d3.scale.linear().domain([0,d3.max(_data, function(d){ return d.ritardo+d.attesa+d.pagate })])           
.range([_chartSize.height,0])
.nice(5);

_yAxis = d3.svg.axis()
.scale(_y)
.orient("left")
.tickSize(-_chartSize.width)
.ticks(5)

Selections and data binding

//create a placeholder for g.bar
var g=_chartD3.append("g").attr(“class”, “placeholder”);

//join data with selection
var bars=g.selectAll("g.bar") .data(_data);

//create elements if not exists
bars.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d, i) { return "translate(" + (_x(i) + 40) + ","+_chartSize.height+")"; })

Update and animation

// change the y axis
_chartD3.select('y.axis').transition()
.duration(600)
.ease('quad-in-out')
.call(_yAxis);

Consideration and tips

--

--

--

Software engineer. Head of tech @everli

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Massimiliano Pesente

Massimiliano Pesente

Software engineer. Head of tech @everli

More from Medium

Create Sparkline Charts with JavaScript

Visualizing Audio Features of Spotify Tracks using D3.js

Tailwind.css basics

Create Dynamic HTML Tables