Public
Edited
Jan 26
Insert cell
Insert cell
viewof chart = {
// Load and process the data
const rawData = await FileAttachment("players_20.csv").csv();
const data = rawData.map((d) => ({
...d,
age: +d.age, // Convert age to numeric
overall: +d.overall, // Convert overall to numeric
nationality: d.nationality // Keep nationality as a categorical field
}));

// Debug: Ensure data is loaded
console.log("Processed data:", data.slice(0, 5));

// Define margins and dimensions
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const width = 800 - margin.left - margin.right;
const height = 600 - margin.top - margin.bottom;

// Create the SVG container
const svg = d3
.create("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);

// Append a group element to the SVG
const chart = svg
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);

// Debug: Ensure SVG is created
console.log("SVG created:", svg.node());

// Define scales
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();
}
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