Skip to content

Instantly share code, notes, and snippets.

@harrisoncramer
Last active November 22, 2017 17:31
Show Gist options
  • Save harrisoncramer/04dcd9742a2be13d99db5f7a7480b4ca to your computer and use it in GitHub Desktop.
Save harrisoncramer/04dcd9742a2be13d99db5f7a7480b4ca to your computer and use it in GitHub Desktop.
Simple Stacked Bar Chart
license: gpl-3.0
<!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>
day titanic avatar akira frozen deliverance avengers
1 20 8 3 0 0 0
2 18 5 1 13 0 0
3 14 3 1 10 0 0
4 7 3 0 5 27 15
5 4 3 0 2 20 14
6 3 1 0 0 10 13
7 2 0 0 0 8 12
8 0 0 0 0 6 11
9 0 0 0 0 3 9
10 0 0 0 0 1 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment