Published
Edited
Feb 12, 2020
11 forks
24 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
// xScale will help us set the x position of the bars
xScale = d3.scaleBand() //Ordinal scale
.domain(d3.range(dataset.length)) //sets the input domain for the scale
.rangeRound([0, w]) //enables rounding of the range
.paddingInner(0.05); //spacing between each bar
Insert cell
//yScale will help us map data to the height of bars in the barchart
yScale = d3.scaleLinear()
.domain([0, d3.max(dataset)]) //sets the upper end of the input domain to the largest data value in dataset
.range([0, h]);
Insert cell
Insert cell
//Create SVG element
svg = d3.select(body)
.append("svg")
.attr("width", w)
.attr("height", h);
Insert cell
//Create bars
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) { // position in x-axis
return xScale(i); // we will pass the values from the dataset
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", xScale.bandwidth()) //Asks for the bandwith of the scale
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", function(d) {
return "rgb("+ Math.round(d * 8) + ",0," + Math.round(d * 10) + ")"; //Change the color of the bar depending on the value
});
Insert cell
Insert cell
d3.select(button)
.on("click", function() {
newData(); //Changes de values of the data
updateBar(); //Updates the bar chart
});
Insert cell
Insert cell
function newData(){
while (dataset.length > 0) { //Clear the current dataset
dataset.pop();
}
for (var i = 0; i < 20; i++) { //Loop 20 times
var newNumber = Math.floor(Math.random() * 20) + 5; //New random integer (5-25)
dataset.push(newNumber); //Add new number to array
}
}
Insert cell
Insert cell
function updateBar(){
//Update all rects
svg.selectAll("rect")
.data(dataset)
.transition() // <---- Here is the transition
.duration(2000) // 2 seconds
.attr("y", function(d) {
return h - yScale(d);
})
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", function(d) {
return "rgb("+ Math.round(d * 8) + ",0," + Math.round(d * 10) + ")";
});
}
Insert cell
md`
Transitions are very powerful and customizable with d3, as explaind in the [documentation](https://github.com/d3/d3-transition). For example, try adding _.delay(function(d,i){return i*100})_ after duration(2000)...
`
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more