A column chart with negative and positive values. The yDomain function stretches the measured domain so it always includes zero, yPadding leaves room for the labels, and a c scale colors each column by whether its value is up or down. The children snippet receives the chart context, so the zero line can be drawn with the y scale.
+page.svelte
./_components/Column.svelte
./_components/AxisX.svelte
./_components/AxisY.svelte
./_data/yearChanges.csv
<script>import { LayerCake, Svg } from'layercake';
import { scaleBand } from'd3-scale';
importColumnfrom'./_components/Column.svelte';
importAxisXfrom'./_components/AxisX.svelte';
importAxisYfrom'./_components/AxisY.svelte';
// The CSV rows are parsed, and their numbers typed, by @rollup/plugin-dsv. See vite.config.jsimport data from'./_data/yearChanges.csv';
const xKey = 'year';
const yKey = 'change';
</script><divclass="chart-container"><!--
The columns grow out of zero, so zero has to be inside the domain. The
`yDomain` function receives the [min, max] measured from the data and
stretches whichever end doesn't reach zero. It works whether the numbers
are all positive, all negative or a mix.
The `c` scale turns each row's "up" or "down" into a color for the
Column component.
`yPadding` adds 18 pixels of room at each end so the numbers on the
longest columns fit.
--><LayerCakepadding={{ top: 10, bottom: 20, left: 25 }}x={xKey}y={yKey}xScale={scaleBand().paddingInner(0.05).round(true)}yDomain={([min, max]) => [Math.min(0, min), Math.max(0, max)]}yPadding={[18, 18]}c={d => (d[yKey] < 0 ? 'down' : 'up')}cDomain={['up', 'down']}cRange={['#00e047', '#ff00cc']}{data}
>{#snippet children(k)}<Svg><AxisXgridlines={false}tickMarkssnapLabels /><AxisY /><ColumnshowLabels /><!-- Columns run up and down from here, so mark it --><lineclass="zero"x1={k.xRange[0]}x2={k.xRange[1]}y1={k.yScale(0)}y2={k.yScale(0)} /></Svg>{/snippet}</LayerCake></div><style>/* Give the wrapper a width and height. LayerCake fills it. */.chart-container {
width: 100%;
height: 250px;
}
.zero {
stroke: #333;
}
</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 */functiongetFill(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 */functioncolumnWidth(d) {
const vals = k.xGet(d);
returnMath.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><gclass="column-group">{#each k.dataas 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)}<rectclass="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.
--><textx={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 SVG x-axis along the bottom of the chart. If the x scale is a band scale, each tick sits in the middle of its band.
--><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=12] - Vertical offset of the label in pixels.
*//** @type {Props} */let {
tickMarks = false,
gridlines = true,
tickMarkLength = 6,
showBaseline = false,
snapLabels = false,
format = d => d,
ticks = undefined,
tickGutter = 0,
dx = 0,
dy = 12
} = $props();
// Snapped labels anchor the first tick to the left edge and the last to the right/** @param {number} i */functiontextAnchor(i) {
if (snapLabels === true) {
if (i === 0) {
return'start';
}
if (i === tickVals.length - 1) {
return'end';
}
}
return'middle';
}
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><gclass="axis x-axis"class:snapLabels>{#if showBaseline === true}<lineclass="baseline"y1={k.height}y2={k.height}x1="0"x2={k.width} />{/if}{#each tickVals as tick, i (tick)}<!-- Fall back to the chart height if the chart has no y dimension --><gclass="tick tick-{i}"transform="translate({k.xScale(tick)},{k.yRange ? Math.max(...k.yRange) : k.height})"
>{#if gridlines === true}<lineclass="gridline"x1={halfBand}x2={halfBand}y1={-k.height}y2="0" />{/if}{#if tickMarks === true}<lineclass="tick-mark"x1={halfBand}x2={halfBand}y1={tickGutter}y2={tickGutter + tickLen}
/>{/if}<textx={halfBand}y={tickGutter + tickLen}{dx}{dy}text-anchor={textAnchor(i)}
>{format(tick)}</text
>
</g>{/each}</g><style>.tick {
font-size: 11px;
}
line,
.tickline {
stroke: #aaa;
stroke-dasharray: 2;
}
.ticktext {
fill: #666;
}
.tick.tick-mark,
.baseline {
stroke-dasharray: 0;
}
/* Push the snapped end labels 3px outward so they clear the chart edge */.axis.snapLabels.tick:last-childtext {
transform: translateX(3px);
}
.axis.snapLabels.tick.tick-0text {
transform: translateX(-3px);
}
</style>
<!--
@component
Generates an SVG y-axis along the left edge of the chart. If the y scale is a band scale, each tick sits in the middle of its band.
--><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=0] - 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).
*//** @type {Props} */let {
tickMarks = false,
labelPosition = 'even',
snapBaselineLabel = false,
gridlines = true,
tickMarkLength = undefined,
format = d => d,
ticks = 4,
tickGutter = 0,
dx = 0,
dy = 0,
charPixelWidth = 7.25
} = $props();
/** @param {number} sum
* @param {string} val */functioncalcStringLength(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 maxTickValPx = $derived(Math.max(...tickVals.map(k.yScale)));
</script><gclass="axis y-axis">{#each tickVals astick (tick)}{@const tickValPx = k.yScale(tick)}<!-- Fall back to the left edge if the chart has no x dimension --><gclass="tick tick-{tick}"transform="translate({k.xRange ? k.xRange[0] : 0}, {tickValPx})">{#if gridlines === true}<lineclass="gridline"{x1}x2={k.width}y1={halfBand}y2={halfBand}></line>{/if}{#if tickMarks === true}<lineclass="tick-mark"{x1}x2={x1 + tickLen}y1={halfBand}y2={halfBand}></line>{/if}<textx={x1}y={halfBand}dx={dx + (labelPosition === 'even' ? -3 : 0)}text-anchor={labelPosition === 'above' ? 'start' : 'end'}dy={dy +
(labelPosition === 'above' || (snapBaselineLabel === true && tickValPx === maxTickValPx)
? -3
: 4)}>{format(tick)}</text
>
</g>{/each}</g><style>.tick {
font-size: 11px;
}
.tickline {
stroke: #aaa;
}
.tick.gridline {
stroke-dasharray: 2;
}
.ticktext {
fill: #666;
}
/* A solid line at the zero tick */.tick.tick-0line {
stroke-dasharray: 0;
}
</style>