Skip to content

Instantly share code, notes, and snippets.

@owlfox
Last active October 7, 2019 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owlfox/7a5b11050b3be12f8d322efa112b21d5 to your computer and use it in GitHub Desktop.
Save owlfox/7a5b11050b3be12f8d322efa112b21d5 to your computer and use it in GitHub Desktop.
example 3.1 of d3 for the impatient
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<div>
<svg
id="key"
width="300"
height="155"
style="background: lightgrey"
></svg>
<svg
id="key2"
width="300"
height="155"
style="background: lightgrey"
></svg>
</div>
</body>
<script>
window.addEventListener("load", makeKeys);
function makeKeys() {
const ds1 = [["Mary", 1], ["Jane", 4], ["Anne", 2]]; //<1>
const ds2 = [["Anne", 5], ["Jane", 3]]; //<2>
const scX = d3 //<3>
.scaleLinear()
.domain([0, 6])
.range([50, 300]),
scY = d3
.scaleLinear()
.domain([0, 3])
.range([50, 150]);
const svg = d3.select("#key"); //<4>
const svg2 = d3.select("#key2");
const drawAxis = svg => {
let j = -1;
svg
.selectAll("text") //<5>
.data(ds1)
.enter()
.append("text")
.attr("x", 20)
.attr("y", d => scY(++j))
.text(d => d[0]);
};
drawAxis(svg);
drawAxis(svg2);
const drawData = svg => {
let k = -1;
svg
.selectAll("circle")
.data(ds1)
.enter()
.append("circle") //<6>
.attr("r", 5)
.attr("fill", "red")
.attr("cx", d => scX(d[1]))
.attr("cy", d => scY(++k) - 5);
};
drawData(svg);
drawData(svg2);
svg.on("click", ()=>{
const cs = svg.selectAll("circle").data(ds2, d => d[0]); //<7>
cs.transition()
.duration(1000)
.attr("cx", d => scX(d[1])); //<8>
cs.exit().attr("fill", "blue"); //<9>
});
svg2.on("click", ()=>{
const cs = svg2.selectAll("circle").data(ds2); //<10>
cs.transition()
.duration(1000)
.attr("cx", d => scX(d[1]));
cs.exit().attr("fill", "green");
});
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment