ComponentsIconsGuidesExamplesGetting started
ComponentsIconsGuidesExamplesGetting started
GitHub repository

Line chart

A line chart over a time or numeric x axis, drawn on canvas by uPlot, with series declared as children.

One line per series over a time or numeric x axis. Data is rows plus c2-chart-series children — the same authoring shape as c2-table’s rows and columns — and presentation is ordinary attributes: curve, points, legend, zoom, the axis bounds.

c2-line-chart is the base of the family. Area chart extends it with a fill, and bar, sparkline and pie share the same data contract and the same --c2-chart__* theme namespace, so an app styles every chart at once.

One engine, loaded on demand. Lines are drawn by uPlot, an optional peer dependency reached through a dynamic import() on first paint — nothing is bundled into the component, and a page that shows no chart downloads no engine.

Installation

npm install @c2n/chart uplot

Usage

ReplayReady at 2018

All three demos use a France extract from the public Our World in Data Energy dataset: annual electricity generation in terawatt-hours, one row per year. The source publishes a codebook and traces these electricity fields to Ember and the Energy Institute. Keeping the same rows across the chart family makes the examples comparable rather than decorative.

Data and series

data is an array of row objects. x-field names the key holding the x value (the row index is used when it is omitted) and x-type says how to read it — linear by default, time for epoch milliseconds, category for discrete slots. Each c2-chart-series child names a field — a dotted path such as stats.cpu works — and optionally a label, a color and a line-width. With no children at all, one line is drawn per numeric key of the first row.

The children are definitions, not rendered elements: they are read the way c2-table reads its columns, so adding, hiding or re-colouring one is an ordinary attribute change.

Realtime

data is compared by identity, and a change to it alone is pushed straight into the engine without re-rendering anything. For a live feed call appendPoint() instead, which writes into the frame’s spare capacity and redraws with no reallocation and no Lit update. max-points keeps the window bounded, dropping the oldest points off the front.

uPlot redraws immediately rather than tweening between samples. That is useful for honest live telemetry, but a slow feed will look stepped. The realtime demos interpolate each annual sample with requestAnimationFrame() and append those intermediate points; this keeps the engine’s inexpensive data path while making the moving window visually smooth. ECharts supports animation="auto", but it is better left off for a high-frequency feed so animations do not overlap.

const chart = document.querySelector('c2-line-chart')
chart.maxPoints = 6
for (const row of incomingYears) {
  chart.appendPoint(row.year, [row.nuclear, row.wind, row.solar])
}

Independent legend and tooltip

The built-in legend and tooltip are convenient defaults. For full layout control, place c2-chart-legend and c2-chart-tooltip anywhere in the same document or shadow root. Their for attribute targets the chart’s id, like a label targets a form control, and automatically replaces the corresponding built-in display. The tooltip defaults to a viewport-safe floating position; set position="inline" to keep it exactly where its HTML is authored. The renderLegend, renderLegendItem and renderTooltip properties accept Lit render functions for application-specific content. The custom demo maps each source to a Phosphor icon (atom, drop, wind, sun, or factory) and computes each value’s share of the five tracked generation sources.

import { html } from 'lit'

legend.renderLegendItem = (item) => html`
  ${energyIcon(item.label, item.color)}
  <strong>${item.label}</strong>
`
tooltip.renderTooltip = (context) => {
  const total = trackedTotalFor(context.formattedX)
  return html`
    <strong>${context.formattedX}</strong>
    ${context.entries.map((entry) => html`
      <span>${energyIcon(entry.series.label, entry.color)} ${entry.formatted} TWh · ${formatPercent(entry.value / total)}</span>
    `)}
  `
}

Sizing

A canvas has no intrinsic size, so a chart is sized by its host rather than by its content: --c2-chart--height (320px by default) plus whatever width the layout gives it. A ResizeObserver keeps the canvas in step, and the plot box is contain: strict so a resize can never feed back into itself. Use lazy-render to defer loading the engine until the chart first scrolls into view.

Theming

Every chart in the package reads the same variables, so setting them once themes all of them. The series palette is --c2-chart__series-1--color through --c2-chart__series-8--color, wired by @c2n/theme to the --c2-theme--chart-series-* tokens, which carry light and dark values. Because the plot is a canvas, these are read with getComputedStyle and handed to the engine — so they behave like any other CSS variable, including under a dark theme, but cannot be reached with ::part().

escAccordionConnected, animated panels with shared borders and single or multiple expansion.LayoutArea chartA line chart with the region under each line filled — every line-chart attribute, plus a fill opacity.ChartAttachmentFile and image attachments with metadata, upload progress, failure states, and actions.Data displayAutocompleteSearchable combobox for local or remote items with customizable list rows.InputsAvatarImage, initials or icon for a person, with status dot and badge.Data displayBadgeTinted pill for status text, counts and dots, optionally pinned to a corner of another element.Data displayBar chartBars over categories or time buckets, with several series drawn side by side within each band.ChartBorder BeamA decorative beam that travels around the border of any positioned container.LayoutBreadcrumbNavigation trail of link buttons with separators, a current page and optional collapsing.NavigationButtonThemeable button with slots for text, prefix, suffix and running icons.ButtonsButton GroupJoined actions and polished segmented controls with single or multiple selection.ButtonsCandlestick chartAn ECharts OHLC chart for market sessions and other open-close ranges, with semantic positive and negative colours.ChartCardGroups related content and actions on a single bordered surface.LayoutCascaderSelect a value from related, multi-level data in one floating panel.InputsChat InputAuto-growing message composer with keyboard submission, toolbar actions and native form support.ChatChat MessageFlexible message row for conversations, assistant answers and activity updates.ChatCheckboxNative checkbox behaviour in a quiet, themeable box with an opt-in hover layer.InputsCode EditorEditable, syntax-highlighted source field on CodeMirror 6, themed entirely through CSS variables.InputsCode ViewerSyntax-highlighted code with line numbers, copy button and dark mode, powered by shiki.Data displayColor AreaTwo-dimensional area for picking saturation and value of a colour.InputsColor SelectColour swatch that opens a full picker built from area and slider.InputsColor SliderHorizontal slider for choosing a hue from 0 to 360.InputsCopy ButtonButton that copies text to the clipboard — the element it sits in, another element by id, or a literal string.ButtonsDashboardGrid of resizable panes, dragged by the edges they share.LayoutDate InputForm-associated single-date input with native picker, constraints, helper text and error states.InputsDate SelectorAccessible one- or two-month calendar for choosing a date range.InputsDetailsCollapsible disclosure built on native details and summary.LayoutGauge chartA focused radial KPI gauge drawn by ECharts, with a configurable scale, progress arc and pointer.ChartHeaderArranges brand, navigation, actions and a mobile trigger in a reusable site shell.LayoutIcon ButtonRound, hoverable button wrapping a slotted SVG icon.ButtonsKbdKeyboard key label for shortcuts and command hints, with the semantics of the native kbd element.Data displayLabelCaption that names and activates the control referenced by its for attribute, with a required marker.InputsLine chartA line chart over a time or numeric x axis, drawn on canvas by uPlot, with series declared as children.ChartLink ButtonText-styled control for link and navigation actions, rendered as a real anchor or a button.NavigationListVertical list container with single or multiple selection.Data displayList ItemSelectable row with icon slots, used on its own or as the option of list and select.Data displayMenuCommands, links, checkboxes and submenus in a popover anchored to a trigger.NavigationModalDialog built on the native dialog element: focus trap, backdrop, Escape, title, body and footer.FeedbackNavigation MenuSite navigation bar whose triggers open panels of links below the header.NavigationNumber InputForm-associated numeric input with native validation, step controls, adornments and helper states.InputsOverlayAnchored popup built on the browser Popover API, positioned with floating-ui.FeedbackPaginationPage navigation in three layouts: numbered pages, a simple page status, or a table-footer row with rows-per-page.NavigationPie chartA pie or donut chart drawn by ECharts, where one row is one slice and label-field names it.ChartProgressLinear progress bar, indeterminate or filling to a value, with an optional label and count.FeedbackQR CodeGenerate accessible, themeable QR codes locally as crisp SVG graphics.Data displayQuestionnaireA multi-step single- and multiple-choice flow with validation, shortcuts and form submission.InputsRadar chartCompare several profiles across the same set of normalized indicators.ChartRadioRadio options built on native inputs, grouped into one value with keyboard navigation.InputsRateAccessible star rating input with hover preview, keyboard control and optional half values.InputsReorder ListReorder a vertical queue with pointer or keyboard input while the application owns persistence.Data displayScatter chartAn ECharts scatter plot for finding relationships, clusters and outliers across two numeric measures.ChartSelectDropdown that pairs a themeable trigger with an anchored list of c2-list-item options.InputsSeperatorHorizontal or vertical rule with an optional label, for dividing content and toolbars.LayoutSheetDialog pinned to an edge of the screen, for content that complements the page rather than interrupting it.FeedbackSide NavResponsive navigation drawer beside the page: pushes the content on large screens, slides over it with a backdrop on small ones.NavigationSkeletonPlaceholder block standing in for content that has not arrived, in three shapes and three animations.FeedbackSliderRange input with a themeable track, thumb, step ticks and value bubble.InputsSparklineA chromeless trend line sized for a table cell, a list row or the trend slot of a c2-stat.ChartSpinnerCircular progress indicator, indeterminate or showing a value, with optional text.FeedbackStatDisplays a KPI with an optional icon, trend and supporting description.Data displayStatus PanelCommunicate empty states, operation outcomes and recoverable errors with clear next steps.FeedbackStepsA vertical trace of a task as it runs: statuses, durations, and stages that open while they work and close when they are done.Data displaySwitchOn/off toggle on a native switch input, with label, description and thumb icons.InputsTableVirtualized data grid with declarative columns, sorting, selection, pinning and resizing.Data displayTabsTab strip that shows one content panel at a time.NavigationText FieldSingle-line input with icon slots, clear button, helper and error text, and a character counter.InputsTextareaMultiline text input with resizing, helper and error text, and a character counter.InputsTheme SelectColour-theme switcher: click to step to the next mode, hover for the full menu.InputsToastNotification cards and a manager for stacked, queued notifications with independent lifetimes.FeedbackTooltipContextual hint shown when its target is hovered or focused, rendered in the top layer.FeedbackTreeHierarchical tree view with expansion, selection, checkboxes and lazy loading.Data displayUploadDrag-and-drop file selection with validation, upload progress, retry, cancellation, and attachment results.InputsVirtual ListWindowed list with built-in search, sorting, selection and an async data source.Data displayFeather Icons287 open-source Feather icons, one web component each.IconsMat Icon2,234 Material Icons ligatures rendered through a single element.IconsPhosphor Icons1,512 flexible icons in six weights, one web component each.IconsThemingTheme every c2n component from a handful of design tokens with @c2n/theme, or reach for any component variable directly.GuideFrameworksUse the components from React, Vue, Angular, Svelte, Lit or plain HTML — typed events, generated template types, and the one piece of configuration each framework needs.GuideUsing c2n in an applicationThe workflow behind every c2n app: load the theme once, use c2-* tags directly, and turn every repeated pattern into a small variant or composed component.GuideAI toolsGive Claude Code, Codex or Google Antigravity the c2n skill, live component APIs, examples and application conventions.Guide