raceBarChart = results => {
const data = results['candidates'].sort(function(a, b) {
return d3.descending(a.percent, b.percent)
});
const margin = ({top: 120, right: 15, bottom: 50, left: 100});
let width = 600;
let height = Math.ceil((data.length + 0.1) * barHeight) + margin.top + margin.bottom;
const svg = d3.create('svg')
.attr("viewBox", [0, 0, width, height])
let x = d3.scaleLinear()
.domain([0, 1])
.range([margin.left, width - margin.right])
let y = d3.scaleBand()
.domain(d3.range(data.length))
.rangeRound([margin.top, height - margin.bottom])
.padding(0.1);
let format = x.tickFormat();
let xAxis = g => g
.attr("transform", `translate(0,${Math.ceil((data.length + 0.1) * barHeight) + margin.top})`)
.call(d3.axisBottom(x).ticks(4).tickFormat(d => d3.format(".0%")(d)))
.call(g => g.select(".domain").remove())
.attr("color", "grey");
let yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).tickFormat(i => data[i].name)
.tickSizeOuter(0))
.attr("font-size", "1em")
svg.append("g")
.selectAll("rect")
.data(data)
.join("rect")
.attr("fill", d => d.color)
.attr("x", x(0))
.attr("y", (d, i) => y(i))
.attr("width", d => x(d.percent) - x(0))
.attr("height", y.bandwidth());
svg.append("g")
.attr("fill", "white")
.attr("text-anchor", "end")
.attr("font-family", "sans-serif")
.attr("font-weight", "bold")
.attr("font-size", "16px")
.selectAll("text")
.data(data)
.join("text")
.attr("x", d => x(d.percent))
.attr("y", (d, i) => y(i) + y.bandwidth() / 2)
.attr("dy", "0.35em")
.attr("dx", -10)
.attr("font-size", "16px")
.text(d => `${d3.format(".2%")(d.percent)} (${d3.format(",")(d.votes)} ballots)`)
.call(text => text.filter(d => d.percent < 50) // short bars
.attr("dx", +10)
.attr("fill", "black")
.attr("text-anchor", "start"));
svg.append("g")
.call(xAxis);
const axis = svg.append("g")
.call(yAxis)
const title = svg.append("text")
.attr("class", "info")
.attr("x", 5)
.attr("y", 25)
.attr("text-anchor", "start")
.style("font-size", "30px")
.style("font-family", "PT Sans")
.style("font-weight", "bold")
.text(results.race_title)
let offset = 5;
if(results.description) {
svg.append("text")
.attr("class", "info")
.attr("x", 5)
.attr("y", 50)
.attr("text-anchor", "start")
.style("font-size", "16px")
.style("font-family", "PT Sans")
.style("font-weight", "bold")
.text(results.description);
offset = 30;
}
svg.append("text")
.attr("class", "info")
.attr("x", 5)
.attr("y", 50 + offset)
.attr("text-anchor", "start")
.style("font-size", "16px")
.style("font-family", "PT Sans")
.text(getUpdateText(results));
svg.append("text")
.attr("x", 5)
.attr("y", 70 + offset)
.attr("text-anchor", "start")
.style("font-size", "16px")
.style("font-family", "PT Sans")
.text(`Source: ${results.source}`);
setTimeout(()=>{
axis.selectAll(".tick text")
.call(wrap, margin.left-10);
}, 0);
return svg.node();
}