D_chart = {
const width = 700;
const height = 350;
const dataset = [5, 10, 24, 16, 18, 19, 22, 9, 8, 17, 4, 6, 10, 12, 20];
const margin = ({top: 50, right: 100, bottom: 10, left: 10})
const svg = d3.create("svg").attr("width", width).attr("height", height)
let xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.range([0, width - margin.right])
.paddingInner(0.05);
let yScale = d3.scaleLinear()
.domain([0, d3.max(dataset)])
.range([0, height]);
const rects = svg.selectAll("rect")
.data(dataset)
.join("rect")
.attr("x", (d, i) => xScale(i))
.attr("y", d => height - yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", d => yScale(d))
.attr("fill", d => "rgb("+ Math.round(d * 5) +", "+ Math.round(d * 2) +", "+ Math.floor(d * 9) +")");
d3.select(add)
.on("click", function(){
const maxValue = 40;
let newNumber = 1+ Math.round(Math.random() * maxValue);
dataset.push(newNumber);
xScale.domain(d3.range(dataset.length));
yScale.domain([0, d3.max(dataset)]);
const bars = svg.selectAll("rect").data(dataset);
const enter = bars.enter().append("rect").attr("x", width).attr("y", d => height - yScale(d))
const updatedBars = enter.merge(bars)
.transition()
.duration(400)
.attr("x", (d, i) => xScale(i))
.attr("y", d => height - yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", d => yScale(d))
.attr("fill", d => "rgb("+ Math.round(d * 5) +", "+ Math.round(d * 2) +", "+ Math.floor(d * 9) +")");
svg.selectAll("text")
.data([newNumber])
.join("text")
.attr("x", 650)
.attr("y", 50)
.attr("font-size", "45px")
.text(d => d)
})
d3.select(reset)
.on("click", function(){
while (dataset.length > 15) {
dataset.pop()
}
svg.selectAll("text").remove()
xScale.domain(d3.range(dataset.length));
yScale.domain([0, d3.max(dataset)]);
svg.selectAll("rect")
.data(dataset)
.join(
exit => exit
.remove()
)
.transition()
.duration(500)
.attr("x", (d, i) => xScale(i))
.attr("y", d => height - yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", d => yScale(d))
.attr("fill", d => "rgb("+ Math.round(d * 5) +", "+ Math.round(d * 2) +", "+ Math.floor(d * 9) +")");
})
return svg.node()
//This visualization is based on Scott Murray's D3 Book (2nd edition) and https://observablehq.com/@uvizlab/d3-tutorial-4-bar-chart-with-transition
}