Chart
newCharts on Unovis. A container that turns a config into series colours, a crosshair that reports the hovered point, a tooltip that is a real Vue component, and a legend that can hide a series.
Click a legend item to hide its series. The tooltip follows the pointer and a finger alike.
Chart is Unovis plus five parts. You compose the Unovis components yourself, VisXYContainer, VisArea, VisAxis, VisDonut and the rest, and the parts give them the theme's colours, a tooltip and a legend. The Area, Bar, Line and Tooltip galleries show the parts at work.
Installation
The item installs @unovis/vue and @unovis/ts.
Your first chart
Start from the data and a config. The config names each series, gives it a label and a colour, and the container writes every colour as --color-<key>:
<script setup lang="ts">
import { VisArea, VisAxis, VisXYContainer } from "@unovis/vue";
import { type ChartConfig, ChartContainer, ChartCrosshair, ChartLegend, ChartTooltip, ChartTooltipContent, chartColors } from "@/components/ui/chart";
type Month = { month: Date; desktop: number; mobile: number };
const data: Month[] = [
{ month: new Date(2024, 0, 1), desktop: 186, mobile: 80 },
{ month: new Date(2024, 1, 1), desktop: 305, mobile: 200 },
{ month: new Date(2024, 2, 1), desktop: 237, mobile: 120 },
];
const config = {
desktop: { label: "Desktop", color: "var(--chart-1)" },
mobile: { label: "Mobile", color: "var(--chart-2)" },
} satisfies ChartConfig;
const keys = ["desktop", "mobile"];
const x = (d: Month) => d.month;
const y = [(d: Month) => d.desktop, (d: Month) => d.mobile];
const color = chartColors(keys);
</script>
<template>
<ChartContainer :config="config" class="aspect-auto h-64 w-full">
<VisXYContainer :data="data">
<VisArea :x="x" :y="y" :color="color" />
<VisAxis type="x" :x="x" />
<ChartCrosshair :x="x" :y-stacked="y" :color="color" />
</VisXYContainer>
<ChartTooltip>
<ChartTooltipContent />
</ChartTooltip>
<ChartLegend />
</ChartContainer>
</template>
Areas and stacked bars stack their series, so the crosshair takes y-stacked; lines, scatter and grouped bars take y. Left out, the crosshair reads them from the chart's components.
The container takes its width from its parent, never from what it draws, and is 16:9 by default. A chart with a fixed height takes aspect-auto as well, or the ratio turns that height into a minimum width.
Four rules keep a chart fast:
- Accessors, formatters and
svgDefsare constants in<script setup>. Unovis compares functions by identity, so an arrow written in the template is new on every render and redraws the whole chart with its 600ms transition. - Replace the data array; a mutation in place is not seen.
- Dates are built with
new Date(year, month, day). A"YYYY-MM-DD"string parses as UTC and lands a day early in western time zones. - Many charts on one page take
lazyon the container: the slot mounts when it scrolls near.
Config
type ChartConfig = Record<string, {
label?: string | Component;
icon?: Component;
color?: string;
theme?: { light: string; dark: string };
}>;
color is any CSS colour; the theme tokens var(--chart-1) to var(--chart-5) switch with the mode. A theme pair becomes light-dark(light, dark). A key must be a valid CSS identifier, so desktop, not desktop.total: the container warns in development.
chartColors(keys) returns an Unovis colour accessor that reads --color-<key> by series index, for the y arrays of areas, lines and bars. A single series writes the variable directly: :color="'var(--color-desktop)'".
Theming
The five series tokens ship with the tokens item, light and dark separately, in a fixed order that keeps every neighbouring pair apart under colour-vision deficiency. fill-chart-1 to fill-chart-5 and the bg- and stroke- forms exist as classes.
Unovis' own variables (--vis-axis-*, --vis-crosshair-*, --vis-donut-*, --vis-radial-bar-*) are mapped onto the tokens on the chart root: ticks in --muted-foreground, grid and domain lines in --border, donut and radial backgrounds in --muted, segments separated by a 2px --background stroke. Override one with a class on the container, [--vis-donut-segment-stroke-width:0].
Tooltip
ChartCrosshair listens to the pointer and reports the hovered point; ChartTooltip positions its content beside the pointer, inside the chart, and flips at the right edge. ChartTooltipContent lists the config keys found in the datum, in config order, with a zero shown as 0. Its props and slots are on the Tooltip gallery.
A chart the crosshair cannot follow, with no x axis or with bars on their side (a pie, a radial, a horizontal bar), feeds the tooltip from Unovis events. ChartContainer hands events to its slot: events(selector) returns the events object for the Unovis component whose marks carry that selector, Donut.selectors.segment or StackedBar.selectors.bar, and the same object every time, so it can sit in the template:
<script setup lang="ts">
import { Donut } from "@unovis/ts";
import { VisDonut, VisSingleContainer } from "@unovis/vue";
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";
</script>
<template>
<ChartContainer :config="config">
<template #default="{ events }">
<VisSingleContainer :data="data">
<VisDonut :value="value" :color="color" :events="events(Donut.selectors.segment)" />
</VisSingleContainer>
<ChartTooltip>
<ChartTooltipContent name-key="browser" hide-label />
</ChartTooltip>
</template>
</ChartContainer>
</template>
A pointer and a finger both open the tooltip. A component rendered inside ChartContainer gets the same function from useChart(). Unovis binds events up to half a second after a render, so the first hover right after mount can be missed.
Legend
ChartLegend lists the config. With toggle every item is a button that hides its series; the keys arrive through v-model:hidden on the container, and useChartSeries(keys) turns them into y accessors that return null for a hidden series, so the remaining series keep their index and colour. Areas, lines and stacked bars draw nothing for it; grouped bars keep its slot empty, and want :bar-min-height="0" so no 2px stub remains:
<script setup lang="ts">
import { ref } from "vue";
import { useChartSeries } from "@/components/ui/chart";
const hidden = ref<string[]>([]);
const series = useChartSeries<Month>(["desktop", "mobile"], hidden);
</script>
<template>
<ChartContainer :config="config" v-model:hidden="hidden">
<VisXYContainer :data="data">
<VisArea :x="x" :y="series.y.value" :color="series.color" />
</VisXYContainer>
<ChartLegend toggle />
</ChartContainer>
</template>
Without the second argument the hook reads the hidden keys from the chart context, so it must run in a component rendered inside ChartContainer.
Accessibility
The SVG is hidden from assistive technology by Unovis. Give the container a label that says what the chart shows, and put the numbers beside it as a table, visually hidden if the design has no room, so the data is reachable without a pointer.
API Reference
ChartContainer
| Prop | Default | Type and description |
|---|---|---|
| config* | — | ChartConfigThe series: each key maps to a |
| label | undefined | stringAn accessible name for the chart. Sets |
| hidden | undefined | string[]
|
| lazy | false | booleanMounts the slot, and with it Unovis, only once the root comes within 200px of the viewport. The root keeps its height meanwhile. |
| Event | Payload and description |
|---|---|
| update:hidden | [keys: string[]]The hidden series keys after a legend toggle. |
| Slot | Scope and description |
|---|---|
| default | { id: string; events: (selector: string) => ChartEvents; }The Unovis container with its components, plus |
ChartCrosshair
| Prop | Default | Type and description |
|---|---|---|
| x | undefined | NumericAccessor<Datum> | ((datum: Datum, index: number) => Date)The x accessor, as on the chart's components; the tooltip reports its value as |
| y | undefined | NumericAccessor<Datum> | NumericAccessor<Datum>[]The y accessors for the circles, one per series. Passed together with |
| yStacked | undefined | NumericAccessor<Datum>[]The stacked y accessors, for stacked areas and bars. Like |
| color | undefined | ColorAccessor<Datum>The circle colour per series, usually |
| duration | 0 | numberAnimation of the line in milliseconds. |
| snapToData | true | booleanSnap the line to the nearest point. On by default. |
| hideWhenFarFromPointer | false | booleanHide the crosshair, and with it the tooltip, when the pointer is more than 100px from a point. Off by default, so a sparse series keeps its crosshair between points. |
| strokeColor | undefined | ColorAccessor<Datum>The outline colour of the circles, per series; |
| strokeWidth | undefined | NumericAccessor<Datum>The outline width of the circles, per series; |
| circleRadius | undefined | numberRadius of the circle on each series; |
ChartTooltip
| Slot | Scope and description |
|---|---|
| default | { datum?: Record<string, unknown> | undefined; x?: number | Date | undefined; index?: number | undefined; }The content, usually |
ChartTooltipContent
| Prop | Default | Type and description |
|---|---|---|
| hideLabel | — | booleanLeaves the title out. |
| hideIndicator | — | booleanLeaves the colour mark out of every row. |
| indicator | "dot" | "dot" | "line" | "dashed"The colour mark: a |
| nameKey | undefined | stringA field of the datum that names the series, for a pie: with |
| labelKey | undefined | stringA config key whose label is the title, or a field of the datum whose value, looked up in the config, names the title. |
| labelFormatter | undefined | ((x: unknown, datum: ChartDatum) => string)Formats the title from the raw x value (a |
| valueFormatter | undefined | ((value: unknown, key: string, datum: ChartDatum) => string)Formats a row's value from the value, its key and the datum. |
| Slot | Scope and description |
|---|---|
| label | { label: string; }The title, with |
| item | { item: ChartTooltipRow; index: number; datum: ChartDatum; }One row, with |
ChartLegend
| Prop | Default | Type and description |
|---|---|---|
| hideIcon | — | booleanLeaves the swatch or icon out. |
| toggle | — | booleanMakes every item a button that hides or shows its series, with |
Props
- config*
ChartConfigThe series: each key maps to alabel, an optionalicon, and acoloror atheme: { light, dark }pair. The root gets--color-<key>for each, so Unovis accessors can return"var(--color-desktop)". A key must be a valid CSS identifier.- label
undefined stringAn accessible name for the chart. Setsrole="group"andaria-labelon the root; without it the root is a plaindiv.- hidden
undefined string[]v-model:hidden, the keys of the series hidden through the legend. Left unbound the container keeps the state itself.- lazy
false booleanMounts the slot, and with it Unovis, only once the root comes within 200px of the viewport. The root keeps its height meanwhile.
Emits
- update:hidden
[keys: string[]]The hidden series keys after a legend toggle.
Slots
- default
{ id: string; events: (selector: string) => ChartEvents; }The Unovis container with its components, plusChartTooltipandChartLegend. Receives the chartidandevents(selector), which returns a Unoviseventsobject that sets the tooltip's datum when the pointer or a finger is on a mark of that selector; the same object comes back for the same selector.
Props
- x
undefined NumericAccessor<Datum> | ((datum: Datum, index: number) => Date)The x accessor, as on the chart's components; the tooltip reports its value asx. Unovis takes the crosshair's accessors all or none, so passxtogether withyoryStacked, or leave those out: the crosshair then snaps through the chart's components, as the examples do.- y
undefined NumericAccessor<Datum> | NumericAccessor<Datum>[]The y accessors for the circles, one per series. Passed together withx, or left out withyStackedso the crosshair takes them from the chart's components.- yStacked
undefined NumericAccessor<Datum>[]The stacked y accessors, for stacked areas and bars. Likey, passed together withxor not at all.- color
undefined ColorAccessor<Datum>The circle colour per series, usuallychartColors(keys).- duration
0 numberAnimation of the line in milliseconds.0by default, so the line keeps up with the pointer.- snapToData
true booleanSnap the line to the nearest point. On by default.- hideWhenFarFromPointer
false booleanHide the crosshair, and with it the tooltip, when the pointer is more than 100px from a point. Off by default, so a sparse series keeps its crosshair between points.- strokeColor
undefined ColorAccessor<Datum>The outline colour of the circles, per series;--backgroundby default through--vis-crosshair-circle-stroke-color. The line takes--vis-crosshair-line-stroke-color,--borderby default.- strokeWidth
undefined NumericAccessor<Datum>The outline width of the circles, per series;2pxby default through--vis-crosshair-circle-stroke-width. The line takes--vis-crosshair-line-stroke-width.- circleRadius
undefined numberRadius of the circle on each series;0hides them, which bars want.
Slots
- default
{ datum?: Record<string, unknown> | undefined; x?: number | Date | undefined; index?: number | undefined; }The content, usuallyChartTooltipContent. Receives the hovereddatum, itsxandindex.
Props
- hideLabel
booleanLeaves the title out.- hideIndicator
booleanLeaves the colour mark out of every row.- indicator
"dot" "dot" | "line" | "dashed"The colour mark: adot, a verticallineor adashedline.- nameKey
undefined stringA field of the datum that names the series, for a pie: withnameKey="browser"the row{ browser: "chrome", visitors: 275 }reads the label and colour ofconfig.chrome.- labelKey
undefined stringA config key whose label is the title, or a field of the datum whose value, looked up in the config, names the title.- labelFormatter
undefined ((x: unknown, datum: ChartDatum) => string)Formats the title from the raw x value (aDatestays aDate) and the datum.- valueFormatter
undefined ((value: unknown, key: string, datum: ChartDatum) => string)Formats a row's value from the value, its key and the datum.toLocaleString()by default.
Slots
- label
{ label: string; }The title, withlabel.- item
{ item: ChartTooltipRow; index: number; datum: ChartDatum; }One row, withitem(key,name,label,value,color,icon), itsindexand thedatum.
Props
- hideIcon
booleanLeaves the swatch or icon out.- toggle
booleanMakes every item a button that hides or shows its series, witharia-pressed. The hidden keys go to the container'sv-model:hidden.
Data attributes
| data-slot | Attributes | Description |
|---|---|---|
| chart | data-chart, role, aria-label | The root; data-chart is the chart id, role="group" with aria-label when label is set. |
| chart-crosshair | — | Unovis' placeholder for the crosshair. |
| chart-tooltip | data-state | The positioned box; data-state is open while a point is hovered. |
| chart-tooltip-content | — | The default content. |
| chart-tooltip-item | — | One row of the content. |
| chart-tooltip-indicator | — | The colour mark of a row. |
| chart-legend | — | The legend. |
| chart-legend-item | data-state, aria-pressed | One series; data-state is visible or hidden, and with toggle the item is a button with aria-pressed. |
| chart-legend-swatch | — | The colour square. |
CSS variables
| Variable | Default | Description |
|---|---|---|
| --chart-1 … --chart-5 | tokens | The series colours, per mode. |
| --color-<key> | from the config | Set on the chart root for every config key with a colour. |
| --vis-* | mapped to the tokens | Unovis' variables, set on the chart root; override on the container. |