Published
Edited
Aug 8, 2022
1 fork
Importers
Insert cell
Insert cell
chart = {

var svg = d3.select(DOM.svg(width, height));

///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 height - 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 colorScale(d)
})

return svg.node()
}
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
function updateBar(){
//Update all rects
d3.select(chart).selectAll("rect")
.data(dataset)
.transition() // <---- Here is the transition
.duration(2000) // 2 seconds
.attr("y", function(d) {
return height - yScale(d);
})
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", function(d) {
return colorScale(d)
});
}
Insert cell
{
while (true) {
newData();
updateBar();
yield;
await Promises.delay(1300);
}
}
Insert cell
Insert cell
margin = ({top: 30, right: 15, bottom: 10, left: 15})
Insert cell
width = 300 - margin.left - margin.right;
Insert cell
height = 150 - margin.top - margin.bottom;
Insert cell
dataset = [ 7, 10, 16, 5, 14, 19, 19, 11, 12, 10]
Insert cell
xScale = d3.scaleBand() //Ordinal scale
.domain(d3.range(dataset.length)) //sets the input domain for the scale
.rangeRound([0, width]) //enables rounding of the range
.paddingInner(0.05); //spacing between each bar
Insert cell
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, height]);
Insert cell
colorScale = d3.scaleSequential()
.domain([0, d3.max(dataset)]) //sets the upper end of the input domain to the largest data value in dataset
.interpolator(d3.interpolateWarm);
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