Skip to content

Instantly share code, notes, and snippets.

@romsson
Created November 8, 2017 14:17
Show Gist options
  • Save romsson/4a9ecaa288216641e021da8ba5d7199a to your computer and use it in GitHub Desktop.
Save romsson/4a9ecaa288216641e021da8ba5d7199a to your computer and use it in GitHub Desktop.
simple bar chat with interaction
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
rect {
fill: white;
stroke: black;
stroke-width: 1px;
}
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
var data = [22, 32, 21, 23, 10, 22, 11, 19, 30, 50];
var x = d3.scaleLinear().range([0, 500]).domain([0, data.length]);
var y = d3.scaleLinear().range([0, 100]).domain([0, d3.max(data)]);
var g = svg.append("g").attr("transform", "translate(100, 0)");
g.selectAll("text").data(data).enter().append("text")
.text(function(d) { return d; })
.attr("y", 200)
.attr("x", function(d, i) { return x(i) + 20; })
.style("font-size", 12)
.style("text-anchor", "middle")
.style("font-family", "monospace");
g.selectAll("rect").data(data).enter().append("rect")
.attr("x", function(d, i) { return x(i); })
.attr("y", function(d) { return 170 - y(d); })
.attr("height", function(d) { return y(d); })
.attr("width", 500 / data.length - 10 )
.on("mouseover", function(d, i) {
d3.select(this).style("fill", "red");
// Should be using Ids instead of values
d3.selectAll("text").filter(function(e, j) {
return i === j;
})
.style("font-size", 24);
})
.on("mouseout", function(d) {
d3.select(this).transition().duration(500).style("fill", "white");
// Should be using Ids instead of values
d3.selectAll("text").filter(function(e) {
return d === e;
})
.transition().duration(500)
.style("font-size", 12);
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment