Last active
May 15, 2017 07:23
-
-
Save ggada/6bb0ae71270832b603a845bbb4bb198b to your computer and use it in GitHub Desktop.
D3 tutorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
/*styling*/ | |
.barplot rect { | |
fill: steelblue; | |
} | |
.barplot text { | |
fill: white; | |
font: 10px sans-serif; | |
text-anchor: end; | |
} | |
</style> | |
<body> | |
<svg class="circles" width="720" height="120"> | |
</svg> | |
<br> | |
<svg class="barplot"> | |
</svg> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script> | |
// d3 code | |
const svg = d3.select(".circles"); | |
let data = [32, 57, 293] | |
// 1 - "binds" data to each circle which can be later accessed by function(d) | |
const circle = svg.selectAll("circle") | |
.data(data, function(d) { return d; }); | |
// the "selectAll -> data -> enter -> append" idiom | |
circle.enter() // data join - see https://bost.ocks.org/mike/join/ | |
.append("circle") // appends circle elements as we join on an empty selection | |
.style("fill", "steelblue") | |
.attr("cy", 60) | |
.attr("cx", function(d, i) { return i * 100 + 30; }) // i is optional, returns the index of the element within its selection | |
.attr("r", function(d) { return Math.sqrt(d); }); // d is the data bound in step 1 | |
circle.exit().remove(); | |
// static SVG - https://gist.githubusercontent.com/mbostock/7331260/raw/d78ce2bed6136d963a0b33719e5d7f63ef05b021/index.html | |
data = [4, 8, 15, 16, 23, 42]; | |
const width = 420, barHeight = 20; | |
var x = d3.scaleLinear() | |
.domain([0, d3.max(data)]) | |
.range([0, width]); | |
const chart = d3.select(".barplot") | |
.attr("width", width) | |
.attr("height", barHeight * data.length); | |
var bar = chart.selectAll("g") | |
.data(data) | |
.enter().append("g") | |
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; }); | |
bar.append("rect") | |
.attr("width", x) | |
.attr("height", barHeight - 1); | |
bar.append("text") | |
.attr("x", function(d) { return x(d) - 3; }) | |
.attr("y", barHeight / 2) | |
.attr("dy", ".35em") | |
.text(function(d) { return d; }); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment