Grouped column
1979
1980
1981
1982
1983
0
5
10
15
A grouped column chart using the x2 nested dimension. x2 is a band scale whose range is one x band wide, so setting x2="fruit" positions each column inside its group with no extra code.
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 x2 band is in percent as well, so the columns inside each group share the ScaledSvg's units.
- +page.svelte
- ./_components/ColumnGrouped.svelte
- ./_components/AxisX.percent-range.html.svelte
- ./_components/AxisY.percent-range.html.svelte
- ./_data/yearGroupsLong.js
<script>
import { LayerCake, ScaledSvg, Html } from 'layercake';
import { scaleBand } from 'd3-scale';
import ColumnGrouped from './_components/ColumnGrouped.svelte';
import AxisX from './_components/AxisX.percent-range.html.svelte';
import AxisY from './_components/AxisY.percent-range.html.svelte';
// A flat list of rows, one per column: { year, fruit, value }
import data from './_data/yearGroupsLong.js';
const xKey = 'year';
const x2Key = 'fruit';
const yKey = 'value';
const seriesColors = ['#ff00cc', '#00ccff', '#ffcc00'];
// With `percentRange` on, the x2 band is measured in percent, so the columns inside
// each group share the ScaledSvg's units.
// `x2="fruit"` is all it takes to position columns within each group. x2 is
// a scaleBand by default. Its domain comes from the data and its range is
// one x band wide. Pass `x2Scale` to customize the padding, for example
// `x2Scale={scaleBand().paddingInner(0.1)}`. You could also skip `x2` and
// build that band scale inside your own component.
</script>
<div class="chart-container">
<LayerCake
ssr
percentRange
padding={{ top: 10, bottom: 20, left: 20 }}
x={xKey}
x2={x2Key}
y={yKey}
c={x2Key}
xScale={scaleBand().paddingInner(0.1)}
yDomain={[0, null]}
cRange={seriesColors}
{data}
>
<Html>
<AxisX gridlines={false} />
<AxisY snapBaselineLabel />
</Html>
<ScaledSvg>
<ColumnGrouped />
</ScaledSvg>
</LayerCake>
</div>
<style>
/* Give the wrapper a width and height. LayerCake fills it. */
.chart-container {
width: 100%;
height: 250px;
}
</style><!--
@component
Generates an SVG grouped column chart using the `x2` nested scale for the within-group position and the `c` scale for color.
-->
<script>
import { getLayerCakeContext } from 'layercake';
const k = getLayerCakeContext();
/**
* @typedef {Object} Props
* @property {string} [fill] - The shape's fill color. By default the color is read from the `c` scale.
* @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';
}
// This chart needs the x2 scale. A chart might not set one, so fall back
// to a zero-width column instead of crashing.
let columnWidth = $derived.by(() => {
const scale = k.x2Scale;
if (scale?.bandwidth) return scale.bandwidth();
const range = k.x2Range ?? [0, 0];
return Math.abs(range[1] - range[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 xPos = k.xGet(d) + (k.x2Get?.(d) ?? 0)}
{@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={columnWidth}
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 + columnWidth / 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] - Formats a tick value for display. Defaults to the scale's tickFormat for time scales, otherwise d => d.
* @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,
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);
let isTime = $derived(
k.xScale.domain()[0] instanceof Date && typeof k.xScale.tickFormat === 'function'
);
/** @type {(d: any) => string} */
let formatTick = $derived(
format ?? (isTime ? k.xScale.tickFormat(typeof ticks === 'number' ? ticks : undefined) : d => d)
);
</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)"
>
{formatTick(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] - Formats a tick value for display. Defaults to the scale's tickFormat for time scales, otherwise d => d.
* @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,
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 isTime = $derived(
k.yScale.domain()[0] instanceof Date && typeof k.yScale.tickFormat === 'function'
);
/** @type {(d: any) => string} */
let formatTick = $derived(
format ?? (isTime ? k.yScale.tickFormat(typeof ticks === 'number' ? ticks : undefined) : d => d)
);
let widestTickLen = $derived(
Math.max(
10,
Math.max(...tickVals.map(d => formatTick(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))"
>
{formatTick(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>export default [
{ year: '1979', fruit: 'apples', value: 2 },
{ year: '1979', fruit: 'bananas', value: 15 },
{ year: '1979', fruit: 'cherries', value: 8 },
{ year: '1980', fruit: 'apples', value: 3 },
{ year: '1980', fruit: 'bananas', value: 10 },
{ year: '1980', fruit: 'cherries', value: 9 },
{ year: '1981', fruit: 'apples', value: 5 },
{ year: '1981', fruit: 'bananas', value: 8 },
{ year: '1981', fruit: 'cherries', value: 11 },
{ year: '1982', fruit: 'apples', value: 8 },
{ year: '1982', fruit: 'bananas', value: 5 },
{ year: '1982', fruit: 'cherries', value: 12 },
{ year: '1983', fruit: 'apples', value: 18 },
{ year: '1983', fruit: 'bananas', value: 3 },
{ year: '1983', fruit: 'cherries', value: 14 }
];