JSFiddle - React, Tailwind, and code Playground
by cwhong
HTML
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="chart" />
CSS
#chart {
width: 320px;
background:lightgray;
}
JavaScript
const data = [
{"range":"<10K","count":320,"i":0},
{"range":"10K-100K","count":1091,"i":1},
{"range":"100K-1M","count":2291,"i":2},
{"range":"10M-100M","count":458,"i":3},
{"range":">100M","count":1836,"i":4}
]
const margin = {
top:20,
right: 0,
bottom: 20,
left: 0,
};
const width = 320 - margin.left - margin.right;
const height = 150 - margin.top - margin.bottom;
console.log(height)
// create an svg container
const chart = d3.select('#chart')
.append('svg:svg')
.attr('width', '100%')
.attr('height', height + margin.top + margin.bottom);
const x = d3.scaleBand()
.domain(data.map(d => d.range))
.rangeRound([0, width])
.paddingInner(0.25)
.paddingOuter(0.25);
const y = d3.scaleLinear()
.domain([0, d3.max(data, d => parseInt(d.count))])
.range([height , 0 + margin.top]);
const bar = chart.selectAll('g')
.data(data)
.enter()
.append('g')
.attr('transform', (d, i) => `translate(${x(d.range)},0)`);
bar.append('rect')
.attr('y', d => y(d.count))
.attr('height', d => (height + margin.top) - y(d.count))
.attr('width', x.bandwidth())
.attr('fill', 'steelblue');
// bar labels
bar.append('text')
.attr('x', x.bandwidth()/2)
.attr('y', d => y(d.count) - 15)
.attr('dy', '.75em')
.text(d => d.count)
.attr('text-anchor', 'middle');
chart.append("g")
.attr("transform", "translate(0," + (height + margin.top) + ")")
.call(d3.axisBottom(x));