Skip to content

Instantly share code, notes, and snippets.

@clhenrick
Created May 7, 2019 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clhenrick/d3cf6054b6fe08dda52de8e1627c993d to your computer and use it in GitHub Desktop.
Save clhenrick/d3cf6054b6fe08dda52de8e1627c993d to your computer and use it in GitHub Desktop.
Simple Scatterplot with d3@5
license: mit

Simple Scatterplot

Using d3@5 and selection.join().

Built with blockbuilder.org

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var margin = { top: 20, left: 50, right: 10, bottom: 50 };
var width = 500;
var height = 500;
var svg = d3.select("body").append("svg")
.attr("height", height)
.attr("width", width);
var xScale = d3.scaleLinear()
.range([0, width - margin.left - margin.right]);
var yScale = d3.scaleLinear()
.range([height - margin.top - margin.bottom, 0]);
var cScale = d3.scaleOrdinal(d3.schemeCategory10);
function xAxis(g) {
g.attr("transform", `translate(0, ${height - margin.bottom - margin.top})`)
.call(d3.axisBottom(xScale));
}
function yAxis(g) {
g.call(d3.axisLeft(yScale));
}
function parseRow(d) {
return {
sepal_length: +d.sepal_length,
sepal_width: +d.sepal_width,
petal_length: +d.petal_length,
petal_width: +d.petal_width,
species: d.species
}
}
function main(data) {
console.log(data);
xScale.domain(d3.extent(data, d => d.sepal_width));
yScale.domain(d3.extent(data, d => d.sepal_length));
var g = svg.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`)
g.append("g").call(xAxis);
g.append("g").call(yAxis);
g.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => xScale(d.sepal_width))
.attr("cy", d => yScale(d.sepal_length))
.attr("fill", d => cScale(d.species))
.attr("r", 2.5);
}
d3.csv("https://gist.githubusercontent.com/clhenrick/fe82108ca72121b3e2000ced4e36a53b/raw/eedfd982b5324d62c2c2b69171b937db73f41f29/flowers.csv", parseRow)
.then(main);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment