Getting to know Susie Lu's d3-annotation() module.
lyrics.csv
filefreshness
' and 'princeliness
' atttributesannotationCalloutElbow
connectorxxxxxxxxxx
<html lang="en">
<head>
<meta charset="utf-8">
<style>
svg { font-family: Courier; }
.annotation-note-title, text.title { font-weight: bold; }
text.title { font-size: 1.2em; }
</style>
</head>
<body>
<svg width=960 height=500>
<text class="title" x=40 y=50>d3.annotation()</text>
<text x=40 y=80>Getting my head around data-driven annotations</text>
</svg>
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-annotation/2.1.0/d3-annotation.min.js"></script>
<script>
// Set up some scales
const y = d3.scaleLinear()
.range([0, 500])
.domain([0, 10]),
x = d3.scaleLinear()
.range([0, 960])
.domain([0, 10]),
color = d3.scaleOrdinal(d3.schemeCategory10)
// Load our external data
d3.csv("lyrics.csv", function(data) {
// Map the lyrics data to an array of objects detailing
// each annotation's text, position & style.
// Note use of x, y, color scales. +d converts strings to numerics.
const annotations = data.map(function(d, i){
return {
note: {
title: d.title,
label: d.lyric,
wrap: 214, // text wrap threshold
align: 'left', //cf. right, middle, dynamic
},
connector: {end: 'dot'}, // cf. arrow
x: x(+d.freshness),
y: y(+d.princeliness),
dy: 90, // vertical offset
dx: 100,// horizontal offset
color: color(i) // send index to color scale
}
})
// Create a d3.annotation()
// & pass in our annotation properties array.
// Susie's examples use accessors & accessorsInverse
// here to establish SVG x,y positions.
// I set these earlier when mapping to annotation properties array
const makeAnnotations = d3.annotation()
.type(d3.annotationCalloutElbow) //cf. annotationLabel etc.
.annotations(annotations)
// Append the annotations to the SVG
d3.select("svg")
.append("g")
.attr("class", "annotation-group")
.call(makeAnnotations)
})
</script>
</body>
</html>
https://d3js.org/d3.v4.js
https://cdnjs.cloudflare.com/ajax/libs/d3-annotation/2.1.0/d3-annotation.min.js