Skip to content

Instantly share code, notes, and snippets.

@NPashaP
Last active January 20, 2018 16:52
Show Gist options
  • Save NPashaP/02684b7413012205bd2bf2e90baf1072 to your computer and use it in GitHub Desktop.
Save NPashaP/02684b7413012205bd2bf2e90baf1072 to your computer and use it in GitHub Desktop.
Viz - Bar - stacked - legend - hover
license: gpl-3.0
<!DOCTYPE html>
<head>
<meta charset="utf-8">
</head>
<style>
.viz-bar .bar{
fill: steelblue;
}
.viz-legend:hover{
cursor:pointer;
}
</style>
<body>
<svg width="960" height="600">
<g transform="translate(50,50)" id="bars"></g>
<g transform="translate(300,500)" id="legend"></g>
</svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="http://vizjs.org/viz.v1.3.0.min.js"></script>
<script>
var fill = {"value1":"#342E3A", "value2":"#B1200F", "value3":"#BB6622", "value4":"#BB9944"};
var keys = ["value1","value2","value3","value4"];
var data = Data();
var stack = d3.stack().keys(keys)(data)
var bar = viz.bar()
.key(function(d){ return d.data.key})
.value0(function(d){ return d[0]})
.value1(function(d){ return d[1]})
.valueScale(d3.scaleLinear().domain([0,4]).range([420,0]))
var bars = d3.select("#bars")
.selectAll(".bars")
.data(stack)
.enter()
.append("g")
.attr("class","bars")
.style("fill",function(d,i){ return fill[d.key]})
bars.selectAll(".bar")
.data(function(d){ return bar.data(d).bars(); })
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d){ return d.x;})
.attr("y", function(d){ return d.y;})
.attr("width", function(d){ return d.width;})
.attr("height", function(d){ return d.height;})
var legend = viz.legend()
.data(keys)
.rows(1)
.width(300)
.fill(function(d){ return fill[d]})
.onMouseOver(function(k){ return update(k); })
.onMouseOut(function(k){ return update(); })
d3.select("#legend").call(legend)
function update(k){
if(!arguments.length) stack = d3.stack().keys(keys)(data);
else {
var newdata = data.map(function(d){ return (r = {key:d.key, value1:0, value2:0, value3:0, value4:0}, r[k]=d[k], r); });
stack = d3.stack().keys(keys)(newdata);
}
bars
.data(stack)
.selectAll(".bar")
.data(function(d){ return bar.data(d).bars(); })
.transition().duration(500)
.attr("x", function(d){ return d.x;})
.attr("y", function(d){ return d.y;})
.attr("width", function(d){ return d.width;})
.attr("height", function(d){ return d.height;});
}
function Data(){
return d3.range(20).map(function(i){ return {key:i, value1: Math.random(), value2: Math.random(), value3: Math.random(), value4: Math.random()}; });
}
// adjust the bl.ocks frame dimension.
d3.select(self.frameElement).style("height", "600px");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment