Public
Edited
Apr 10, 2023
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell
{
const viewBoxWidth = 800;
const viewBoxHeight = 400;
const margin = { top: 20, right: 20, bottom: 20, left: 20 };
const width = 800 - margin.left - margin.right;
const height = 400 - margin.top - margin.bottom;
const svg = d3.create("svg")
.attr("viewBox", `0 0 ${viewBoxWidth} ${viewBoxHeight}`);

const data = d3.range(20).map(() => Math.floor(Math.random() * 200 + 5));

const bars = svg.selectAll(".bar")
.data(data, d => d)
.join("rect")
.attr("class", "bar")
.attr("x", (d, i) => i * (width / data.length))
.attr("y", d => height - d)
.attr("width", width / data.length - 1)
.attr("height", d => d)
.attr("fill", (d, i) => i === 0 ? "orange" : "black"); // set the color of the first bar to orange

let i = 0;
let j = 1;
let swapped = false;

const interval = setInterval(() => {
if (data[i] > data[j]) {
const temp = data[i];
data[i] = data[j];
data[j] = temp;
swapped = true;

bars.data(data)
.transition()
.duration(100)
.attr("x", (d, i) => i * (width / data.length))
.attr("y", d => height - d)
.attr("height", d => d)
.attr("fill", (d, index) => {
if (index === i) return "orange"; // highlight the current bar being considered with orange color
if (index === j) return "red"; // highlight the next bar being considered with red color
return "black"; // set the rest of the bars to the default color
});
}

if (j === data.length - 1) {
if (!swapped) clearInterval(interval);
swapped = false;
i = 0;
j = 1;
} else {
i++;
j++;
}
}, 200);
// bars = svg.selectAll(".bar")
// .data(data, d => d)
// .join("rect")
// .attr("class", "bar")
// .attr("x", (d, i) => i * (width / data.length))
// .attr("y", d => height - d)
// .attr("width", width / data.length - 1)
// .attr("height", d => d)
// .attr("fill", (d, i) => "black"); // set the color of the first bar to orange
yield svg.node();
}

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