# Chart / Gráfico

> Line and bar charts with no dependencies; data lives in an HTML table.

Page: https://componentes-lovat.vercel.app/c/chart/  
License: MIT · Design: W3C WAI, Complex images  
Requires: tokens.css  
Context: herramienta · Density: alta · Tone: sobria

## Files

- Tokens (once): https://componentes-lovat.vercel.app/tokens.css
- HTML: https://componentes-lovat.vercel.app/raw/chart/chart.html
- CSS: https://componentes-lovat.vercel.app/raw/chart/chart.css
- JS: https://componentes-lovat.vercel.app/raw/chart/chart.js
- Everything in one file: https://componentes-lovat.vercel.app/r/chart.html

Dark theme: add class `dark` to `<html>`.

## When to use

- To show a trend (line) or compare categories (bars).
- Up to 3 series.

## When not to use

- For 2 or 3 numbers: write them.
- For parts of a whole with many categories: use a table.

## Accessibility

Roles: img, table

| Keys | Action |
|---|---|
| ← / → | Moves through points and announces values |
| Inicio / Fin | First or last point |

- The SVG has a summary in aria-label; exact values are under “View data”.
- Series differ by color and stroke (solid, dashed, dotted).
- Theme colors only: --primary and --muted-foreground; no gradients or animation.

## Code

```html
<figure class="c-chart" data-c-chart data-type="line">
  <figcaption class="c-chart__head">
    <span class="c-chart__title">Visitas por semana</span>
    <span class="c-chart__note">Datos de ejemplo</span>
  </figcaption>
  <div class="c-chart__legend" aria-hidden="true"></div>
  <div class="c-chart__plot" tabindex="0"></div>
  <p class="c-chart__readout" aria-live="polite"></p>
  <details class="c-chart__data">
    <summary>Ver datos</summary>
    <table>
      <thead><tr><th scope="col">Semana</th><th scope="col">2026</th><th scope="col">2025</th></tr></thead>
      <tbody>
        <tr><th scope="row">S1</th><td>1200</td><td>980</td></tr>
        <tr><th scope="row">S2</th><td>1350</td><td>1010</td></tr>
        <tr><th scope="row">S3</th><td>1280</td><td>1100</td></tr>
        <tr><th scope="row">S4</th><td>1620</td><td>1150</td></tr>
        <tr><th scope="row">S5</th><td>1780</td><td>1190</td></tr>
        <tr><th scope="row">S6</th><td>1710</td><td>1240</td></tr>
        <tr><th scope="row">S7</th><td>2050</td><td>1300</td></tr>
        <tr><th scope="row">S8</th><td>2240</td><td>1360</td></tr>
      </tbody>
    </table>
  </details>
</figure>

<figure class="c-chart" data-c-chart data-type="bar">
  <figcaption class="c-chart__head">
    <span class="c-chart__title">Pedidos por canal</span>
    <span class="c-chart__note">Datos de ejemplo</span>
  </figcaption>
  <div class="c-chart__legend" aria-hidden="true"></div>
  <div class="c-chart__plot" tabindex="0"></div>
  <p class="c-chart__readout" aria-live="polite"></p>
  <details class="c-chart__data">
    <summary>Ver datos</summary>
    <table>
      <thead><tr><th scope="col">Canal</th><th scope="col">Septiembre</th><th scope="col">Agosto</th></tr></thead>
      <tbody>
        <tr><th scope="row">Web</th><td>420</td><td>380</td></tr>
        <tr><th scope="row">Tienda</th><td>310</td><td>330</td></tr>
        <tr><th scope="row">WhatsApp</th><td>260</td><td>190</td></tr>
        <tr><th scope="row">Marketplace</th><td>140</td><td>150</td></tr>
      </tbody>
    </table>
  </details>
</figure>
```

```css
/* Gráfico de línea y barras sin dependencias. Los datos viven en la <table>; chart.js dibuja el SVG.
   Colores solo de variables del tema (cambian con cada combinación de Wada): --primary, --muted-foreground,
   --foreground, --border. Sin degradados ni animación. Necesita tokens.css. */
.c-chart { margin: 0; width: 100%; max-width: 44rem; display: grid; gap: .5rem; font-family: inherit; color: var(--foreground); }
.c-chart__head { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: .25rem 1rem; }
.c-chart__title { font-weight: 600; font-size: .9375rem; }
.c-chart__note { font-size: .75rem; color: var(--muted-foreground); }
.c-chart__legend { display: flex; flex-wrap: wrap; gap: .25rem 1rem; font-size: .75rem; color: var(--muted-foreground); }
.c-chart__key { display: inline-flex; align-items: center; gap: .375rem; }
.c-chart__key svg { width: 18px; height: 8px; overflow: visible; }
.c-chart__plot { position: relative; height: var(--chart-h, 240px); border-radius: calc(var(--radius) - 2px); outline: none; }
.c-chart__plot:focus-visible { box-shadow: 0 0 0 2px var(--background), 0 0 0 4px var(--ring); }
.c-chart__plot svg { display: block; width: 100%; height: 100%; overflow: visible; }
.c-chart__grid { stroke: var(--border); stroke-width: 1; shape-rendering: crispEdges; }
.c-chart__axis { fill: var(--muted-foreground); font-size: 11px; font-variant-numeric: tabular-nums; }
.c-chart__line { fill: none; stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; vector-effect: non-scaling-stroke; }
.c-chart__dot { stroke: var(--background); stroke-width: 2; }
.c-chart__bar { shape-rendering: crispEdges; }
.c-chart__cursor { stroke: var(--foreground); stroke-opacity: .25; stroke-width: 1; }
.c-chart__s0 { stroke: var(--primary); fill: var(--primary); }
.c-chart__s1 { stroke: var(--muted-foreground); fill: var(--muted-foreground); }
.c-chart__s2 { stroke: var(--foreground); fill: var(--foreground); }
.c-chart__line.c-chart__s1 { stroke-dasharray: 5 4; }
.c-chart__line.c-chart__s2 { stroke-dasharray: 1 4; }
.c-chart__line { fill: none; }
.c-chart__bar.c-chart__s1 { fill-opacity: .55; }
.c-chart__tip { position: absolute; top: 0; pointer-events: none; z-index: 2; min-width: 7rem; padding: .375rem .5rem; border: 1px solid var(--border); border-radius: calc(var(--radius) - 2px); background: var(--popover); color: var(--popover-foreground); font-size: .75rem; line-height: 1.4; box-shadow: 0 4px 12px -4px #0000002e; white-space: nowrap; }
.c-chart__tip b { display: block; margin-bottom: .125rem; }
.c-chart__tip span { display: flex; justify-content: space-between; gap: .75rem; font-variant-numeric: tabular-nums; }
.c-chart__tip i { display: inline-block; width: .5rem; height: .5rem; border-radius: 50%; margin-right: .375rem; vertical-align: .05em; }
.c-chart__readout { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; margin: 0; }
.c-chart__data { font-size: .75rem; color: var(--muted-foreground); }
.c-chart__data summary { cursor: pointer; width: fit-content; border-radius: 4px; }
.c-chart__data summary:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
.c-chart__data table { margin-top: .5rem; border-collapse: collapse; font-variant-numeric: tabular-nums; color: var(--foreground); }
.c-chart__data th, .c-chart__data td { padding: .25rem .75rem .25rem 0; text-align: left; border-bottom: 1px solid var(--border); font-weight: 400; }
.c-chart__data td { text-align: right; }
.c-chart__data thead th { color: var(--muted-foreground); }
@media (forced-colors: active) { .c-chart__s0, .c-chart__s1, .c-chart__s2 { stroke: CanvasText; fill: CanvasText; } }
```

```js
/* Gráfico de línea y barras sin dependencias. Lee los datos de la <table> del propio gráfico (primera
   columna = etiquetas; cada columna siguiente = una serie) y dibuja un SVG que se adapta al ancho.
   Teclado: enfoca el gráfico y usa ← → (Inicio/Fin) para recorrer los puntos; el valor se anuncia.
   Uso: <figure data-c-chart data-type="line|bar"> … <table> … </figure>; Componentes.chart.init(root) tras insertar. */
(function () {
  const C = (window.Componentes = window.Componentes || {});
  const SVG = 'http://www.w3.org/2000/svg';
  const fmt = new Intl.NumberFormat(document.documentElement.lang || 'es', { maximumFractionDigits: 1 });

  function el(tag, attrs, parent) {
    const n = document.createElementNS(SVG, tag);
    for (const k in attrs) n.setAttribute(k, attrs[k]);
    if (parent) parent.appendChild(n);
    return n;
  }

  function read(fig) {
    const t = fig.querySelector('table');
    const series = [...t.tHead.rows[0].cells].slice(1).map((c) => ({ name: c.textContent.trim(), values: [] }));
    const labels = [];
    [...t.tBodies[0].rows].forEach((r) => {
      labels.push(r.cells[0].textContent.trim());
      series.forEach((s, i) => s.values.push(parseFloat(String(r.cells[i + 1]?.textContent).replace(/[^\d.-]/g, '')) || 0));
    });
    return { labels, series: series.slice(0, 3) };
  }

  // Escala «redonda»: el máximo sube al siguiente 1, 2, 2.5 o 5 × 10^n.
  function niceMax(v) {
    if (v <= 0) return 1;
    const p = Math.pow(10, Math.floor(Math.log10(v)));
    for (const m of [1, 2, 2.5, 5, 10]) if (m * p >= v) return m * p;
    return 10 * p;
  }

  function legend(fig, data, type) {
    const box = fig.querySelector('.c-chart__legend');
    if (!box) return;
    box.innerHTML = '';
    data.series.forEach((s, i) => {
      const k = document.createElement('span');
      k.className = 'c-chart__key';
      const svg = el('svg', { viewBox: '0 0 18 8' }, k);
      if (type === 'bar') el('rect', { x: 5, y: 0, width: 8, height: 8, rx: 1.5, class: `c-chart__bar c-chart__s${i}` }, svg);
      else el('line', { x1: 0, y1: 4, x2: 18, y2: 4, class: `c-chart__line c-chart__s${i}` }, svg);
      k.append(s.name);
      box.appendChild(k);
    });
  }

  function draw(fig) {
    const plot = fig.querySelector('.c-chart__plot');
    const data = fig._data;
    const type = fig.dataset.type === 'bar' ? 'bar' : 'line';
    const W = plot.clientWidth, H = plot.clientHeight;
    if (!W || !H) return;
    const pad = { t: 8, r: 8, b: 24, l: 40 };
    const iw = W - pad.l - pad.r, ih = H - pad.t - pad.b;
    const max = niceMax(Math.max(...data.series.flatMap((s) => s.values)));
    const y = (v) => pad.t + ih - (v / max) * ih;
    const n = data.labels.length;
    const step = type === 'bar' ? iw / n : iw / Math.max(1, n - 1);
    const xAt = (i) => (type === 'bar' ? pad.l + step * i + step / 2 : pad.l + step * i);

    plot.querySelector('svg')?.remove();
    const svg = el('svg', { viewBox: `0 0 ${W} ${H}`, 'aria-hidden': 'true', focusable: 'false' });
    plot.prepend(svg);
    for (let k = 0; k <= 4; k++) {
      const v = (max / 4) * k, yy = Math.round(y(v)) + .5;
      el('line', { x1: pad.l, x2: W - pad.r, y1: yy, y2: yy, class: 'c-chart__grid' }, svg);
      el('text', { x: pad.l - 8, y: yy + 4, 'text-anchor': 'end', class: 'c-chart__axis' }, svg).textContent = fmt.format(v);
    }
    const every = Math.ceil(n / Math.max(1, Math.floor(iw / 56)));
    data.labels.forEach((lab, i) => {
      if (i % every) return;
      el('text', { x: xAt(i), y: H - 6, 'text-anchor': 'middle', class: 'c-chart__axis' }, svg).textContent = lab;
    });
    const cursor = el('line', { x1: 0, x2: 0, y1: pad.t, y2: pad.t + ih, class: 'c-chart__cursor', visibility: 'hidden' }, svg);

    if (type === 'bar') {
      const groupW = step * .7, bw = groupW / data.series.length;
      data.series.forEach((s, si) => s.values.forEach((v, i) => {
        const x = pad.l + step * i + (step - groupW) / 2 + bw * si;
        el('rect', { x: x + 1, y: y(v), width: Math.max(1, bw - 2), height: pad.t + ih - y(v), rx: 3, class: `c-chart__bar c-chart__s${si}` }, svg);
      }));
    } else {
      data.series.forEach((s, si) => {
        el('polyline', { points: s.values.map((v, i) => `${xAt(i)},${y(v)}`).join(' '), class: `c-chart__line c-chart__s${si}` }, svg);
      });
    }
    const dots = data.series.map((s, si) => el('circle', { r: 4, class: `c-chart__dot c-chart__s${si}`, visibility: 'hidden' }, svg));
    fig._geo = { xAt, y, step, pad, n, cursor, dots, type, W };
  }

  function show(fig, i) {
    const g = fig._geo, data = fig._data, plot = fig.querySelector('.c-chart__plot');
    if (!g) return;
    let tip = plot.querySelector('.c-chart__tip');
    if (i == null) { if (tip) tip.hidden = true; g.cursor.setAttribute('visibility', 'hidden'); g.dots.forEach((d) => d.setAttribute('visibility', 'hidden')); return; }
    fig._i = i;
    const x = g.xAt(i);
    g.cursor.setAttribute('x1', x); g.cursor.setAttribute('x2', x); g.cursor.setAttribute('visibility', g.type === 'line' ? 'visible' : 'hidden');
    g.dots.forEach((d, si) => { d.setAttribute('cx', x); d.setAttribute('cy', g.y(data.series[si].values[i])); d.setAttribute('visibility', g.type === 'line' ? 'visible' : 'hidden'); });
    if (!tip) { tip = document.createElement('div'); tip.className = 'c-chart__tip'; tip.setAttribute('aria-hidden', 'true'); plot.appendChild(tip); }
    tip.hidden = false;
    tip.innerHTML = `<b></b>` + data.series.map((s, si) => `<span><span><i class="c-chart__s${si}" style="background:currentColor;color:var(--${['primary', 'muted-foreground', 'foreground'][si]})"></i>${s.name}</span><strong>${fmt.format(s.values[i])}</strong></span>`).join('');
    tip.querySelector('b').textContent = data.labels[i];
    const left = Math.min(Math.max(0, x + 12), g.W - tip.offsetWidth);
    tip.style.left = (x + 12 + tip.offsetWidth > g.W ? x - 12 - tip.offsetWidth : left) + 'px';
    const ro = fig.querySelector('.c-chart__readout');
    if (ro) ro.textContent = `${data.labels[i]}: ` + data.series.map((s) => `${s.name} ${fmt.format(s.values[i])}`).join(', ');
  }

  function setup(fig) {
    fig._data = read(fig);
    const data = fig._data, plot = fig.querySelector('.c-chart__plot');
    const type = fig.dataset.type === 'bar' ? 'bar' : 'line';
    const title = fig.querySelector('.c-chart__title')?.textContent.trim() || 'Gráfico';
    const s0 = data.series[0];
    const last = s0.values.length - 1;
    plot.setAttribute('role', 'img');
    plot.setAttribute('aria-label', `${title}. ${type === 'bar' ? 'Barras' : 'Línea'} con ${data.series.length} series y ${data.labels.length} puntos; ${s0.name} va de ${fmt.format(s0.values[0])} en ${data.labels[0]} a ${fmt.format(s0.values[last])} en ${data.labels[last]}. Usa las flechas para recorrerlo; los datos están en «Ver datos».`);
    legend(fig, data, type);
    draw(fig);
    plot.addEventListener('pointermove', (e) => {
      const g = fig._geo; if (!g) return;
      const r = plot.getBoundingClientRect(), px = e.clientX - r.left;
      const i = g.type === 'bar' ? Math.floor((px - g.pad.l) / g.step) : Math.round((px - g.pad.l) / g.step);
      show(fig, Math.max(0, Math.min(g.n - 1, i)));
    });
    plot.addEventListener('pointerleave', () => { if (document.activeElement !== plot) show(fig, null); });
    plot.addEventListener('focus', () => show(fig, fig._i ?? 0));
    plot.addEventListener('blur', () => show(fig, null));
    plot.addEventListener('keydown', (e) => {
      const n = data.labels.length, cur = fig._i ?? 0;
      const next = { ArrowRight: cur + 1, ArrowLeft: cur - 1, Home: 0, End: n - 1 }[e.key];
      if (next === undefined) return;
      e.preventDefault();
      show(fig, Math.max(0, Math.min(n - 1, next)));
    });
    new ResizeObserver(() => { draw(fig); if (document.activeElement === plot) show(fig, fig._i ?? 0); }).observe(plot);
  }

  function init(root) {
    (root || document).querySelectorAll('[data-c-chart]:not([data-c-ready])').forEach((fig) => {
      fig.dataset.cReady = '';
      try { setup(fig); } catch (e) { console.warn('[chart]', e); }
    });
  }

  C.chart = { init, redraw: (fig) => { fig._data = read(fig); draw(fig); } };
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => init());
  else init();
})();
```

## Credits

- W3C WAI, Complex images: https://www.w3.org/WAI/tutorials/images/complex/
