Public
Edited
Jan 25, 2023
Insert cell
Insert cell
chart = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);

// Create bars
svg
.append("g")
.attr("fill", "steelblue")
.selectAll("rect")
.data(students)
.join("rect")
.attr("x", d => x(d.name))
.attr("y", d => y(d.var1))
.attr("height", d => y(0) - y(d.var1))
.attr("width", x.bandwidth());

//Create Variable 1 values text
svg
.append("g")
.selectAll("text")
.data(students)
.join("text")
.text(d => Math.floor(d.var1))
.attr("x", d => x(d.name) + x.bandwidth() / 2)
.attr("y", d => y(d.var1) - 6)
.attr("text-anchor", "middle")
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "black");
//.attr("font-weight", "bold");

//Create x-axis name labels
svg
.append("g")
.attr("transform", `translate(0,${height - margin.bottom})`)
.selectAll("text")
.data(students)
.join("text")
.text(d => d.name.split(' ')[0])
.attr("x", d => x(d.name) + x.bandwidth() / 2)
.attr("y", d => 60)
.attr("text-anchor", "middle")
.attr("font-family", "sans-serif")
.attr("font-size", "12px")
.attr("fill", "black");
//.attr("font-weight", "bold");

svg.append("g").call(xAxis);

svg.append("g").call(yAxis);

svg.call(yTitle);

return svg.node();
}
Insert cell
yAxis = g =>
g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove())
Insert cell
xAxis = g =>
g
.attr("transform", `translate(0,${height - margin.bottom})`)
.selectAll('image')
.data(students)
.join('image')
.attr('href', d => d.img)
.attr("x", d => x(d.name))
.attr('y', 5)
.attr('width', 40)
.attr('height', 40)
.call(d3.axisBottom(x).tickSizeOuter(0))
Insert cell
yTitle = g =>
g
.append("text")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("y", 10)
.text("Variable 1")
Insert cell
y = d3
.scaleLinear()
.domain([0, d3.max(students, d => d.var1)])
.range([height - margin.bottom, margin.top])
Insert cell
x = d3
.scaleBand()
.domain(students.map(d => d.name))
.rangeRound([margin.left, width - margin.right])
.padding(0.25)
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