Skip to content

Instantly share code, notes, and snippets.

@fogonwater
Last active December 1, 2017 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fogonwater/54a38fc2b35b945047317a3c48b4cab1 to your computer and use it in GitHub Desktop.
Save fogonwater/54a38fc2b35b945047317a3c48b4cab1 to your computer and use it in GitHub Desktop.
labels from csv with d3.annotation()
license: mit

Getting to know Susie Lu's d3-annotation() module.

  • load lyrics.csv file
  • position annotations with 'freshness' and 'princeliness' atttributes
  • color annotations using row index
  • use the annotationCalloutElbow connector
  • set vertical + horizontal note offsets
<!DOCTYPE html>
<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>
freshness princeliness title lyric
1.0 2.0 Verse begins… Now this is a story all about how, my life got flipped turned upside down
4.5 2.5 … continues… And I'd like to take a minute, just sit right there
5.0 6.0 … and concludes I'll tell you how I became the prince of a town called Bel-Air
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment