Skip to content

Instantly share code, notes, and snippets.

@jtr13
Last active December 11, 2019 19:28
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 jtr13/98bbc5b0d5fb6b5c07ec46e2bef9b706 to your computer and use it in GitHub Desktop.
Save jtr13/98bbc5b0d5fb6b5c07ec46e2bef9b706 to your computer and use it in GitHub Desktop.
d3.json
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
const w = 525;
const h = 400;
const svg = d3.select("body").append("svg").attr("width", w).attr("height", h);
const xScale = d3.scaleLinear().domain([0,1]).range([0,w-60]);
const yScale = d3.scaleLinear().domain([0,1]).range([h,0]);
const colors = d3.scaleOrdinal(d3.schemeTableau10);
d3.json("https://data.ct.gov/resource/y6p2-px98.json?category=Fruit").then(function (data) {
console.log(data);
xScale.domain([d3.min(data.map(d => d.location_1.coordinates[0])),
d3.max(data.map(d => d.location_1.coordinates[0]))]);
yScale.domain([d3.min(data.map(d => d.location_1.coordinates[1])),
d3.max(data.map(d => d.location_1.coordinates[1]))]);
svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", d => xScale(d.location_1.coordinates[0]))
.attr("cy", d => yScale(d.location_1.coordinates[1]))
.attr("r", "3")
.attr("fill", d => colors(d.item))
.on("mouseover", function(d) { // IDVW2, p. 270
var xPos = +d3.select(this).attr("cx");
var yPos = +d3.select(this).attr("cy");
d3.select(this).style("cursor", "pointer");
svg.append("text")
.attr("id", "tooltip")
.attr("x", function() {
if(xPos < w/2) {
return xPos + 10
} else {
return xPos - 10
}
})
.attr("y", yPos)
.attr("font-size", "11px")
.attr("text-anchor", function() {
if(xPos < w/2) {
return "start"
} else {
return "end"
}
})
.attr("alignment-baseline", "middle")
.text(d.item); // not a function (already in one)
})
.on("mouseout", function() {
d3.select("#tooltip").remove();
});
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment