horizontalBar = (data, options = {}) => {
const {
bar_color = 'steelblue',
chart_width = 600,
chart_height = 400,
margin = { top: 20, right: 20, bottom: 20, left: 100 },
format = ""
} = options;
const svg = d3
.create("svg")
.attr("viewBox", [0, 0, chart_width, chart_height]);
const x = d3
.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([margin.left, chart_width - margin.right]);
const xAxis = g =>
g
.attr("transform", `translate(0,${margin.top})`)
.call(d3.axisTop(x).ticks(chart_width / 80, format))
.call(g => g.select(".domain").remove());
const y = d3
.scaleBand()
.domain(d3.range(data.length))
.rangeRound([margin.top, chart_height - margin.bottom])
.padding(0.1);
const yAxis = g =>
g.attr("transform", `translate(${margin.left},0)`).call(
d3
.axisLeft(y)
.tickFormat(i => data[i].name)
.tickSizeOuter(0)
);
svg
.append("g")
.attr("fill", bar_color)
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", x(0))
.attr("y", (d, i) => y(i))
.attr("width", d => x(d.value) - x(0))
.attr("height", y.bandwidth());
svg
.append("g")
.attr("fill", "white")
.attr("text-anchor", "end")
.attr("font-family", "sans-serif")
.attr("font-size", 12)
.selectAll("text")
.data(data)
.join("text")
.attr("x", d => x(d.value))
.attr("y", (d, i) => y(i) + y.bandwidth() / 2)
.attr("dy", "0.35em")
.attr("dx", -4)
.text(d => d.value)
.call(text =>
text
.filter(d => x(d.value) - x(0) < 20)
.attr("dx", +4)
.attr("fill", "black")
.attr("text-anchor", "start")
);
svg.append("g").call(xAxis);
svg.append("g").call(yAxis);
return svg.node();
}