A basic scatterplot that loads data, scales and axes and updates domains based on extrema. Uses Mike Bostock's margin conventions and the data for Anscombe's Quartet.
forked from kpq's block: Basic starter code for many simple D3 charts
xxxxxxxxxx
<meta charset="utf-8">
<style type="text/css">
body {
font-family: arial, sans;
font-size: 11px;
}
svg {
border: 1px solid #f0f;
}
.axis line,
.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
<body>
</body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript">
var margin = {top: 20, right: 50, bottom: 20, left: 10};
var width = 960 - 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 xScale = d3.scaleLinear()
.range([0,width]);
var yScale = d3.scaleLinear()
.range([height,0]);
var xAxis = d3.axisBottom()
.scale(xScale);
var yAxis = d3.axisRight()
.scale(yScale);
d3.tsv("quartet.tsv", ready);
function ready(error, data) {
if (error) return console.warn(error);
data.forEach(function(d) {
d.xPos = +d.xPos;
d.yPos = +d.yPos;
});
//update domains based on extrema, which has pluses and minuses
xScale.domain(d3.extent(data, function(d) { return d.xPos; }));
yScale.domain(d3.extent(data, function(d) { return d.yPos; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + width + ",0)")
.call(yAxis);
var circleGroup = svg.selectAll(".circle-group")
.data(data).enter().append("g")
.attr("class", "circle-group")
.attr("transform", function(d) { return "translate(" + xScale(d.xPos) + "," + yScale(d.yPos) + ")"; });
circleGroup.append("circle")
.attr("r", 5);
circleGroup.append("text")
.text(function(d) { return d.xPos + "," + d.yPos; })
.attr("dx", 5)
.attr("dy", -5);
}
</script>
https://d3js.org/d3.v4.min.js