viewof chart = {
const rawData = await FileAttachment("players_20.csv").csv();
const data = rawData.map((d) => ({
...d,
age: +d.age,
overall: +d.overall,
nationality: d.nationality
}));
console.log("Processed data:", data.slice(0, 5));
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const width = 800 - margin.left - margin.right;
const height = 600 - margin.top - margin.bottom;
const svg = d3
.create("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
const chart = svg
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
console.log("SVG created:", svg.node());
const x = d3
.scaleLinear()
.domain(d3.extent(data, (d) => d.age))
.range([0, width]);
const y = d3
.scaleLinear()
.domain(d3.extent(data, (d) => d.overall))
.range([height, 0]);
const color = d3
.scaleOrdinal()
.domain([...new Set(data.map((d) => d.nationality))])
.range(d3.schemeCategory10);
// Add x-axis
chart
.append("g")
.attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(x))
.append("text")
.attr("x", width / 2)
.attr("y", 35)
.attr("fill", "black")
.style("font-size", "14px")
.text("Age");
// Add y-axis
chart
.append("g")
.call(d3.axisLeft(y))
.append("text")
.attr("x", -height / 2)
.attr("y", -40)
.attr("fill", "black")
.style("font-size", "14px")
.style("text-anchor", "middle")
.attr("transform", "rotate(-90)")
.text("Overall Rating");
// Add scatterplot points
chart
.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", (d) => x(d.age))
.attr("cy", (d) => y(d.overall))
.attr("r", 5)
.style("fill", (d) => color(d.nationality))
.style("opacity", 0.8);
// Add chart title
chart
.append("text")
.attr("x", width / 2)
.attr("y", -10)
.attr("text-anchor", "middle")
.style("font-size", "16px")
.text("Scatterplot of Age vs. Overall Rating by Nationality");
// Return the entire SVG element for Observable to render
return svg.node();
}