Redesign of a PEW Research Center chart as a slopegraph.
xxxxxxxxxx
<svg width="320" height="720"></svg>
<script src="https://unpkg.com/d3@4.6.0"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.slope { stroke: #c2c2c4; stroke-width: 0.5; opacity: 0.5 }
.slope.obama { stroke: #00739F; }
.slope.trump { stroke: #A10011; }
circle.obama { fill: #00739F; }
circle.trump { fill: #A10011; }
text.value, text.label { fill: #99a; font-family: Open Sans; font-weight: 300; font-size: 8px; }
.scale { stroke: #c2c2c4; stroke-width: 0.5; stroke-dasharray: 2,3; }
</style>
<script>
var svg = d3.select("svg"),
margin = { top: 20, right: 100, bottom: 20, left: 100 },
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("pew-obama-vs-trump.csv")
.get(function(data) {
var y = d3.scaleLinear()
.range([height,0])
.domain([5,95]); // TODO do properly
// Obama scale
g.append("line")
.attr("class", "scale")
.attr("x1", 0).attr("y1", 0)
.attr("x2", 0).attr("y2", height);
// Trump scale
g.append("line")
.attr("class", "scale")
.attr("x1", width).attr("y1", 0)
.attr("x2", width).attr("y2", height);
// lines
g.selectAll("line.slope")
.data(data)
.enter()
.append("line")
.attr("x1", 0)
.attr("y1", function(d) { return y(d.Obama); })
.attr("x2", width)
.attr("y2", function(d) { return y(d.Trump); })
.attr("class", function(d) { return y(d.Obama) - y(d.Trump) < 0 ? "slope obama" : "slope trump"});
// markers on Obama scale
g.selectAll("circle.obama")
.data(data)
.enter()
.append("circle")
.attr("class", "obama")
.attr("cx", 0)
.attr("cy", function(d) { return y(d.Obama); })
.attr("r", 2);
g.selectAll("text.obama.value")
.data(data)
.enter()
.append("text")
.attr("class", "value obama")
.attr("text-anchor", "end")
.attr("x", -5)
.attr("y", function(d) { return y(d.Obama) + 3; })
.text(function(d) { return d.Obama + "%"; });
g.selectAll("text.obama.label")
.data(data)
.enter()
.append("text")
.attr("class", "label obama")
.attr("text-anchor", "end")
.attr("x", -25)
.attr("y", function(d) { return y(d.Obama) + 3; })
.text(function(d) { return d.Country; });
// markers on Trump scale
g.selectAll("circle.trump")
.data(data)
.enter()
.append("circle")
.attr("class", "trump")
.attr("cx", width)
.attr("cy", function(d) { return y(d.Trump); })
.attr("r", 2);
g.selectAll("text.trump.value")
.data(data)
.enter()
.append("text")
.attr("class", "value trump")
.attr("x", width + 5)
.attr("y", function(d) { return y(d.Trump) + 3; })
.text(function(d) { return d.Trump + "%"; });
g.selectAll("text.trump.label")
.data(data)
.enter()
.append("text")
.attr("class", "label trump")
.attr("x", width + 25)
.attr("y", function(d) { return y(d.Trump) + 3; })
.text(function(d) { return d.Country; });
});
</script>
https://unpkg.com/d3@4.6.0