Built with blockbuilder.org
Last active
August 11, 2018 01:29
-
-
Save john-guerra/606739ac4cd7251f8e4df71e48abeaa2 to your computer and use it in GitHub Desktop.
Scatterplot d3v4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
</style> | |
</head> | |
<body> | |
<h1>Scatterplot D3v4</h1> | |
<svg width=200 | |
height=200 | |
id="viz"> | |
</svg> | |
<div>Made by John with ❤️</div> | |
<script> | |
let svg = d3.select("#viz"), | |
margin = {top: 20, right: 20, bottom: 30, left: 50}, | |
width = +svg.attr("width") - margin.left - margin.right, | |
height = +svg.attr("height") - margin.top - margin.bottom, | |
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); | |
g.append("g") | |
.attr("class", "x axis"); | |
g.append("g") | |
.attr("class", "y axis"); | |
let myData = [ | |
{name:"John", age:23, height:1.93}, | |
{name:"Mafe", age:22, height:1.70}, | |
{name:"Sonia", age:27, height:1.60}, | |
{name:"Vicente", age:73, height:0.32} | |
]; | |
let x = d3.scaleLinear() | |
.range([0, width]); | |
let y = d3.scaleLinear() | |
.range([height, 0]); | |
function update(myData) { | |
x.domain([0, d3.max(myData, d => d.age)]); | |
y.domain([0, d3.max(myData, d => d.height)]); | |
let points = g.selectAll(".point") | |
.data(myData); //update | |
pointsEnter = points | |
.enter() | |
.append("circle") | |
.attr("class", "point"); | |
points.merge(pointsEnter) //Enter + Update | |
.attr("cx", d => x(d.age)) | |
.attr("cy", d => y(d.height)) | |
.attr("r", 3.5); | |
points.exit() | |
.remove(); | |
g.select(".x.axis") | |
.call(d3.axisBottom(x)) | |
.attr("transform", | |
"translate(0, " + height + ")"); | |
g.select(".y.axis") | |
.call(d3.axisLeft(y)); | |
} | |
update(myData); | |
console.log("w", width, " h", height); | |
</script> | |
</body> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment