Ir al contenido

LineChart

Muestra cómo cambia algo en el tiempo. Pasa el puntero, o enfócalo y usa las flechas, para leer todas las series en un momento.

import { LineChart, AreaChart, ChartFrame } from '@sypnia/ui/react'

En esta página
  1. Varias series
  2. Una serie, como área
  3. Estados
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

Varias series

Una cruz se ajusta a la hora más cercana y una sola pista lista todas las series, así el puntero nunca tiene que caer justo en una línea.

Requests
Per hour, last 24 hours
  • Reads
  • Writes
  • Sign-ins
05001000150000:0003:0006:0009:0012:0015:0018:0021:00
Ver como tabla
HourReadsWritesSign-ins
00:0060331168
01:0056229071
02:0053927478
03:0053726489
04:00556260104
05:0055122077
06:0060923399
07:00682254122
08:00766282147
09:00856316172
10:00901309150
11:00985349172
12:001058389190
13:001116427205
14:001156461216
15:001130444178
16:001128465181
17:001105478180
18:001064483176
19:001007479171
20:00896424119
21:00824408112
22:00752387107
23:00687365104
Código
import { LineChart } from '@sypnia/ui/react';

const hours = Array.from({ length: 24 }, (_, h) => `${String(h).padStart(2, '0')}:00`);
const wave = (base: number, swing: number, shift: number) => hours.map((_, h) => Math.round(base + swing * Math.sin((h - shift) / 3.8) + (h % 5) * 9));

export default function Requests() {
  return (
    <LineChart title="Requests" subtitle="Per hour, last 24 hours" xLabel="Hour" x={hours}
      series={[
        { id: 'read', label: 'Reads', data: wave(820, 310, 9) },
        { id: 'write', label: 'Writes', data: wave(340, 120, 11) },
        { id: 'auth', label: 'Sign-ins', data: wave(120, 60, 8) },
      ]} />
  );
}

Una serie, como área

Storage used
One series needs no legend: the title names it
0 B9,5 MB19 MB29 MB38 MBOct 1Oct 5Oct 9Oct 13Oct 17Oct 21Oct 25Oct 29
Ver como tabla
DayDatabase
Oct 118 MB
Oct 219 MB
Oct 320 MB
Oct 420 MB
Oct 521 MB
Oct 622 MB
Oct 723 MB
Oct 821 MB
Oct 922 MB
Oct 1023 MB
Oct 1124 MB
Oct 1224 MB
Oct 1325 MB
Oct 1426 MB
Oct 1524 MB
Oct 1625 MB
Oct 1726 MB
Oct 1827 MB
Oct 1927 MB
Oct 2028 MB
Oct 2129 MB
Oct 2228 MB
Oct 2328 MB
Oct 2429 MB
Oct 2530 MB
Oct 2631 MB
Oct 2731 MB
Oct 2832 MB
Oct 2931 MB
Oct 3032 MB
Código
import { AreaChart, useSypnia } from '@sypnia/ui/react';

const days = Array.from({ length: 30 }, (_, d) => `Oct ${d + 1}`);

export default function Storage() {
  const { format } = useSypnia();
  return (
    <AreaChart title="Storage used" subtitle="One series needs no legend: the title names it" xLabel="Day" x={days} height={200}
      formatValue={(v) => format.bytes(v)}
      series={[{ id: 'db', label: 'Database', data: days.map((_, d) => Math.round((18 + d * 0.46 + (d % 7) * 0.3) * 1_048_576)) }]} />
  );
}

Estados

En la primera carga el gráfico muestra la forma de lo que viene. Al actualizarse conserva el último dibujo, atenuado, así nada salta.

Errors
Per day, this week
Código
import { useState } from 'react';
import { Button, EmptyState, LineChart, SegmentedControl } from '@sypnia/ui/react';

type State = 'loading' | 'refreshing' | 'empty' | 'error';
const x = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const data = [{ id: 'errors', label: 'Errors', data: [12, 9, 14, 31, 18, 6, 4] }];

export default function States() {
  const [state, setState] = useState<State>('loading');
  return (
    <div className="sy-stack">
      <SegmentedControl label="State" value={state} onChange={setState}
        options={[{ value: 'loading', label: 'First load' }, { value: 'refreshing', label: 'Refreshing' }, { value: 'empty', label: 'Empty' }, { value: 'error', label: 'Error' }]} />
      <LineChart title="Errors" subtitle="Per day, this week" x={state === 'loading' || state === 'empty' ? [] : x} series={state === 'loading' || state === 'empty' ? [] : data} height={200}
        loading={state === 'loading' || state === 'refreshing'}
        error={state === 'error' ? 'The errors could not be loaded. Check your connection and try again.' : undefined}
        empty={<EmptyState compact icon="check" title="No errors this week." actions={<Button size="sm">See last month</Button>} />} />
    </div>
  );
}

Skeleton

La pieza real y su skeleton: la misma caja, así nada se mueve cuando llegan los datos.

Requests
Per day, last week
  • Answered
  • Failed
050010001500MonTueWedThuFriSatSun
Ver como tabla
AnsweredFailed
Mon82012
Tue94030
Wed10108
Thu98014
Fri112022
Sat6105
Sun5403
Código
import { ChartSkeleton, LineChart } from '@sypnia/ui/react';

// The chart and its skeleton: the same height, the axes and the room of the legend.
const x = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
export default function Skeleton() {
  return (
    <div className="sy-grid">
      <LineChart title="Requests" subtitle="Per day, last week" x={x} height={200}
        series={[{ id: 'ok', label: 'Answered', data: [820, 940, 1010, 980, 1120, 610, 540] }, { id: 'err', label: 'Failed', data: [12, 30, 8, 14, 22, 5, 3] }]} />
      <ChartSkeleton height={200} legend={2} />
    </div>
  );
}

Cuándo usarlo

Úsalo cuando

  • La pregunta es «¿cómo cambió esto?»: solicitudes por hora, almacenamiento por día, errores por semana.
  • Hasta cinco series. Mantienen el mismo color en todas partes, en el mismo orden.
  • Una cantidad que se acumula (almacenamiento, usuarios totales): usa AreaChart, el mismo gráfico con un relleno bajo la línea.

No lo uses cuando

  • No hay tiempo ni orden en el eje horizontal: compara categorías con un BarChart.
  • Quieres dos unidades distintas en un gráfico (solicitudes y milisegundos). Nunca dos escalas verticales: usa dos gráficos.
  • Más de cinco series: agrupa el resto como «Otros», o muestra varios gráficos pequeños.
  • Todo se trata de un número: usa un Stat, con un Sparkline si la forma importa.

Para todos

  • El gráfico tiene un nombre que dice qué muestra y qué series tiene.
  • Con el teclado: Tab hasta el gráfico, y luego Izquierda y Derecha mueven la cruz; se anuncian los valores.
  • «Ver como tabla» muestra los mismos números como tabla, así nada queda disponible solo al pasar el puntero.
  • Las series nunca se distinguen solo por color: siempre hay una leyenda, y el texto nunca se dibuja con el color de una serie.
  • Los cinco colores de las series están revisados para daltonismo y contraste en noche y papel.

Props

LineChartTipoPor defecto
seriesobligatorio Series[]
titleobligatorio ReactNode
xobligatorio

The positions along the horizontal axis: dates, hours, names.

string[]
area

Fills under each line with a light wash: for a quantity that accumulates.

boolean
empty ReactNode
error ReactNode
formatValue

How a value is written in ticks, tooltip and table. Defaults to a compact number in the person's language.

((v: number) => string)
height number
loading boolean
subtitle ReactNode
xLabel

The header of the first column of the table view: what `x` is.

string
AreaChartTipoPor defecto
seriesobligatorio Series[]
titleobligatorio ReactNode
xobligatorio

The positions along the horizontal axis: dates, hours, names.

string[]
empty ReactNode
error ReactNode
formatValue

How a value is written in ticks, tooltip and table. Defaults to a compact number in the person's language.

((v: number) => string)
height number
loading boolean
subtitle ReactNode
xLabel

The header of the first column of the table view: what `x` is.

string
ChartFrameTipoPor defecto
titleobligatorio ReactNode
empty

Shown instead of the plot when there is nothing to draw.

ReactNode
error ReactNode
height number 240
isEmpty boolean
legend

Series to list in the legend. Not shown for a single series: the title already names it.

{ label: string; line?: boolean; }[]
loading

New data is on its way: the chart keeps its last drawing, dimmed. On the first load pass `loading` with no data.

boolean
skeleton

What the plot shows on the first load instead of the default plot skeleton, when the chart's shape is not a plot with axes (rows of bars, a gauge).

ReactNode
subtitle

What is plotted and in what unit: «Requests per minute, last 24 hours».

ReactNode
table

The same numbers as a table, behind «View as table».

{ columns: string[]; rows: (string | number)[][]; }
  1. Varias series
  2. Una serie, como área
  3. Estados
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

    Busca páginas, secciones y términos