Naive grouping of an ordinal scale
In response to: http://stackoverflow.com/questions/25913528/add-second-x-axis-to-scatterplot-to-display-group-information
Naive grouping of an ordinal scale
In response to: http://stackoverflow.com/questions/25913528/add-second-x-axis-to-scatterplot-to-display-group-information
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<style> | |
text { | |
font: 12px sans-serif; | |
} | |
.axis path, .axis line { | |
fill: none; | |
stroke: #000; | |
shape-rendering: crispEdges; | |
} | |
circle.point { | |
fill: steelblue; | |
stroke: black; | |
} | |
</style> | |
<script> | |
var margin = {top: 10, right: 10, bottom: 30, left: 30}, | |
width = 500 - margin.left - margin.right, | |
height = 300 - margin.top - margin.bottom; | |
var chartData = [ | |
{name: "AB", group: "A", number: 0.5}, | |
{name: "ABC", group: "A", number: 10.0}, | |
{name: "BC", group: "B", number: 3.0}, | |
{name: "BCD", group: "B", number: 5.0}, | |
{name: "BCDE", group: "B", number: 0.3}, | |
{name: "CD", group: "C", number: 1.6}, | |
{name: "DE", group: "D", number: 1.5} | |
]; | |
var lkUp = {}; | |
chartData.forEach(function(d) { lkUp[d.name] = {group: d.group}; }); | |
var x = d3.scale.ordinal() | |
.domain(chartData.map(function(d) { return d.name; })) | |
.rangePoints([0, width]), | |
y = d3.scale.linear() | |
.domain([0, d3.max(chartData, function(d) { return d.number; })]) | |
.range([height, 0]), | |
xAxis = d3.svg.axis() | |
.scale(x) | |
.tickFormat(function(d) { return lkUp[d].group; }) | |
.orient("bottom"), | |
yAxis = d3.svg.axis() | |
.scale(y) | |
.orient("left"); | |
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 + ")"); | |
svg.selectAll("circle.point") | |
.data(chartData) | |
.enter().append("circle") | |
.attr({ | |
"class": "point", | |
cx: function(d) { return x(d.name); }, | |
cy: function(d) { return y(d.number); }, | |
r: 5 | |
}); | |
svg.append("g") | |
.attr("class", "x axis") | |
.attr("transform", "translate(0," + height + ")") | |
.call(xAxis); | |
svg.append("g") | |
.attr("class", "y axis") | |
.call(yAxis); | |
</script> | |