easy-d3-annotate

Simple annotations for d3 graphics

Setup

Include d3 (v7 or higher) before including your annotation script.

To add easy-d3-annotate as a node module run npm i @camdenblatchly/easy-d3-annotate.

In use

Here is an example of an annotation definition:

let annotation = {
    note: "Boston, MA", // Whatever you want your note to say. Accepts HTML.
    data: [ 
      // The coordinates of the annotation subject go first
      { x: +x(max_cty.pct_ba_higher), y: y(+max_cty.pci) }, 
      // You can optionally define an intermediary point for the line to pass through
      { x: x(0.4), y: y(45000) }, 
      // The coordinates of the annotation note go last
      { x: x(0.42), y: y(35000) }, 
    ], 
    width: 100,
    height: 55, 
    // You can optionally specify an id for CSS styling
    id: 'max-anno',
    // Or a class
    class: 'annotation',
    // Use arrow_offset to offset the position of the arrow from its subject
    arrow_offset: { x: 0, y: dot_radius * 1.5 }, 
    // Specify where the line should connect to the note
    line_start: 'top', 
    // Lines can either have linear or normal curves 
    curve_type: 'linear'
  }
      
You can then add your annotation by running svg.call(addAnnotation, annotation) at the end of your script.

Parameters

note A string containing your annotation text. It accepts HTML.

data An array containing at least two x/y coordinate pairs. The first coordinate pair demarcates the location of what you want to point to. The final coordinate pair demarcates the location of your annotation note. In between, you can add coordinate pairs for any location you want your line to pass through.

width Width of the note container. Defaults to pixels.

height Height of the note container. Defaults to pixels.

id Optional id applied to the g element containing the note and line.

class Optional class applied to the g element containing the note and line.

arrow_offset Optional coordinate pair defining the offset of the arrow from the subject. Defaults to pixels.

curve_type One of either "natural" (a swoopy line) or "linear" (a straight line). Defaults to "natural".

Styling

Annotation notes are added to the SVG using foreignObject elements. As such, the easiest way to customize your annotation styles is by defining the foreignObject element or any HTML elements you added within.