Chart 3D

The container, camera, axes and tooltip that every 3D chart builds on.

chart-3d is the core the other charts install with it. Use it directly to draw your own d3-3d shapes in the chart box: useChart3D hands you the camera, Axes3D draws the box, Marks3D draws your shapes with every renderer and shade lights a face. A container takes more than one Marks3D - a chart and marks of your own beside it - and paints each set over the ones before it in the tree, on every renderer.

-101-101-101-101-101-101-101-101-101-101-101-101

Installation

npx shadcn@latest add niekes/chart3dcn/chart-3d#v1.2.0

Renderers

The marks of a chart - its bars, points and faces - are drawn by the renderer of the container. "svg", the default, draws them as SVG elements; "canvas" paints them on a canvas, for charts with many marks.

<ChartContainer3D config={chartConfig} renderer="canvas">

The box, its labels, the tooltip, the legend and the gizmo stay SVG and HTML with every renderer. A chart draws as SVG on the server and until the browser shows it has a canvas, and stays SVG where it has none.

Shortcuts

Press ? on a chart, or the keyboard button in its corner, for the shortcuts that rotate, pan, zoom and reset it; Escape or a click outside closes the panel again. Each row names its action, then lists its keys and - past a thin rule - its pointer gestures, with the drag written out as "Drag". The platform modifier and a drag rotate - ⌘ on a Mac, Ctrl on Windows and Linux; a plain drag only inspects, with the default cursor - Alt (⌥ on a Mac) and a drag pans, the platform modifier with the wheel zooms to the cursor - a trackpad pinch arrives as Ctrl and the wheel, so it zooms on every platform - and a double click resets; the wheel alone scrolls the page. On a touch screen two fingers turn the chart and pinch it to the point between them, while one finger scrolls the page and inspects. A drag that turns nothing - without the modifier, or one finger sideways - shows a hint in the middle of the chart for a moment, over a light veil, the gesture that would have turned it, as the panel names it; the veil is data-slot="chart-3d-hint", the box in it data-slot="chart-3d-hint-box", and it shows nothing where keymap has that gesture off. The cursor names the gesture: a hand while the platform modifier is held, grabbing while the drag turns, the four arrows while Alt is held, zoom-in or zoom-out while the wheel zooms. See ADR-0001. shortcuts={false} hides the button. The chart announces its keys to screen readers through aria-keyshortcuts, and the keys in the panel carry data-slot="kbd", as the Kbd of shadcn/ui does, so className="[&_[data-slot=kbd]]:bg-background" on the container restyles them. The button is data-slot="chart-3d-shortcuts-trigger", the list data-slot="chart-3d-shortcuts-panel", and the corner that holds both data-slot="chart-3d-shortcuts".

Keymap

keymap rebinds, renames or turns off every action, over its defaults. Keep it outside the component, so it stays the same object between renders.

const keymap: Keymap3D = {
  rotateLeft: ["a", "ArrowLeft"], // new keys; the panel shows the first
  zoomIn: { keys: ["Control+Plus"], label: "Vergrößern" },
  reset: false, // the action is off
  wheelZoom: false, // so is the gesture, and the modifier with the wheel zooms the page
  help: { label: "Tastenkürzel" }, // the name of the button and of its row
}

<ChartContainer3D config={chartConfig} keymap={keymap}>

keymap={false} turns everything off: the chart stands still, leaves the tab order and shows no button. The panel lists the actions that are on, one row per label, so actions that share a label share a row.

ActionDefault keysLabel
dragRotate⌘/Ctrl and dragRotate
touchOrbitTwo-finger dragRotate
rotateLeftArrowLeftRotate
rotateRightArrowRightRotate
rotateUpArrowUpRotate
rotateDownArrowDownRotate
dragPanAlt/⌥ and dragPan
panLeftShift+ArrowLeftPan
panRightShift+ArrowRightPan
panUpShift+ArrowUpPan
panDownShift+ArrowDownPan
zoomInPlus, =Zoom
zoomOut-Zoom
wheelZoom⌘/Ctrl and the wheelZoom
pinchZoomPinchZoom
reset0Reset
doubleClickResetDouble-clickReset
help?Keyboard shortcuts

Keys are written the way aria-keyshortcuts writes them: the modifiers Control, Alt, Meta and Shift, then the key of the press, joined by +, with Plus for the plus key and Space for the space bar. A press matches only with exactly the modifiers of its keys, so Ctrl and 0 still resets the zoom of the browser. Shift counts beside a named key such as ArrowLeft; a character such as ? is typed with it already, so "?" matches without it. The gestures can be turned off and renamed, but not rebound.

The keys work only while the chart has the focus, and every one can be turned off or rebound, as WCAG 2.1.4 asks of shortcuts with a single character.

Gizmo

The axes in the lower left corner turn with the camera, so a turned chart still shows which way is up and where its axes point. They neither pan nor zoom. gizmo moves them to another corner, gizmo={false} hides them.

<ChartContainer3D config={chartConfig} gizmo="top-left">

The gizmo is data-slot="chart-3d-gizmo", drawn in --muted-foreground and hidden from screen readers. Each axis draws in currentColor and carries data-axis, so className="[&_[data-axis=x]]:text-red-500" on the container colors one axis.

View

defaultView is where a reset returns the camera, and where it starts without a view. view is a heading the page gives the camera: it starts there, and when the view changes it glides there over the animationDuration, in step with the data - where the reader asks for reduced motion, it jumps. A view moves only what it names, so one of yaw and tilt keeps the zoom and the pan of the reader, and it is no lock: the reader turns the camera on from it, and the same view handed in again moves nothing.

<ChartContainer3D config={chartConfig} view={facing(place.lon, place.lat)}>
  <RoutesChart3D data={stops} land={land} lon="lon" lat="lat" />
</ChartContainer3D>

facing(lon, lat) is the view that looks at a place on a globe. The routes chart uses both for a tour that turns the globe to its next stop. Like every part of the charts, facing runs on the client: call it in a client component, or hand defaultView or view the yaw and tilt it returns - a server component of Next.js cannot call it.

Tooltip

The tooltip of a mark follows the pointer, above and to its right. Where it would leave the chart it flips to the other side - on each axis alone, and only to a side with more room - and glides there; where the reader asks for reduced motion, it jumps. placement puts it in another corner of the pointer (ADR-0005).

<ChartContainer3D config={chartConfig} placement="bottom-left">

The tooltip is data-slot="chart-3d-tooltip", and its data-placement names the corner it took, flipped or not - "top-left", "top-right", "bottom-left" or "bottom-right" - so CSS can style each corner. To square the corner that points at the pointer:

<ChartContainer3D
  config={chartConfig}
  className="[&_[data-placement=top-right]]:rounded-bl-none [&_[data-placement=top-left]]:rounded-br-none [&_[data-placement=bottom-right]]:rounded-tl-none [&_[data-placement=bottom-left]]:rounded-tr-none"
>

What a mark says is built from the data behind it, its values as the ticks name them through format, until tooltip on the chart says otherwise: a function of what the mark would say - a title and its items, a label and a value each - and of the data behind the mark, in the words of the chart's props: the entry and series key of a bar, the entry of a point, the key and the spanned entries of a face of a ribbon, the row, column and value of a cell. It runs when the pointer lands on the mark, and null shows none (ADR-0006).

<BarChart3D
  data={data}
  index="month"
  tooltip={(tooltip, { entry, key }) => ({
    ...tooltip,
    title: `${entry.month} · ${key}`,
    items: tooltip.items.map((item) => ({ ...item, value: <>{item.value} €</> })),
  })}
/>

Focus

A mark can name the groups it belongs to in groups. Pointing at a mark lights the fill of every mark that shares one of its groups - the faces of a bar, the faces of a tile of the globe - in the focus color: --chart-3d-focus, or its own fill lightened (see Theming). A stroke of the mark's own stays, and nothing else changes, so the order the marks paint in, and with it the depth, stays as it was, on the canvas too. Off the mark or off the chart the focus clears; through a drag that turns the chart it stays, so what is in focus can be followed from every side. Marks without groups never light.

// The faces of a bar share its key, so pointing at one lights the whole bar.
const marks = cubeMarks(key, faces, color, tooltip).map((mark) => ({ ...mark, groups: [key] }))

Labels

The labels of the box sit beside their ticks, away from the box, and slide round them as the camera turns. Where two would touch, they slide apart along their axis, and where that is not enough, every other one moves to a second row; only an axis seen nearly end on shows every second, fourth… label. A label gives way to one of an axis with fewer ticks, whose labels say more each. When an axis moves to another edge of the box, its labels fade from one edge to the other.

The arrow keys glide the camera to its next view instead of jumping there. Where the reader asks for reduced motion, the camera jumps and the labels move without a transition.

Transitions

A chart glides into new data over the animationDuration of its container; 0 makes it jump, and so does a reader who asks for reduced motion. The glide happens in the numbers, before the projection - useTween eases them from the ones on screen - so the camera answers at once, mid-glide too. Every key moves as its own mark (Enter in the glossary):

  • A key the data brings starts at its enter value: a new bar grows out of the floor, at its place, and fades in as it grows.
  • A key that stays glides from where it stands to its new number - also to a new place, when the data reorders.
  • A key the data drops glides back to its enter value, the mirror of its entering, and leaves when the glide is done: a removed bar shrinks back into the floor and fades out as it shrinks, so nothing flat pops away at the end.

The enter value is one number for every key, or a function that finds it among numbers, such as that of a neighbour: a point of the line and the routes chart starts on its neighbour where that is on screen, and a dropped one heads for the nearest that stays. A glide starts from the numbers on screen, so data that comes while a chart is on its way moves every mark on from where it is. Every change of the data starts the glide anew, though, so a feed that comes faster than the animationDuration leaves the marks trailing behind it, and a mark the feed dropped goes, wherever it has come to, with the first change the time of a glide after it left: give such a chart a duration shorter than the interval of its feed, or 0.

A mark fades with faded(color, opacity), a color-mix with transparent that every renderer draws: tween an opacity per key with useTween - 1, with 0 as the enter value - and fade the color after shade.

The axes glide along (useTweenAxes): their ends ease instead of jumping from one round number to the next, a tick that stays glides as the same label, an entering one fades in, and a dropped one fades out - in place, or as the gliding end sweeps past it - while the line of the axis grows to a new outermost tick and shrinks from a dropped one. The bar chart's Update and Enter-and-leave demos show all of it; a chart of your own gets the same behaviour by tweening its numbers with useTween and its axes with useTweenAxes before it projects.

Legend

legend shows the label and the color of every config key below the chart. ChartLegend3D is the same legend on its own, for anywhere else on the page, such as one legend for two charts that share a config. It scopes the colors of its config itself, so its swatches match the charts.

<div className="flex flex-col gap-2">
  <ChartLegend3D config={chartConfig} />
  <ChartContainer3D config={chartConfig}>
    <BarChart3D data={thisYear} index="month" />
  </ChartContainer3D>
  <ChartContainer3D config={chartConfig}>
    <BarChart3D data={lastYear} index="month" />
  </ChartContainer3D>
</div>

Props

A prop means the same in every chart that takes it, so the next chart reads like the last, and a new chart takes these names (ADR-0012).

PropWhat it isCharts
dataThe entries, a table with an entry per row, or the grid of numbers data[row][column]every chart
indexThe field of the category of an entry along x: its name on the axis and in the tooltip, and what its marks follow through new databar, area
keysThe fields that each hold a series, in a wide tablebar, area
stackThe name of the stack of a key: keys of the same name stand on one another in one row along zbar
seriesThe field whose value is the config key of the series of an entry, in a long tablescatter, line, routes, places, globe, choropleth, donut
x, y, zThe position along each axis: a field of the entry; in a grid, x and z are the positions of the columns and rowsscatter, line; bar field and surface x, z
domainThe values the first and the last column (x) and row (z) of a grid stand forbar field, surface
lon, latThe fields of the place of an entry, in degreesroutes, places, globe
valueThe field of the value of an entryplaces, globe, choropleth, donut
idThe field that identifies an entry: what its marks follow through new data, within its series, in the choropleth its region. In the places, the routes and the donut chart it names the entry in the tooltip tooscatter, line, routes, places, choropleth, donut
labelThe field that titles the tooltip of an entry, and nothing elseglobe, choropleth
landThe regions of the earth under the marks, a GeoJSON feature collectionroutes, places, globe, choropleth
formatHow a number reads, keyed by what it formats: by axis where the chart has axes - the x of a category axis takes the category - and by field, value, elsewhereevery chart but routes
titlesThe titles of the axes, by axisthe charts with axes
colorsThe config keys of the colors at the lowest and the highest valueline, bar field, surface
radiusThe radius of a point, or of the largest dot, in the units of the view boxscatter, places
tooltipWhat a mark says on hover, from what it would say and the data behind itevery chart
placementThe corner beside the pointer the tooltip sits atthe container

Stability

From 1.0.0 the package follows semver for what a chart is used with: the charts and their props, ChartContainer3D and its props, ChartLegend3D, and the types they take - ChartConfig, Symbol3D, View3D, Renderer3D, Keymap3D, KeyAction3D, Gesture3D and Tooltip3D - and facing, the view a page hands defaultView or view. So does what a stylesheet styles a chart by, on the Theming page: the names of the data-slots, the data-* attributes beside them and the CSS variables. A change to any of them that breaks a project waits for a major version.

What a chart is built from stays free to change in a minor version, with an entry in the changelog: Axes3D, Marks3D, Labels3D, useChart3D, useTween, useTweenAxes, useSeries, useTooltips, Mark3D, Label3D, World, GeoProjectionLike and the helpers axis, entryTicks, pad, linear, worldBox, intoWorld, shade, faded, colorOf, finite, keyOf, joined, nonNegative, cubeMarks, barCorners, barMarks, floored, gridAxis, ramp, globe, placeOf, azimuth, azimuthAt, placeAt, GLOBE_RADIUS, orthographic, earth, usePoints, pointTooltip, useConfigKeys, useRuns, segment and uniqueIds. They are exported so a chart of your own can draw the way the charts here do; pin the version of the package, or own a copy through the registry, if you build on them.

API Reference

ChartContainer3D

Takes the props of a div as well.

Prop

Type

View3D

Prop

Type

Symbol3D

The picture a chart draws for a config key, as the symbol of that key: the tip of a route.

Prop

Type

Mark3D

One shape that Marks3D draws, in paint order: a polygon, unless its shape says "circle", which takes the radius r, or "symbol", which takes r, the symbol and, to turn it, the point it comes from.

Prop

Type

Label3D

A label that Labels3D draws beside a mark.

Prop

Type

Edit on GitHub

On this page