Built with blockbuilder.org
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:20px;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<button class="add">Add</button>
<button class="remove">Remove</button>
<br>
<br>
<script>
const margin = { top: 10, right: 10, bottom: 30, left: 10 };
const width = 800;
const height = 500;
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.bottom - margin.top;
let cities = [];
const y = d3.scaleLinear()
.rangeRound([innerHeight, 0])
;
const x = d3.scaleBand()
.rangeRound([0, innerWidth])
.padding(0.2)
;
const color = d3.scaleOrdinal(d3.schemeCategory20c)
.domain([0, 100])
;
const svg = d3.select('body')
.append('svg')
.style('border', '1px solid #ddd')
.attr('width', width)
.attr('height', height);
const g = svg.append('g')
.attr('transform', `translate(${margin.top},${margin.left})`)
;
const chartAxis = g.append('g')
.attr('transform', `translate(${0},${innerHeight})`)
;
function update(data) {
let t = d3.transition()
.delay(100)
;
y.domain([0, d3.max(data, d => d)]);
x.domain(data.map(d => d));
let xAxis = d3.axisBottom(x).ticks(20).tickFormat(d3.format(",.0f"));
chartAxis.transition()
.delay(100)
.call(xAxis)
;
let selection = g.selectAll('rect')
.data(data, d => d)
;
// EXIT
selection.exit()
.attr('class', 'exit')
.transition(t)
.attr('height', 0)
.attr('y', innerHeight)
.remove()
;
// UPDATE old elements present in new data.
selection.attr("class", "update")
.attr('y', d => innerHeight)
.attr('height', 0)
.attr('width', x.bandwidth())
.transition(t)
.attr('x', x)
.attr('y', y)
.attr('width', x.bandwidth())
.attr('height', d => innerHeight - y(d));
// ENTER
selection.enter()
.append('rect')
.attr('class', 'enter')
.attr('height', 0)
.attr('y', innerHeight)
.attr('x', x)
.attr('width', x.bandwidth())
.style('fill', d => color(d))
.transition(t)
.attr('height', d => innerHeight - y(d))
.attr('y', y)
;
}
update(cities);
function rand(min=10, max=100) {
return (Math.random() * (max - min) + min);
}
document.querySelector('.add')
.addEventListener('click', function() {
cities.push(rand());
update(cities);
});
document.querySelector('.remove')
.addEventListener('click', function() {
cities.pop();
update(cities);
});
</script>
</body>
https://d3js.org/d3.v4.min.js