Public
Edited
Sep 17, 2023
Insert cell
Insert cell
summary = d3.rollup(
data,
(v) => ({
total_players: v.length,
average_age: d3.mean(v, (d) => d.age),
country: v[0].nationality
}),
(d) => d.nationality
)
Insert cell
{
const target = html`<svg id="target" viewBox="0 0 ${width} ${height}"></svg>`;

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

const svg = d3.select(target);
// Create New Element
const gDrawing = svg
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
gDrawing
.append("rect")
.attr("width", iwidth)
.attr("height", iheight)
.attr("fill", "#eee");

// Convert summary data to Array for populating
const data = Array.from(summary.values());

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

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

const color = d3.scaleOrdinal(d3.schemeAccent);

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

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

const circles = gDrawing
.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", (d) => x(d.total_players))
.attr("cy", (d) => y(d.average_age))
.attr("r", 5)
.attr("fill", (d) => color(d.country));

// Add a title and define appropriate formating
svg
.append("text")
.attr("x", iwidth / 2)
.attr("y", margin.top)
.attr("text-anchor", "middle")
.style("font-size", "18px")
.text("Total Count and Average Age of Player By Country");

// Add X-axis label with Formating
svg
.append("text")
.attr("x", iwidth / 2)
.attr("y", iheight + margin.top + 30)
.attr("text-anchor", "middle")
.style("font-size", "14px")
.text("Total Count of Players");

// Add Y-axis label with formating
svg
.append("text")
.attr("x", -iheight / 2)
.attr("transform", "rotate(-90)")
.attr("y", -margin.left + 75)
.style("font-size", "14px")
.text("Average Player Age");
return target;
}
Insert cell
d3 = require("d3@6")
Insert cell
Insert cell
height = width * 0.5
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