xxxxxxxxxx
<meta charset="utf-8">
<style>
svg {
overflow: visible;
}
body {
padding: 40px;
}
.bar--positive {
fill: steelblue;
color: steelblue;
font-weight: bold;
}
.bar--negative {
fill: darkorange;
color: darkorange;
font-weight: bold;
}
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
table {
border-collapse: collapse;
}
td {
border-bottom: 1px solid #d3d3d3;
padding: 5px;
}
thead th, .info th {
font-size: 1.2em;
padding-bottom: 20px;
}
.info {
border-bottom: 1px solid #b7b7b7;
}
.info svg {
height: 20px;
font-size: 0.8em;
font-weight: 100
}
line.middle {
stroke: black;
}
line.ldiv {
stroke: #dddddd;
stroke-width: 1px;
}
body {
font-family:Arial,Helvetica;
}
</style>
<body>
<table></table>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {right: 30, left: 30},
width = 400 - margin.left - margin.right,
height = 20;
var x = d3.scale.linear()
.range([0, width]);
var table = d3.select("table");
// header 1
var headRow = table.append("thead").append("tr");
headRow.append("th");
headRow.append("th").html("Margin");
headRow.append("th");
// header 2
var infoRow = table.append("tr")
infoRow.append("th").classed("info", true).html("Location");
var limits = infoRow.append("th").classed("info", true).append("svg");
infoRow.append("th").classed("info", true).html("Result");
d3.tsv("data.tsv", function(error, data) {
x.domain([-100, 100]);
[-50, -25, 0, 25, 50].forEach(function(d) {
limits.append("text")
.classed("info", true)
.attr("x", x(d) - (d === 0 ? 23 : 35))
.text(function() {
var sign = d === 0 ? '' : '+';
return sign + Math.abs(d);
});
});
var tr = table.selectAll(".bar")
.data(data)
.enter()
.append("tr");
// add name
tr.append("td").html(function(d) { return d.name });
// add graph
var svg = tr.append("td").append("svg").attr("width", width).attr("height", height);
svg
.append("rect")
.attr("class", function(d) { return "bar bar--" + (d.value < 0 ? "negative" : "positive"); })
.attr("x", function(d) { return x(Math.min(0, d.value)); })
.attr("y", 0)
.attr("width", function(d) { return Math.abs(x(d.value) - x(0)); })
.attr("height", 20);
svg
.append("line")
.classed("middle", true)
.attr({
x1: x(0),
x2: x(0),
y1: -20,
y2: height + 20
});
[-50, -25, 25, 50].forEach(function(d) {
svg
.append("line")
.classed("ldiv", true)
.attr({
x1: x(d),
x2: x(d),
y1: -20,
y2: height + 5
});
});
// add result
tr.append("td")
.attr("class", function(d) { return "bar bar--" + (d.value < 0 ? "negative" : "positive"); })
.html(function(d) {
var name = d.value < 0 ? "Humpty": "Dumpty";
return name + " +" + Math.abs(d.value);
});
})
</script>
https://d3js.org/d3.v3.min.js