D3ScatterplotChangeVar
by Simon Raper
CSS
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
JavaScript
//Add data
var dataset = [
[1, 3],
[3, 12],
[6, 4],
[11, 1],
[7, 7],
[2, 3]
];
//Set constants
var w = 420,
h = 400,
padding=30;
//Create adaptable scales
var xScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d3.max([d[0], d[1]]); })])
.range([padding, w-padding]);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d3.max([d[0], d[1]]); })])
.range([h-padding, padding]);
//Set up the svg
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Add in circles for each data point
svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function (d) {
return xScale(d[0]);
})
.attr("cy", function (d) {
return yScale(d[1]);
})
.attr("r", 5)
//Swap the axes
d3.selectAll("circle")
.transition()
.duration(1000)
.attr("cx",function (d) {
return xScale(d[1]);
})
.attr("cy",function (d) {
return yScale(d[0]);
});
//Set up the axes
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);