D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
harrisoncramer
Full window
Github gist
Simple Stacked Bar Chart
<!doctype html> <html> <head> <title>D3 in Action Examples</title> <meta charset="utf-8" /> <script src="https://d3js.org/d3.v4.min.js"></script> </head> <body> </body> <script> function steamgraph(){ d3.csv("movies.csv", data =>{ d3.select("body").append("svg").attr("width", 550).attr("height", 500) var xScale = d3.scaleLinear().domain([0,10]).range([20,480]) // Notice that the yScale is not inverted on the yScale var yScale = d3.scaleLinear().domain([0,60]).range([480,20]) // We create a heightscale where the y is inverted! var heightScale = d3.scaleLinear().domain([0,60]).range([20, 480]) var movies = ["titanic","avatar","akira","frozen","deliverance","avengers"] var colorScale = d3.scaleOrdinal().domain(movies).range(["#fcd88a", "#cf7c1c", "#93c464", "#75734F", "#5eafc6", "#41a368"]) console.log(data) yAxis = d3.axisLeft().scale(yScale) .tickSize(-500) d3.select("svg").append("g") .attr("class", "yAxis") .call(yAxis) .attr("transform",`translate(${20}, 0)`) xAxis = d3.axisBottom().scale(xScale) .tickSize(-500) d3.select("svg").append("g") .attr("class", "xAxis") .call(xAxis) .attr("transform",`translate(0, ${480})`) d3.select("g.xAxis").selectAll("g.tick").selectAll("text") d3.select("g.xAxis").selectAll("g.tick").selectAll("line") var stackLayout = d3.stack() .keys(movies) d3.select("svg").selectAll("g.bar") .data(stackLayout(data)) // Pass the sorted data in .enter() .append("g") .attr("class", "bar") .each(function(d) { d3.select(this).selectAll("rect") .data(d) .enter() .append("rect") .attr("width", 40) .attr("height", p => heightScale(p[1]) - heightScale(p[0])) .attr("x", (p, i) => xScale(i) + 25) .attr("y", p => yScale(p[1])) .style("fill", colorScale(d.key)) }) }); } steamgraph(); </script> </html>
https://d3js.org/d3.v4.min.js