Created
October 24, 2018 13:24
-
-
Save johnburnmurdoch/23dc20c6ebb5e37e2f50d2998f4aebb7 to your computer and use it in GitHub Desktop.
d3: translating text and rotating in-situ
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://unpkg.com/d3@5"></script> | |
<script src="https://unpkg.com/d3-selection-multi"></script> | |
<style> | |
* { | |
margin: 0; | |
padding: 0; | |
border: 0; | |
font-family: sans-serif; | |
font-size: 14px; | |
} | |
body { | |
background: #eee; | |
margin: 5px; | |
} | |
svg{ | |
display: inline-block; | |
border: 1px solid #aaa; | |
margin: 3px; | |
} | |
</style> | |
</head> | |
<body> | |
<svg id=rot_then_trans></svg> | |
<svg id=trans_then_rot></svg> | |
<svg id=grouped></svg> | |
<script> | |
const width = 460, height = 300; | |
d3.selectAll('svg') | |
.attr("width", width) | |
.attr("height", height) | |
.style("width", `${width}px`) | |
.style("height", `${height}px`); | |
const rot_then_trans = d3.select('#rot_then_trans'); | |
const trans_then_rot = d3.select('#trans_then_rot'); | |
const grouped = d3.select('#grouped'); | |
const dataSet = [1, 11, 21, 31]; | |
const anchors = d3.selectAll('svg').selectAll('circle') | |
.data(dataSet) | |
.enter() | |
.append('circle') | |
.attrs({ | |
cx: (d,i) => d*10+30, | |
cy: (d,i) => 50, | |
r: 5, | |
stroke: 'red', | |
"stroke-width": 2, | |
fill: 'none' | |
}); | |
const labels_A = rot_then_trans.selectAll('text.B') | |
.data(dataSet) | |
.enter() | |
.append('text') | |
.attrs({ | |
class: "A", | |
transform: (d,i) => `rotate(30) translate(${d*10+30}, ${50})` | |
}) | |
.html(d => `rot then trans`); | |
const labels_B = trans_then_rot.selectAll('text.A') | |
.data(dataSet) | |
.enter() | |
.append('text') | |
.attrs({ | |
class: "B", | |
transform: (d,i) => `translate(${d*10+30}, ${50}) rotate(30)` | |
}) | |
.html(d => `trans then rot`); | |
const groups = grouped.selectAll('g') | |
.data(dataSet) | |
.enter() | |
.append('g') | |
.attrs({ | |
transform: (d,i) => `translate(${d*10+30}, ${50})` | |
}); | |
const group_circles = groups | |
.append('circle') | |
.attrs({ | |
r: 5, | |
stroke: 'red', | |
"stroke-width": 2, | |
fill: 'none' | |
}); | |
const group_text = groups | |
.append('text') | |
.attrs({ | |
class: "B", | |
transform: (d,i) => `rotate(30)` | |
}) | |
.html(d => `Grouped`); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment