Public
Edited
Mar 22, 2023
1 fork
Insert cell
Insert cell
Insert cell
{
// adapted from https://observablehq.com/@d3/lets-make-a-bar-chart/2?collection=@d3/lets-make-a-bar-chart
const svg = d3
.create("svg")
.attr("width", 1024)
.attr("height", numbers.length * 16)
.attr("font-family", "sans-serif")
.attr("font-size", "10")
.attr("text-anchor", "end");

const bar = svg
.selectAll("g")
.data(numbers)
.join("g")
.attr("transform", (d, i) => `translate(0,${i * 16})`);

bar
.append("rect")
.attr("fill", "steelblue")
.attr("width", (d) => d * 10)
.attr("height", 15);

bar
.append("text")
.attr("fill", "white")
.attr("x", (d) => d * 10 - 3)
.attr("y", 15 / 2)
.attr("dy", "0.35em")
.text((d) => d);

return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
numbers
Insert cell
x = d3
.scaleLinear()
.domain([0, d3.max(numbers)])
.range([0, 300])
Insert cell
y = d3
.scalePoint()
.domain(d3.range(numbers.length)) // note: this is an array containing an entry for each entry in the data
.range([0, 435]) // we allocate a space of 20px for each entry, to accomodate space for paddings
Insert cell
Insert cell
{
// adapted from https://observablehq.com/@d3/lets-make-a-bar-chart/2?collection=@d3/lets-make-a-bar-chart
// const svg = d3
// .create("svg")
// .attr("width", 1024) // change
// .attr("height", y.range()[1]) // change
// .attr("font-family", "sans-serif")
// .attr("font-size", "10")
// .attr("text-anchor", "end");
const svg = d3.select("#viz");

const bar = svg
.selectAll("g")
.data(numbers)
.join("g")
.attr("transform", (d, i) => `translate(${y(i) + y.step()}, ${y.step()})`); // change

bar
.selectAll("circle")
.data((d) => [d])
.join("circle")
.attr("fill", "steelblue")
.attr("r", (d) => r(d)); // change
//.attr("height", y.bandwidth() - 1); // change
}
Insert cell
r = d3
.scaleSqrt()
.domain([0, d3.max(numbers)])
.range([0, 50])
Insert cell
r(2)
Insert cell
r(4)
Insert cell
Insert cell
Insert cell
d3 = require('d3')
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