D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
curran
Full window
Github gist
[unlisted] Using a sqrt scale
<!DOCTYPE html> <html> <head> <title>Encoding Data with Size</title> <script src="https://d3js.org/d3.v4.min.js"></script> <style> .axis .tick line { stroke-width: 2px; stroke: #dddddd; } .axis .tick text { font-size: 30px; fill: #8E8883; } .axis .domain { display: none; } .axis__label { text-anchor: middle; font-size: 50px; fill: #635F5D; } </style> </head> <body> <svg width="960" height="500"></svg> <script> const xValue = d => d.sepalLength; const yValue = d => d.petalLength; const sizeValue = d => d.petalWidth; const sizeMax = 10; const xLabel = "Sepal Length"; const yLabel = "Petal Length"; const margin = {top: 30, right: 30, bottom: 100, left: 100}; const svg = d3.select("svg"); const width = +svg.attr("width"); const height = +svg.attr("height"); const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; const xScale = d3.scaleLinear().range([0, innerWidth]); const yScale = d3.scaleLinear().range([innerHeight, 0]); const sizeScale = d3.scaleSqrt() .range([0, sizeMax]); const xAxis = d3.axisBottom() .scale(xScale) .tickSizeInner(-innerHeight) .tickPadding(15); const yAxis = d3.axisLeft() .scale(yScale) .tickSizeInner(-innerWidth) .ticks(5) .tickPadding(10); const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); const xAxisG = g.append("g") .attr("class", "axis") .attr("transform", `translate(0, ${innerHeight})`); const yAxisG = g.append("g") .attr("class", "axis"); xAxisG .append("text") .attr("class", "axis__label") .attr("x", innerWidth / 2) .attr("y", 85) .text(xLabel); yAxisG .append("text") .attr("class", "axis__label") .attr("transform", "rotate(-90)") .attr("x", -innerHeight / 2) .attr("y", -45) .text(yLabel); function render(data){ xScale .domain(d3.extent(data, xValue)) .nice(); yScale .domain(d3.extent(data, yValue)) .nice(); sizeScale .domain([0, d3.max(data, sizeValue)]); xAxisG.call(xAxis); yAxisG.call(yAxis); const circles = g.selectAll("circle").data(data); circles.exit().remove(); circles .enter().append("circle") .attr("r", 5) .merge(circles) .attr("cx", d => xScale(xValue(d))) .attr("cy", d => yScale(yValue(d))) .attr("r", d => sizeScale(sizeValue(d))); } function type(d){ d.sepalLength = +d.sepalLength; d.sepalWidth = +d.sepalWidth; d.petalLength = +d.petalLength; d.petalWidth = +d.petalWidth; return d; } d3.csv("iris.csv", type, render); </script> </body> </html>
https://d3js.org/d3.v4.min.js