Public
Edited
Mar 22, 2023
Insert cell
Insert cell
numbers = d3
.range(Math.round(Math.random() * 20))
.map((d) => Math.round(Math.random() * 100))
Insert cell
newNumbers = d3
.range(Math.round(Math.random() * 20))
.map((d) => Math.round(Math.random() * 100))
Insert cell
svg`<svg id='viz' width='600' height='400'></svg>`
Insert cell
svg`<svg id='viz2' width='600' height='400'></svg>`
Insert cell
{
const myChart = BarChart();

d3.select("#viz2").datum(newNumbers).call(myChart.barColor("red").width(400));
d3.select("#viz").datum(numbers).call(myChart.barColor("steelblue"));
}
Insert cell
function BarChart() {
let barColor = "orange";
let width = 200;
const scaleLength = d3.scaleLinear().domain([0, 40]).range([0, width]);
const scaleY = d3
.scaleBand()
.domain(d3.range(10))
.range([0, 300])
.paddingInner(0.05);

function my(selection) {
const myData = selection.datum();
scaleY.domain(d3.range(myData.length));

const gs = selection
.selectAll("g")
.data(myData)
.join("g")
.attr("transform", (d, i) => `translate(${10},${scaleY(i)})`);

gs.selectAll("rect")
.data((d) => [d])
.join("rect")
.attr("height", scaleY.bandwidth())
.attr("width", scaleLength)
.attr("fill", barColor);

gs.selectAll("text")
.data((d) => [d])
.join("text")
.attr("dx", 5)
.attr("y", scaleY.bandwidth())
.attr("dy", -3)
.text((d) => d);
}

my.barColor = function (value) {
if (!arguments.length) return barColor;
barColor = value;
return my;
};

my.width = function (value) {
if (!arguments.length) return width;
width = value;
scaleLength.range([0, width]);
return my;
};

return my;
}
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