# Plot Components

SVG-based plotting components for visualising data streams.

```bash
npm install @ixfx/plots
```

---

## Overview

All plot components share a common rendering approach (SVG, intrinsic sizing via ResizeObserver, theme-aware CSS variables) but differ in what they visualise:

| Component | Data shape | Axis meaning | Draw styles | Age/colour | Key use case |
|-----------|-----------|--------------|-------------|------------|-------------|
| `<ixfx-plot-single-axis>` | 1D values (ordered sequence) | X = index/order, Y = value | 9 styles (line, marker, bar, hist) | Age + colour | Time series, sensor readings |
| `<ixfx-plot-xy-axis>` | 2D (x, y) pairs | X = value, Y = value | 2 styles (circle, square) | Age + colour | Scatter plots, Lissajous |
| `<ixfx-plot-multi-axis>` | Named 1D series | Same as single-axis per series | Defined per series via `styleSeries()` | Per-series colour | Multiple simultaneous signals |
| `<ixfx-plot-histogram>` | 1D values (unordered distribution) | X/Y = value bins, bar length = density | Single bar style | Opacity via `--value` | Value distribution, heat map |

---

## Common Features

### Adding Data

```typescript
// single-axis / histogram
plot.add(42);
plot.set([1, 2, 3, 4, 5]);
plot.clear();

// xy-axis — requires x and y
plot.add(0.5, 0.8);
plot.setXY([1,2,3], [4,5,6]);
plot.clear();

// multi-axis — named values
plot.addData({ temperature: 22, humidity: 60 });
plot.clear();
```

### Common Properties

| Property | Type | Default | Applies to | Description |
|----------|------|---------|-------------|-------------|
| `title` | `string` | `""` | all | Title displayed on the plot |
| `capacity` | `number` | `100` | single-axis, xy-axis, histogram | Max data points to store |
| `paused` | `boolean` | `false` | all but multi-axis | Pause rendering updates |

### Inline (Declarative) Data

Provide initial data directly in the HTML for **single-axis** and **histogram**:

```html
<ixfx-plot-single-axis>1, 2, 0.5, 0.3, -1</ixfx-plot-single-axis>
<ixfx-plot-histogram>0.1 0.4 0.7 0.3 0.9</ixfx-plot-histogram>
```

Numbers can be separated by commas, spaces, or semicolons. Programmatic `set()` / `add()` calls take precedence.

### CSS Variables (shared)

| Variable | Default | Applies to | Description |
|----------|---------|-------------|-------------|
| `--plot-color` | `var(--accent)` | single-axis, xy-axis | Base colour for data points |
| `--plot-text` | `var(--surface-2-text, #fff)` | all | Text colour for title |

### Sizing

All components use `display: inline-block` with `width: 100%; height: 100%` by default. They observe their container via `ResizeObserver`, so sizing is controlled entirely by the parent:

```css
.plot-container {
  width: 100%;
  height: 200px;
}
.plot-container > ixfx-plot-* {
  width: 100%;
  height: 100%;
}
```

---

## `<ixfx-plot-single-axis>`

Renders a 1D data series as a time-series / ordered-sequence plot.

**Tag:** `<ixfx-plot-single-axis>`

### Properties

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `drawStyle` | `SingleAxisDrawStyle` | `line-sharp` | Rendering style |
| `ageStyle` | `SingleAxisAgeStyle` | `none` | Ageing effect |
| `tooltips` | `boolean` | `true` | Show tooltip on hover |
| `precise` | `boolean` | `false` | Show latest value in corner |
| `persistentScale` | `boolean` | `true` | Keep same scale; if `false`, scale adjusts to visible data |
| `rangeMin` | `number` | `NaN` | Fixed minimum value for Y-axis (when set, disables auto-scaling) |
| `rangeMax` | `number` | `NaN` | Fixed maximum value for Y-axis (when set, disables auto-scaling) |
| `clickPauses` | `boolean` | `false` | Toggle pause on click |
| `shaded` | `boolean` | `false` | Shaded area under line |
| `areaColor` | `string` | `""` | Custom shade colour |
| `colorMode` | `ColourMode` | `fixed` | Colour mapping |
| `colorEasing` | `string` | `""` | Easing for colour mapping |
| `colorScale` | `string` | `""` | Colour palette for `scale` mode |

### Fixed Range

Set `range-min` and `range-max` attributes to fix the Y-axis scale:

```html
<ixfx-plot-single-axis range-min="0" range-max="100"></ixfx-plot-single-axis>
```

When both are set, the plot uses a fixed range instead of auto-scaling to the data.

### Draw Styles

| Style | Description |
|-------|-------------|
| `line-sharp` | Sharp line segments (default) |
| `line-round` | Rounded line segments |
| `circles` | Circle markers |
| `squares` | Square markers |
| `vbar` | Vertical bars from baseline |
| `hbar` | Horizontal bars |
| `hist-bottom` | Histogram bars from bottom |
| `hist-top` | Histogram bars from top |
| `hist-middle` | Histogram bars from middle |

### Age Styles

| Style | Description |
|-------|-------------|
| `none` | No effect (default) |
| `opacity` | Older points fade out |
| `desaturation` | Older points grayscale |
| `size` | Older points shrink |

Applies to discrete draw styles only (`circles`, `squares`, `vbar`, `hbar`, `hist-*`).

### Colour Mapping

| Mode | Description |
|------|-------------|
| `fixed` | Single colour (default) |
| `opacity` | Varying opacity |
| `hue` | Map value to hue |
| `saturation` | Map value to saturation |
| `lightness` | Map value to lightness |
| `scale` | Interpolate through a colour palette |

Use `color-easing` for easing functions or `color-scale` for custom palettes:

```html
<ixfx-plot-single-axis color-mode="scale" color-scale="green,yellow,red">
```

### Events

- **`plot-datapoint-click`** — `{ value: number, index: number }`
- **`plot-pointer-move`** — `{ clientX: number, clientY: number, index: number }`
- **`plot-pointer-leave`** — Fired when pointer leaves the plot

### Value Formatting

Override `valueFormat` to customize the tooltip and precise value display:

```typescript
plot.valueFormat = v => v ? `${v.toFixed(1)}°C` : '';
```

### Properties

| Property | Type | Description |
|----------|------|-------------|
| `values` | `readonly number[]` | Get all values in the series |
| `dataLength` | `number` | Number of data points |
| `series` | `PlotDataSeries` | Internal data series instance |

### Example

```html
<ixfx-plot-single-axis draw-style="line-round" title="Temperature" capacity="50"></ixfx-plot-single-axis>
<script type="module">
  import '@ixfx/plots';
  const plot = document.querySelector('ixfx-plot-single-axis');
  setInterval(() => plot.add(Math.random() * 100), 100);
</script>
```

---

## `<ixfx-plot-xy-axis>`

Renders a 2D X/Y scatter or line plot.

**Tag:** `<ixfx-plot-xy-axis>`

### Properties

Same colour/age properties as single-axis. Add via `plot.add(x, y)` or `plot.setXY(xArray, yArray)`.

### Draw Styles

| Style | Description |
|-------|-------------|
| `circles` | Circle markers (default) |
| `squares` | Square markers |

### Events

- **`plot-datapoint-click`** — `{ x: number, y: number, index: number }`

### Custom Formatting

Override `valueFormat`:

```typescript
plot.valueFormat = (x, y) => `(${x.toFixed(2)}, ${y.toFixed(2)})`;
```

### Example

```html
<ixfx-plot-xy-axis draw-style="circles" age-style="opacity" title="Position"></ixfx-plot-xy-axis>
<script type="module">
  import '@ixfx/plots';
  const plot = document.querySelector('ixfx-plot-xy-axis');
  let t = 0;
  setInterval(() => { plot.add(Math.sin(t), Math.cos(t)); t += 0.1; }, 50);
</script>
```

---

## `<ixfx-plot-multi-axis>`

Displays multiple named 1D series simultaneously with configurable layout.

**Tag:** `<ixfx-plot-multi-axis>`

Unlike the other plot components, multi-axis manages multiple independent data streams. Each series has its own colour, and the layout can arrange them as overlapped, horizontal, vertical, or in a grid.

### Properties

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `layout` | `"overlap"` \| `"horizontal"` \| `"vertical"` \| `"grid"` | `overlap` | How to arrange the series |
| `gridMinWidth` | `number` | `180` | Min column width in `grid` layout (px) |
| `capacity` | `number` | `100` | Max data points per series |

### Methods

```typescript
plot.addData({ temperature: 22, humidity: 60, pressure: 1013 });
plot.addObject({ temperature: 22, humidity: 60 });        // Add to existing series
plot.setData('temperature', [1, 2, 3]);                  // Replace series data
plot.setObjects({ a: [1,2,3], b: [4,5,6] });            // Replace multiple series
plot.styleSeries('temperature', { 'plot-color': '#ff6b6b' });
plot.clear();                                            // Clear all series
plot.clearSeries('temperature');                          // Clear single series
plot.series;                                             // Get series names array
```

### Layouts

| Layout | Description |
|--------|-------------|
| `overlap` | All series drawn on the same axes (default) |
| `horizontal` | Each series in its own row |
| `vertical` | Each series in its own column |
| `grid` | Auto-fill grid, each cell holds one series |

### Per-Series Styling

```typescript
plot.styleSeries('temperature', {
  'plot-color': '#ff6b6b',
  'draw-style': 'line-round',
});
plot.styleSeries('humidity', {
  'plot-color': '#4ecdc4',
  'draw-style': 'hist-bottom',
});
```

### Events

- **`plot-datapoint-click`** — `{ series: string, value: number, index: number }`
- **`plot-series-add`**, **`plot-series-remove`** — Series lifecycle

### Example

```html
<ixfx-plot-multi-axis layout="horizontal" class="plot-lg"></ixfx-plot-multi-axis>
<script type="module">
  import '@ixfx/plots';
  const plot = document.querySelector('ixfx-plot-multi-axis');
  let t = 0;
  setInterval(() => {
    plot.addData({ x: Math.sin(t), y: Math.cos(t), z: Math.sin(t * 0.5) });
    t += 0.1;
  }, 80);
</script>
```

---

## `<ixfx-plot-histogram>`

Renders a histogram of value distributions. Unlike `ixfx-plot-single-axis` (where the X-axis represents ordering), this component shows a pure distribution — all values in the current buffer are binned into buckets spanning the data range. There is no time or sequence axis.

**Tag:** `<ixfx-plot-histogram>`

### Properties

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `orientation` | `PlotHistogramOrientation` | `horizontal` | `horizontal` or `vertical` |
| `resolution` | `number` | `0.10` | Fraction of range per bucket |
| `min` / `max` | `number` | auto | Fixed value range (disables auto-scaling) |
| `capacity` | `number` | `100` | Max values retained |
| `valueTooltips` | `PlotHistogramValueTooltips` | `hover` | `hover` (bubble), `inline` (overlay-text), or `none` |
| `tooltipDelay` | `number` | `400` | Hover delay (ms) before the `hover` bubble appears/disappears |
| `valueUpdateInterval` | `number` | `500` | Max rate (ms) at which a shown value refreshes against live-changing data |
| `paused` | `boolean` | `false` | Pause rendering updates |

### Orientation

| Value | Description |
|-------|-------------|
| `horizontal` (default) | X-axis = value range → vertical bars rising from bottom |
| `vertical` | Y-axis = value range → horizontal bars extending from left (bottom-to-top = min-to-max) |

### Resolution

Controls bucket granularity. Value is a fraction of the available space. Default `0.10` = 10 buckets.

```html
<ixfx-plot-histogram resolution="0.05"></ixfx-plot-histogram>  <!-- 20 buckets -->
<ixfx-plot-histogram resolution="0.20"></ixfx-plot-histogram>  <!-- 5 buckets -->
```

### Fixed Range

Set `min` / `max` attributes to fix the value range and disable automatic RangeStream scaling:

```html
<ixfx-plot-histogram min="0" max="1" resolution="0.05"></ixfx-plot-histogram>
```

### Bar Length

By default, each bar's length (height in horizontal, width in vertical) is proportional to the fraction of values in that bucket — a classic histogram. Override via `--plot-histogram-bar-length` to produce a **heat-map** appearance where all bars are full-length and only colour varies:

```css
ixfx-plot-histogram {
  --plot-histogram-bar-length: 1;
  --plot-histogram-fill: oklch(65% 0.2 30);
  --plot-histogram-gap: 0px;
}
```

### CSS Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `--plot-histogram-fill` | `currentColor` | Fill colour of each bucket bar |
| `--plot-histogram-gap` | `1px` | Gap between adjacent buckets |
| `--plot-histogram-border-radius` | `0` | Corner radius of each bucket |
| `--plot-histogram-bar-length` | `auto` | Fixed bar length fraction (0–1); `auto` = proportional to density |

Opacity is derived from `--value` (set inline on each bucket bar):
```css
rect.bar {
  opacity: calc(0.15 + var(--value) * 0.85);
}
```

### Events

- **`plot-bucket-click`** — `{ bucketIndex: number, valueMin: number, valueMax: number, relativeValue: number }`

### Tooltips

`valueTooltips` selects how hovering a bucket is shown, sharing the same overridable `valueFormat(valueMin, valueMax, frequency)` (default: `"<min> - <max>: <frequency>"`):

- `"hover"` (default) — a floating `ixfx-tooltip` bubble, positioned by the component itself: centred on the hovered bar along the bucket axis, offset from the cursor on the other axis. Debounced by `tooltipDelay` ms (default `400`) on first appearance and on hide; switching directly between bars while already visible updates instantly.
- `"inline"` — swaps the title overlay-text (top-left) for the hovered bucket's value/frequency instantly (no debounce), reverting to `title` when the pointer leaves.
- `"none"` — no hover feedback.

While hovering, both `hover` and `inline` refresh their displayed value at most every `valueUpdateInterval` ms (default `500`) as the underlying bucket's data changes, rather than on every `add()`.

Note: `title` is not reflected to the native `title` attribute, so hovering the plot doesn't also trigger the browser's own tooltip.

### Example

```html
<ixfx-plot-histogram title="distribution" capacity="500"></ixfx-plot-histogram>
<script type="module">
  import '@ixfx/plots';
  const plot = document.querySelector('ixfx-plot-histogram');
  setInterval(() => plot.add(Math.random()), 50);
</script>
```

---

## TypeScript

```typescript
import type { SingleAxisDrawStyle, SingleAxisAgeStyle } from '@ixfx/plots';
import type { XyDrawStyle, XyAgeStyle } from '@ixfx/plots';
import type { PlotHistogramOrientation, PlotHistogramBucketClickDetail } from '@ixfx/plots';
import type { MultiAxisLayout, PlotMultiAxis } from '@ixfx/plots';
```
