forked from RodrigoRoaRodriguez/d3tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercise2.html
More file actions
64 lines (54 loc) · 2.44 KB
/
Copy pathexercise2.html
File metadata and controls
64 lines (54 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body{background-color: #fcc;}
svg#the-right-svg{background-color: #dfd;}
svg#the-wrong-svg{background-color: #faa;}
svg#the-right-svg text {font: bold 100px monospace;}
tspan.right{stroke-width: 2px; stroke:green;}
</style>
<h1 style="font: bold 2em monospace">EXERCISE 2</h1>
<svg id="the-wrong-svg" width="200" height="200"></svg>
<svg id="the-right-svg" width="600" height="600"><text style="font: bold 15px monospace;" x="10" y="580">Do <tspan style="fill:red;">NOT</tspan> mess with me</text></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
// EXERCISE DESCRIPTION:
// create a 4x4 half-square with the numbers from 0 to 9
// SUBJECTS COVERED
// - Data processing
// - Function Mapping
// - How to do 'nested-loops' in D3
// STEP 1: get our data in the application
// Unfortunately, our data was gathered, and will continue to be gathered, by a // disorganized non-programmer who doesn't know how to count from 0.
const BAD_DATA = [[5,6,7],[10],[8,9],[1,2,3,4]]
// STEP 2: Create a function that fixes our data every time.
let sortRows = badData => badData.slice(0).sort((a,b)=>(a.length < b.length))
let fromZero = badData => badData.map(row => row.map(badDatum => badDatum-1))
let fixData = badData => fromZero(sortRows(badData))
// STEP 3: select right svg canvas and pair the right texts.
// <text> can be used as a text-canvas (or in this case rows) where every
// piece of text is a <tspan> element
let datalessSvg = d3.select('#the-right-svg')
let pairRowsToTexts = datalessSvg.selectAll('text.right').data(fixData(BAD_DATA))
//STEP 4: make a new selection for new ROWS in the data.
let forEveryNewRow = pairRowsToTexts.enter()
.append('text')
.attr('class', 'right')
//STEP 5: Style your rows
let fontSize = 125
forEveryNewRow
.style('fill', (_,i) => d3.schemeCategory10[i])
.attr('y', (dataElement, index) => (index+1) * fontSize)
//STEP 6: pair each datum to a <tspan>.
let pairDataToTspans = forEveryNewRow.selectAll('tspan.right')
.data(row => row)
//STEP 7: make a new selection for NEW entries in the data.
let forEveryNewDatum = pairDataToTspans.enter()
//STEP 8: append a <tspan> for every new datum in the rows
let myTspans = forEveryNewDatum.append('tspan').text(dataElement => dataElement.toString())
//STEP 9: style your tspans
myTspans
.attr('class', 'right')
.attr('x', (dataElement, index) => index * fontSize)
.style('font', `bold ${fontSize}px monospace`)
</script>