Skip to content

Instantly share code, notes, and snippets.

@lwthatcher
Last active December 14, 2016 22:16
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lwthatcher/5456840f796632c27edc813ce8ab4719 to your computer and use it in GitHub Desktop.
simple polygon and point
license: mit

This is a bare-bones example of drawing polygons and points using D3 v4 while using an axis.

You can represent points in world coordinates, then use d3.scaleLinear() to create the appropriate axis scale transform.

Built with blockbuilder.org

<!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; }
polygon {
fill: CadetBlue
}
</style>
</head>
<body>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear().range([0, 500]);
var y = d3.scaleLinear().range([500, 0]);
x.domain([0, 50]);
y.domain([0, 50]);
var point = {"x": 24, "y": 31}
var poly = [{"x":10, "y":50},
{"x":20,"y":20},
{"x":50,"y":10},
{"x":30,"y":30}];
svg.selectAll("polygon")
.data([poly])
.enter().append("polygon")
.attr("points",function(d) {
return d.map(function(d) {
return [x(d.x),y(d.y)].join(",");
}).join(" ");
});
svg.append("circle")
.attr("r", 4)
.attr("cx", x(point.x))
.attr("cy", y(point.y))
// add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment