Built with blockbuilder.org
Created
November 21, 2018 01:52
-
-
Save veev/962c2b6ef33617b070d9f5b52fdab103 to your computer and use it in GitHub Desktop.
fresh block
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> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
</style> | |
</head> | |
<body> | |
<script> | |
// Feel free to change or delete any of the code you see in this editor! | |
const names = ['Andy', 'Beth', 'Craig', 'Diane', 'Evelyn', 'Fred', 'Georgia', 'Harry', 'Isabel', 'John'] | |
const myData = [ | |
{ | |
'name': 'Andy', | |
'score': 37 | |
}, | |
{ | |
'name': 'Beth', | |
'score': 39 | |
}, | |
{ | |
'name': 'Craig', | |
'score': 31 | |
}, | |
{ | |
'name': 'Diane', | |
'score': 35 | |
}, | |
{ | |
'name': 'Evelyn', | |
'score': 38 | |
} | |
] | |
const svg = d3.select('#wrapper') | |
.append('svg') | |
.attr('width', 500) | |
.attr('height', 200) | |
const barMax = 400 | |
const barScale = d3.scaleLinear() | |
.domain([0, 100]) | |
.range([0, barMax]) | |
const randomInt = () => { | |
return Math.floor(10 * Math.random()) | |
} | |
updateScores = () => { | |
const updatedData = myData.map( d => { | |
d.score = 30 + randomInt() | |
return d | |
}) | |
updateBars(updatedData) | |
} | |
addPerson = () => { | |
if (myData.length === 10) { | |
return | |
} | |
myData.push({ | |
name: names[myData.length], | |
score: 30 + randomInt() | |
}) | |
// adds a new object to the end of the array | |
updateBars(myData) | |
} | |
removePerson = () => { | |
if (myData.length === 0) { | |
return | |
} | |
myData.pop() // removes element at the end of the array | |
updateBars(myData) | |
} | |
updateBars = (data) => { | |
const bars = svg.selectAll('rect') | |
.data(data) | |
bars.enter() | |
.append('rect') | |
.attr('fill', 'steelblue') // you can also set the color with a class | |
.attr('width', d => barScale(d.score)) | |
.attr('height', 20) | |
.attr('y', (d, i) => i * 22) | |
.attr('x', d => 0) | |
.merge(bars) | |
// .transition() | |
// .duration(1000) | |
.attr('width', d => barScale(d.score)) | |
bars.exit() | |
// .transition() | |
// .duration(1000) | |
.remove() | |
// .append('rect') | |
console.log(bars) | |
} | |
// initializeData() | |
updateBars(myData) | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment