xxxxxxxxxx
<meta charset="utf-8">
<style>
.grid {
stroke-width: 0.5px;
stroke: steelblue;
fill: none;
opacity: 0.5;
}
.axis {
stroke-width: 3px;
stroke: black;
fill: none;
}
g.item circle {
fill: black;
stroke: none;
}
svg {
border: 1px solid #ccc;
}
text {
font: 12px sans-serif;
}
</style>
<body>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
//Options
var width = 480,
height = 480,
dotRadius = 4,
gridSpacing = 10;
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height);
//Scales for item positions
var x = d3.scale.linear().domain([-10,10]).range([0,width]);
var y = d3.scale.linear().domain([-10,10]).range([height,0]);
//gridlines
svg.append("path")
.attr("class","grid")
.attr("d",function() {
var d = "";
for (var i = gridSpacing; i < width; i += gridSpacing ) {
d += "M"+i+",0 L"+i+","+height;
}
for (var i = gridSpacing; i < height; i += gridSpacing ) {
d += "M0,"+i+" L"+width+","+i;
}
return d;
})
//x axis
svg.append("path")
.attr("class","axis")
.attr("d","M0,"+height/2+" L"+width+","+height/2);
//y axis
svg.append("path")
.attr("class","axis")
.attr("d","M"+width/2+",0 L"+width/2+","+height);
//Data - x and y can be anything positive or negative
//Domains for scales need to be wide enough.
//Currently -10 to +10
var itemList = [
{
x: 5,
y: 5,
description: "I'm in the upper-right quadrant!"
},
{
x: -5,
y: -5,
description: "I'm in the lower-left quadrant!"
}
];
//One group per item
var items = svg.selectAll("g.item").data(itemList).enter().append("g")
.attr("class","item");
//Add a dot
items.append("circle")
.attr("r",dotRadius)
.attr("cx",function(d){
return x(d.x);
})
.attr("cy",function(d){
return y(d.y);
});
//Add a label
//would need to use .getBBox() to make sure this doesn't hit the sides
items.append("text")
.attr("x",function(d){
return x(d.x);
})
.attr("y",function(d){
return y(d.y);
})
.attr("dy","1.25em")
.attr("text-anchor","middle")
.text(function(d){return d.description;});
</script>
Modified http://d3js.org/d3.v3.min.js to a secure url
https://d3js.org/d3.v3.min.js