Public
Edited
May 21, 2023
Insert cell
Insert cell
Insert cell
function generateRandomData() {
const dataset = [];

for (let i = 0; i < 100; i++) {
const height = Math.random() * 7;
const weightRandomOffset = Math.random() * 30 - 10; // Random number between -10 and 20
const weight = height * 30 + weightRandomOffset;
const gender = Math.random() < 0.5 ? "Male" : "Female";
const age = height * 10 + (Math.random() * 5 - 2.5); // Age slightly correlated with height

dataset.push({ height, weight, gender, age });
}

return dataset;
}
Insert cell
data = generateRandomData()
Insert cell
## 2. Create a scatterplot of height vs. weight with color to show gender and size to show age
Insert cell
{
const target = html`<svg id="target" viewBox="0 0 ${width} ${height}">
</svg>`;

const margin = { left: 50, right: 20, top: 20, bottom: 50 },
iwidth = width - margin.left - margin.right,
iheight = height - margin.top - margin.bottom;

const svg = d3.select(target);

const gDrawing = svg
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);

gDrawing
.append("rect")
.attr("width", iwidth + 5)
.attr("height", iheight + 5)
.attr("fill", "lightgrey")
.attr("transform", "translate(0, -5)");

const x = d3
.scaleLinear()
.domain([0, d3.max(data, (d) => d.height)])
.range([0, iwidth])
.nice();

const y = d3
.scaleLinear()
.domain([0, d3.max(data, (d) => d.weight)])
.range([iheight, 0])
.nice();

const color = d3.scaleOrdinal(d3.schemeAccent);
// .domain(Array.from(new Set(data.map(d => d.profession)).values()));

const r = d3
.scaleSqrt()
.domain([0, d3.max(data, (d) => d.age)])
.range([0, 8])
.nice();

gDrawing
.append("g")
.attr("class", "x--axis")
.attr("transform", `translate(0, ${iheight})`)
.call(d3.axisBottom(x));

gDrawing
.append("text")
.attr("class", "x--axis-label")
.attr("x", iwidth / 2)
.attr("y", iheight + margin.bottom / 2 + 5)
.attr("text-anchor", "middle")
.text("Height");

gDrawing.append("g").attr("class", "y--axis").call(d3.axisLeft(y));

gDrawing
.append("text")
.attr("class", "y--axis-label")
.attr("transform", "rotate(-90)")
.attr("x", -iheight / 2)
.attr("y", -margin.left + 15)
.attr("text-anchor", "middle")
.text("Weight");

const circles = gDrawing
.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", (d) => x(d.height))
.attr("cy", (d) => y(d.weight))
.attr("r", (d) => r(d.age))
.attr("fill", (d) => color(d.gender));

return target;
}
Insert cell
height = width * 0.5
Insert cell
Insert cell
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