Column annotated
Since we want an ordinal x-axis and Layer Cake defaults to a linear scale, pass in a custom scale to xScale with a few formatting options. Set the y-scale to always start at 0 so you don't show misleading differences between groups. The annotation and its arrows come from one config object, drawn by the AnnotationsData and Arrows components.
This is the server-side rendered version. ssr and percentRange on <LayerCake> put the scales in percentages, so the chart renders before the browser measures it. The axes are HTML components and the marks sit in a <ScaledSvg> that stretches to fit its box. The arrows are the exception: a ScaledSvg would bend them out of shape, so they get a second <LayerCake> with the same scales that renders only in the browser. Both cakes use position="absolute" to sit on top of each other.
- +page.svelte
- ./_components/Column.svelte
- ./_components/AxisX.percent-range.html.svelte
- ./_components/AxisY.percent-range.html.svelte
- ./_components/AnnotationsData.html.svelte
- ./_components/Arrows.svelte
- ./_components/ArrowheadMarker.svelte
- ./_modules/arrowUtils.js
- ./_data/groups.csv
<script>
import { LayerCake, Svg, ScaledSvg, Html } from 'layercake';
import { scaleBand } from 'd3-scale';
import Column from './_components/Column.svelte';
import AxisX from './_components/AxisX.percent-range.html.svelte';
import AxisY from './_components/AxisY.percent-range.html.svelte';
import Annotations from './_components/AnnotationsData.html.svelte';
import Arrows from './_components/Arrows.svelte';
import ArrowheadMarker from './_components/ArrowheadMarker.svelte';
// The CSV rows are parsed, and their numbers typed, by @rollup/plugin-dsv. See vite.config.js
import data from './_data/groups.csv';
const xKey = 'year';
const yKey = 'value';
const annotations = [
{
text: 'Example text...',
[xKey]: 1980,
[yKey]: 14,
dx: 15, // Nudge the text, in pixels
dy: -5,
arrows: [
{
clockwise: false, // Which way the arrow bows, true by default
source: {
anchor: 'left-bottom', // A spot on the text box: left, middle or right, then top, middle or bottom
dx: -2,
dy: -7
},
target: {
// A target under the data keys goes through the x and y scales
[xKey]: 1980,
[yKey]: 4.5,
// Nudge the arrow tip, in pixels
dx: 2,
dy: 5
}
},
{
source: {
anchor: 'right-bottom',
dy: -7,
dx: 5
},
target: {
// Percentage strings are measured against the chart instead
x: '68%',
y: '48%'
}
}
]
}
];
</script>
<div class="chart-container">
<LayerCake
ssr
percentRange
position="absolute"
padding={{ bottom: 20, left: 20 }}
x={xKey}
y={yKey}
xScale={scaleBand().paddingInner(0.02)}
xDomain={[1979, 1980, 1981, 1982, 1983]}
yDomain={[0, null]}
{data}
>
<Html>
<AxisX gridlines={false} />
<AxisY snapBaselineLabel />
</Html>
<ScaledSvg>
<Column />
</ScaledSvg>
<Html>
<Annotations {annotations} />
</Html>
</LayerCake>
<!--
A second LayerCake, rendered only in the browser, holds the arrows. The
ScaledSvg above stretches to fit its box, which would bend the arrows out
of shape, so they get a plain Svg with the same scales.
-->
<LayerCake
position="absolute"
padding={{ bottom: 20, left: 20 }}
x={xKey}
y={yKey}
xScale={scaleBand().paddingInner(0.02).round(true)}
xDomain={[1979, 1980, 1981, 1982, 1983]}
yDomain={[0, null]}
{data}
>
<Svg>
{#snippet defs()}
<ArrowheadMarker />
{/snippet}
<Arrows {annotations} />
</Svg>
</LayerCake>
</div>
<style>
/* Give the wrapper a width and height. LayerCake fills it. */
.chart-container {
position: relative;
width: 100%;
height: 250px;
}
</style><!--
@component
Generates an SVG column chart.
-->
<script>
import { getLayerCakeContext } from 'layercake';
const k = getLayerCakeContext();
/**
* @typedef {Object} Props
* @property {string} [fill='#00e047'] - The shape's fill color, used for every column. Set a `c` scale on `<LayerCake>` to color each column from its own row of data instead.
* @property {string} [stroke='#000'] - The shape's stroke color.
* @property {number} [strokeWidth=0] - The shape's stroke width.
* @property {boolean} [showLabels=false] - Show the numbers for each column.
*/
/** @type {Props} */
let { fill, stroke = '#000', strokeWidth = 0, showLabels = false } = $props();
// Use the `fill` prop if there is one, then the `c` scale's color, then the default
/** @param {any} d */
function getFill(d) {
return fill ?? k.cGet?.(d) ?? '#00e047';
}
// A histogram passes a [start, end] pair through the x accessor, so the column spans the two
/** @param {any} d */
function columnWidth(d) {
const vals = k.xGet(d);
return Math.abs(vals[1] - vals[0]);
}
// Each column starts at zero and runs out to its value, so a negative value
// hangs below zero. Keep zero inside your yDomain, or columns will be drawn
// outside the chart.
let zeroY = $derived(k.yScale(0));
</script>
<g class="column-group">
{#each k.data as d, i}
{@const valueY = k.yGet(d)}
{@const xGot = k.xGet(d)}
{@const xPos = Array.isArray(xGot) ? xGot[0] : xGot}
{@const colWidth = k.xScale.bandwidth ? k.xScale.bandwidth() : columnWidth(d)}
{@const yValue = k.y(d)}
<rect
class="group-rect"
data-id={i}
data-range={k.x(d)}
data-count={yValue}
x={xPos}
y={Math.min(zeroY, valueY)}
width={colWidth}
height={Math.abs(valueY - zeroY)}
fill={getFill(d)}
{stroke}
stroke-width={strokeWidth}
/>
{#if showLabels && yValue != null}
{@const pointsUp = valueY < zeroY}
<!--
Put the number just past the far end of the column: above a positive
column and below a negative one. Switching the text baseline keeps the
gap the same at any font size.
-->
<text
x={xPos + colWidth / 2}
y={valueY}
dy={pointsUp ? -5 : 5}
text-anchor="middle"
dominant-baseline={pointsUp ? 'auto' : 'hanging'}>{yValue}</text
>
{/if}
{/each}
</g>
<style>
text {
font-size: 12px;
}
</style><!--
@component
Generates an HTML x-axis along the bottom of the chart, for server-side rendered charts. If the x scale is a band scale, each tick sits in the middle of its band.
Positions are percentages when `percentRange={true}` and pixels otherwise, so this also works in a client-side chart with no setup. Set the `units` prop to `'%'` or `'px'` to override that.
-->
<script>
import { getLayerCakeContext } from 'layercake';
const k = getLayerCakeContext();
/**
* @typedef {Object} Props
* @property {boolean} [tickMarks=false] - Show a vertical mark at each tick.
* @property {boolean} [gridlines=true] - Show gridlines extending into the chart area.
* @property {number} [tickMarkLength=6] - The length of the tick mark.
* @property {boolean} [showBaseline=false] - Show a solid line along the bottom of the chart.
* @property {boolean} [snapLabels=false] - Instead of centering the text labels on the first and the last items, align them to the edges of the chart.
* @property {(d: any) => string} [format=d => d] - Formats a tick value for display.
* @property {number|Array<any>|((ticks: Array<any>) => Array<any>)} [ticks] - If this is a number, it passes that along to the [d3Scale.ticks](https://github.com/d3/d3-scale) function. If this is an array, hardcodes the ticks to those values. If it's a function, passes along the default tick values and expects an array of tick values in return. If nothing, it uses the default ticks supplied by the D3 function.
* @property {number} [tickGutter=0] - The gap in pixels between the bottom of the chart area and the start of the tick.
* @property {number} [dx=0] - Horizontal offset of the label in pixels.
* @property {number} [dy=0] - Vertical offset of the label in pixels.
* @property {'px'|'%'} [units] - Position with pixels or percentages. Defaults to `'%'` when `percentRange={true}`, otherwise `'px'`.
*/
/** @type {Props} */
let {
tickMarks = false,
gridlines = true,
tickMarkLength = 6,
showBaseline = false,
snapLabels = false,
format = d => d,
ticks = undefined,
tickGutter = 0,
dx = 0,
dy = 0,
units = k.percentRange === true ? '%' : 'px'
} = $props();
let tickLen = $derived(tickMarks === true ? (tickMarkLength ?? 6) : 0);
let isBandwidth = $derived(typeof k.xScale.bandwidth === 'function');
/** @type {Array<any>} */
let tickVals = $derived(
Array.isArray(ticks)
? ticks
: isBandwidth
? k.xScale.domain()
: typeof ticks === 'function'
? ticks(k.xScale.ticks())
: k.xScale.ticks(ticks)
);
let halfBand = $derived(isBandwidth ? k.xScale.bandwidth() / 2 : 0);
</script>
<div class="axis x-axis" class:snapLabels>
{#if showBaseline === true}
<div class="baseline" style="top:100%; width:100%;"></div>
{/if}
{#each tickVals as tick, i (tick)}
{@const tickValUnits = k.xScale(tick)}
{#if gridlines === true}
<div
class="gridline"
style:left="{tickValUnits + halfBand}{units}"
style="top:0; bottom:0;"
></div>
{/if}
{#if tickMarks === true}
<div
class="tick-mark"
style:left="{tickValUnits + halfBand}{units}"
style:height="{tickLen}px"
style:bottom="{-tickLen - tickGutter}px"
></div>
{/if}
<div
class="tick tick-{i}"
style:left="{tickValUnits + halfBand}{units}"
style="top:calc(100% + {tickGutter}px);"
>
<div
class="text"
style:top="{tickLen}px"
style:transform="translate(calc(-50% + {dx}px), {dy}px)"
>
{format(tick)}
</div>
</div>
{/each}
</div>
<style>
.axis,
.tick,
.tick-mark,
.gridline,
.baseline {
position: absolute;
}
.axis {
width: 100%;
height: 100%;
}
.tick {
font-size: 11px;
}
.gridline {
border-left: 1px dashed #aaa;
}
.tick-mark {
border-left: 1px solid #aaa;
}
.baseline {
border-top: 1px solid #aaa;
}
.tick .text {
color: #666;
position: relative;
white-space: nowrap;
transform: translateX(-50%);
}
/* Snapped end labels sit 40% inside their edge instead of centered on it */
.axis.snapLabels .tick:last-child {
transform: translateX(-40%);
}
.axis.snapLabels .tick.tick-0 {
transform: translateX(40%);
}
</style><!--
@component
Generates an HTML y-axis along the left edge of the chart, for server-side rendered charts. If the y scale is a band scale, each tick sits in the middle of its band.
Positions are percentages when `percentRange={true}` and pixels otherwise, so this also works in a client-side chart with no setup. Set the `units` prop to `'%'` or `'px'` to override that.
-->
<script>
import { getLayerCakeContext } from 'layercake';
const k = getLayerCakeContext();
/**
* @typedef {Object} Props
* @property {boolean} [tickMarks=false] - Show a horizontal mark at each tick.
* @property {'even'|'above'} [labelPosition='even'] - Whether the label sits level with its tick ('even') or above it ('above').
* @property {boolean} [snapBaselineLabel=false] - When labelPosition='even', adjust the lowest label so that it sits above the tick mark.
* @property {boolean} [gridlines=true] - Show gridlines extending into the chart area.
* @property {number} [tickMarkLength] - Length of the tick mark in pixels. Defaults to the width of the widest label when `labelPosition` is 'above', otherwise 6.
* @property {(d: any) => string} [format=d => d] - Formats a tick value for display.
* @property {number|Array<any>|((ticks: Array<any>) => Array<any>)} [ticks=4] - If this is a number, it passes that along to the [d3Scale.ticks](https://github.com/d3/d3-scale) function. If this is an array, hardcodes the ticks to those values. If it's a function, passes along the default tick values and expects an array of tick values in return.
* @property {number} [tickGutter=0] - The gap in pixels between the left edge of the chart area and the tick.
* @property {number} [dx=0] - Horizontal offset of the label in pixels.
* @property {number} [dy=-3] - Vertical offset of the label in pixels.
* @property {number} [charPixelWidth=7.25] - Used to calculate the widest label length to offset labels. Adjust if the automatic tick length doesn't look right because you have a bigger font (or just set `tickMarkLength` to a pixel value).
* @property {'px'|'%'} [units] - Position with pixels or percentages. Defaults to `'%'` when `percentRange={true}`, otherwise `'px'`.
*/
/** @type {Props} */
let {
tickMarks = false,
labelPosition = 'even',
snapBaselineLabel = false,
gridlines = true,
tickMarkLength = undefined,
format = d => d,
ticks = 4,
tickGutter = 0,
dx = 0,
dy = -3,
charPixelWidth = 7.25,
units = k.percentRange === true ? '%' : 'px'
} = $props();
/** @param {number} sum
* @param {string} val */
function calcStringLength(sum, val) {
if (val === ',' || val === '.') return sum + charPixelWidth * 0.5;
return sum + charPixelWidth;
}
let isBandwidth = $derived(typeof k.yScale.bandwidth === 'function');
/** @type {Array<any>} */
let tickVals = $derived(
Array.isArray(ticks)
? ticks
: isBandwidth
? k.yScale.domain()
: typeof ticks === 'function'
? ticks(k.yScale.ticks())
: k.yScale.ticks(ticks)
);
let widestTickLen = $derived(
Math.max(
10,
Math.max(...tickVals.map(d => format(d).toString().split('').reduce(calcStringLength, 0)))
)
);
let tickLen = $derived(
tickMarks === true
? labelPosition === 'above'
? (tickMarkLength ?? widestTickLen)
: (tickMarkLength ?? 6)
: 0
);
let x1 = $derived(-tickGutter - (labelPosition === 'above' ? widestTickLen : tickLen));
let halfBand = $derived(isBandwidth ? k.yScale.bandwidth() / 2 : 0);
let maxTickValUnits = $derived(Math.max(...tickVals.map(k.yScale)));
</script>
<div class="axis y-axis">
{#each tickVals as tick, i (tick)}
{@const tickValUnits = k.yScale(tick)}
<div
class="tick tick-{i}"
style="left:{k.xRange ? k.xRange[0] : 0}{units};top:{tickValUnits + halfBand}{units};"
>
{#if gridlines === true}
<div class="gridline" style="top:0;" style:left="{x1}px" style:right="0px"></div>
{/if}
{#if tickMarks === true}
<div class="tick-mark" style:top="0" style:left="{x1}px" style:width="{tickLen}px"></div>
{/if}
<div
class="text"
style:top="0"
style:text-align={labelPosition === 'even' ? 'right' : 'left'}
style:width="{widestTickLen}px"
style:left="{-widestTickLen - tickGutter - (labelPosition === 'even' ? tickLen : 0)}px"
style:transform="translate({dx + (labelPosition === 'even' ? -3 : 0)}px, calc(-50% + {dy +
(labelPosition === 'above' ||
(snapBaselineLabel === true && tickValUnits === maxTickValUnits)
? -3
: 4)}px))"
>
{format(tick)}
</div>
</div>
{/each}
</div>
<style>
.axis,
.tick,
.tick-mark,
.gridline,
.text {
position: absolute;
}
.axis {
width: 100%;
height: 100%;
}
.tick {
font-size: 11px;
width: 100%;
}
.gridline {
border-top: 1px dashed #aaa;
}
.tick-mark {
border-top: 1px solid #aaa;
}
.tick .text {
color: #666;
}
</style><!--
@component
Adds HTML text annotations placed by the chart's x and y scales, so they sit on the data.
-->
<script>
import { getLayerCakeContext } from 'layercake';
const k = getLayerCakeContext();
/**
* One annotation. The chart's x and y accessors read its data fields for
* the position, so it carries whatever keys those accessors look up.
* @typedef {Object} Annotation
* @property {string} text - The annotation's text.
* @property {number} [dx] - Horizontal nudge in pixels.
* @property {number} [dy] - Vertical nudge in pixels.
*/
/**
* @typedef {Object} Props
* @property {Array<Annotation>} annotations - The annotations to draw.
* @property {(d: Annotation) => string} [getLabel=d => d.text] - Returns the text for an annotation.
* @property {'px'|'%'} [units] - Position with pixels or percentages. Defaults to `'%'` when `percentRange={true}`, otherwise `'px'`.
*/
/** @type {Props} */
let {
annotations,
getLabel = d => d.text,
units = k.percentRange === true ? '%' : 'px'
} = $props();
</script>
<div class="layercake-annotations">
{#each annotations as d, i}
<div
class="layercake-annotation"
data-id={i}
style:left={`calc(${k.xGet(d)}${units} + ${d.dx || 0}px)`}
style:top={`calc(${k.yGet(d)}${units} + ${d.dy || 0}px)`}
>
{getLabel(d)}
</div>
{/each}
</div>
<style>
.layercake-annotation {
position: absolute;
}
</style><!--
@component
Adds SVG swoopy arrows based on a config object. It attaches arrows to divs, which are created by another component such as [Annotations.html.svelte](https://layercake.graphics/components/Annotations.html.svelte).
-->
<script>
import { tick } from 'svelte';
import { getLayerCakeContext } from 'layercake';
import { swoopyArrow, getElPosition, parseCssValue } from '../_modules/arrowUtils.js';
const k = getLayerCakeContext();
/**
* Where an arrow starts, on the annotation's text box.
* @typedef {Object} ArrowSource
* @property {string} anchor - A spot on the box as `horizontal-vertical`, e.g. `'right-middle'`. Horizontal is `left`, `middle` or `right`. Vertical is `top`, `middle` or `bottom`.
* @property {number|string} [dx] - Horizontal nudge, in pixels or as a percentage of the box width.
* @property {number|string} [dy] - Vertical nudge, in pixels or as a percentage of the box height.
*/
/**
* Where an arrow ends. Either a percentage of the chart, like `'68%'`, or a
* data value that goes through the x and y scales. Leave `x` or `y` out to
* read it from the annotation with the chart's x or y accessor instead.
* @typedef {Object} ArrowTarget
* @property {string|number} [x] - The x position.
* @property {string|number} [y] - The y position.
* @property {number|string} [dx] - Horizontal nudge, in pixels or as a percentage of the chart width.
* @property {number|string} [dy] - Vertical nudge, in pixels or as a percentage of the chart height.
*/
/**
* @typedef {Object} Arrow
* @property {boolean} [clockwise=true] - Which way the arrow bows.
* @property {ArrowSource} source - Where the arrow starts.
* @property {ArrowTarget} target - Where the arrow ends.
*/
/**
* One annotation, the same object that Annotations.html.svelte or
* AnnotationsData.html.svelte draws the text for. Only `arrows` matters here.
* @typedef {Object} Annotation
* @property {string} text - The annotation's text.
* @property {Array<Arrow>} [arrows] - The arrows to draw from this annotation.
*/
/**
* @typedef {Object} Props
* @property {Array<Annotation>} annotations - The annotations, in the same order the text component rendered them. See the [Column example](https://layercake.graphics/example/Column) for a full config.
* @property {string} [containerClass='.chart-container'] - The CSS selector of the element wrapping the `<LayerCake>` component. The arrows crawl it for the annotation divs.
* @property {string} [annotationClass='.layercake-annotation'] - The CSS selector of the annotation divs.
*/
/** @type {Props} */
let {
annotations,
containerClass = '.chart-container',
annotationClass = '.layercake-annotation'
} = $props();
/** @type {SVGGElement|undefined} */
let container = $state();
// The x side of an arrow works in `left` and `width`, the y side in `top` and `height`
/** @type {Array<{ dimension: 'width'|'height', css: 'left'|'top', position: 'x'|'y' }>} */
const lookups = [
{ dimension: 'width', css: 'left', position: 'x' },
{ dimension: 'height', css: 'top', position: 'y' }
];
/** @type {Array<Element>} */
let annotationEls = $state([]);
// Find the annotation divs the text component rendered, once the DOM has
// caught up, and again whenever the annotations change. The selectors have to
// match your markup, or nothing is found.
$effect(() => {
annotations;
tick().then(() => {
const parent = container?.closest(containerClass);
annotationEls = parent ? Array.from(parent.querySelectorAll(annotationClass)) : [];
});
});
/**
* @param {number} i The annotation's index.
* @param {Arrow} arrow
*/
function getArrowPath(i, arrow) {
const el = annotationEls[i];
if (!el) return '';
// Work out where the arrow starts: the spot on the annotation div named
// by `source.anchor`, plus any offset
const arrowSource = getElPosition(el);
const sourceCoords = arrow.source.anchor.split('-').map((q, j) => {
const { css, dimension, position } = lookups[j];
// 'middle' is halfway along the side. Anything else names an edge of the box.
const point =
q === 'middle'
? arrowSource[css] + arrowSource[dimension] / 2
: arrowSource[/** @type {'left'|'right'|'top'|'bottom'} */ (q)];
return (
point +
parseCssValue(arrow.source[`d${position}`], j, arrowSource.width, arrowSource.height)
);
});
// Default to clockwise
const clockwise = typeof arrow.clockwise === 'undefined' ? true : arrow.clockwise;
// Work out where the arrow ends. A percentage string like '50%' is
// measured against the chart. Anything else is a data value that goes
// through the x and y scales.
const targetCoords = [
arrow.target.x || k.x(arrow.target),
arrow.target.y || k.y(arrow.target)
].map((q, j) => {
const val =
typeof q === 'string' && q.includes('%')
? parseCssValue(q, j, k.width, k.height)
: j
? k.yScale(q)
: k.xScale(q);
return val + parseCssValue(arrow.target[`d${lookups[j].position}`], j, k.width, k.height);
});
// Draw the arc from source to target
const arc = swoopyArrow();
arc.angle(Math.PI / 2);
arc.clockwise(clockwise);
arc.x(q => q[0]);
arc.y(q => q[1]);
return arc([sourceCoords, targetCoords]);
}
</script>
<g bind:this={container}>
{#if annotations.length}
<g class="swoops">
{#each annotations as anno, i}
{#if anno.arrows}
{#each anno.arrows as arrow}
<path marker-end="url(#arrowhead)" d={getArrowPath(i, arrow)}></path>
{/each}
{/if}
{/each}
</g>
{/if}
</g>
<style>
.swoops {
position: absolute;
max-width: 200px;
line-height: 14px;
}
.swoops path {
fill: none;
stroke: #000;
stroke-width: 1;
}
</style><!--
@component
Generates an SVG `<marker>` with a triangle for an arrowhead. Add it through the `defs` snippet of the `<Svg>` layout, then point a path's `marker-end` at `url(#arrowhead)`.
-->
<script>
/**
* @typedef {Object} Props
* @property {string} [fill='#000'] - The arrowhead's fill color.
* @property {string} [stroke='#000'] - The arrowhead's stroke color.
*/
/** @type {Props} */
let { fill = '#000', stroke = '#000' } = $props();
</script>
<marker id="arrowhead" viewBox="-10 -10 20 20" markerWidth="17" markerHeight="17" orient="auto">
<path d="M-6,-6 L 0,0 L -6,6" {fill} {stroke} />
</marker>// Helper functions for creating swoopy arrows
/**
* Turn a length into a number of pixels. A number is returned as is. `'12px'`
* becomes 12. `'50%'` is measured against the chart size. `i` says which side
* to measure against: 0 for width and 1 for height, the same order as [x, y].
* @param {string|number|null|undefined} d
* @param {number} i
* @param {number} width
* @param {number} height
* @returns {number}
*/
export function parseCssValue(d, i, width, height) {
if (!d) return 0;
if (typeof d === 'number') {
return d;
}
if (d.indexOf('%') > -1) {
return (+d.replace('%', '') / 100) * (i ? height : width);
}
return +d.replace('px', '');
}
/**
* Find where an element sits inside its parent. That's the spot an arrow points
* at. getBoundingClientRect measures from the top of the page, so subtract the
* parent's position to get coordinates the arrows can use.
* @param {Element} el
* @returns {{ top: number, right: number, bottom: number, left: number, width: number, height: number }}
*/
export function getElPosition(el) {
const annotationBbox = el.getBoundingClientRect();
const parentBbox = (el.parentElement ?? el).getBoundingClientRect();
const coords = {
top: annotationBbox.top - parentBbox.top,
right: annotationBbox.right - parentBbox.left,
bottom: annotationBbox.bottom - parentBbox.top,
left: annotationBbox.left - parentBbox.left,
width: annotationBbox.width,
height: annotationBbox.height
};
return coords;
}
// Draws the curved arrow itself. Adapted from bizweekgraphics/swoopyarrows.
export function swoopyArrow() {
let angle = Math.PI;
let clockwise = true;
/** @type {(d: any) => number} */
let xValue = d => d[0];
/** @type {(d: any) => number} */
let yValue = d => d[1];
/**
* @param {number} a
* @param {number} b
* @returns {number}
*/
function hypotenuse(a, b) {
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
/**
* @param {any[]} data
* @returns {string}
*/
function render(data) {
data = data.map(d => {
return [xValue(d), yValue(d)];
});
// The arrow is a piece of a circle. The next three lines work out which
// circle. Start with the straight-line distance between the two points.
// The arc bows away from that line.
const h = hypotenuse(data[1][0] - data[0][0], data[1][1] - data[0][1]);
// How far the circle's center sits from that straight line. A wider
// `angle` means a flatter arc and a center that sits further back.
const d = h / (2 * Math.tan(angle / 2));
// The distance from the center to either endpoint is the circle's radius.
const r = hypotenuse(d, h / 2);
// Write the arc out as an SVG path. Here is what each part of an example
// path `M 200,50 a 50,50 0 0,1 100,0` means:
//
// M 200,50 start at (200,50)
// a draw an arc
// 50,50 the two radii. Equal radii make it a circle
// 0 the x-axis rotation. It has no effect on a circle
// 0,1 large-arc-flag 0 and sweep-flag 1: take the short way, clockwise
// 100,0 end 100 to the right and level with the start, at (300,50)
//
// Full syntax: http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands
const path =
'M ' +
data[0][0] +
',' +
data[0][1] +
' a ' +
r +
',' +
r +
' 0 0,' +
(clockwise ? '1' : '0') +
' ' +
(data[1][0] - data[0][0]) +
',' +
(data[1][1] - data[0][1]);
return path;
}
/** @param {number} [_] */
render.angle = function renderAngle(_) {
if (!arguments.length) return angle;
angle = Math.min(Math.max(/** @type {number} */ (_), 1e-6), Math.PI - 1e-6);
return render;
};
/** @param {boolean} [_] */
render.clockwise = function renderClockwise(_) {
if (!arguments.length) return clockwise;
clockwise = !!_;
return render;
};
/** @param {(d: any) => number} [_] */
render.x = function renderX(_) {
if (!arguments.length) return xValue;
xValue = /** @type {(d: any) => number} */ (_);
return render;
};
/** @param {(d: any) => number} [_] */
render.y = function renderY(_) {
if (!arguments.length) return yValue;
yValue = /** @type {(d: any) => number} */ (_);
return render;
};
return render;
}year,value 1979,2 1980,3 1981,5 1982,8 1983,18