# Color-blind-safe pattern fills

patternFallback: true layers a texture (stripe / crosshatch / dots / diagonal) on every series so two series with similar hues still read as distinct in grayscale or for readers with color-vision deficiency. Works on bars and area stacks.

Uses `@svgrid/grid` (MIT). Category: Charts. Live demo: https://svgrid.com/demos/156-chart-patterns/

Install: `npm i @svgrid/grid` (Svelte 5).

## About this example

Colour-blind-safe pattern fills on Svelte 5 charts. Colour alone is a fragile encoding for readers with red-green or blue-yellow colour vision deficiency, so SvGrid layers SVG pattern fills, stripe, crosshatch, dots and diagonal, over the series colour. Opt in per series with pattern or set patternFallback true on the spec to cycle four patterns across every unflagged series, on bars and area stacks alike, so similar hues still read as distinct in grayscale.

Color alone is a fragile encoding for readers with red/green or blue/yellow color vision deficiency. SvGrid lets you layer SVG pattern fills (`stripe`, `crosshatch`, `dots`, `diagonal`) over the series color so two series with similar hues still read as distinct.

Two ways to opt in:

- `series[i].pattern: 'stripe'` per series, OR
- `spec.patternFallback: true` cycles four patterns across every unflagged series. One flag, instant accessibility upgrade.

## Imports, features and API used

- Imports: `@svgrid/grid`
- Table features registered: `rowSortingFeature`, `columnFilteringFeature`
- Columns: `quarter` (Quarter), `region` (Region), `revenue` (Revenue)
- SvGridApi methods called: `api.getDisplayedRows()`

## Frequently asked questions

### How do I turn patterns on for a whole chart?

Set patternFallback: true on the spec. Every series without its own pattern gets one of the four textures in rotation, layered over its colour.

### Can I pick a pattern per series?

Yes. series[i].pattern accepts stripe, crosshatch, dots or diagonal and wins over the fallback cycle.

### Do patterns print?

Yes. They are SVG pattern fills, so they survive grayscale printing and the SVG export, which is the point.

## Related documentation

- [Chart accessibility and localization](https://svgrid.com/docs/help/charts/accessibility.md)
- [Axes, scales and styling](https://svgrid.com/docs/help/charts/axes-and-styling.md)

## Related articles

- [TypeScript Patterns for Data-Heavy Front-End Apps](https://svgrid.com/blog/typescript-for-data-heavy-apps/) - How ColumnDef generics, discriminated unions, and derived types from constants eliminate a whole class of runtime bugs in data-heavy Svelte apps.
- [The WAI-ARIA Grid Pattern Explained](https://svgrid.com/blog/wai-aria-grid-pattern-explained/) - A practical breakdown of the ARIA grid pattern - the roles, keyboard model, and live-region wiring that make interactive data grids actually usable by keyboard and screen-reader users.
- [Sparkline Cells in a Svelte Data Grid](https://svgrid.com/blog/sparkline-cells/) - Show inline trend sparklines inside grid cells using SvGrid's built-in sparkline column property - no charting library needed, just a field that holds a number array.

## Source code (156-chart-patterns.svelte)

```svelte
<!-- Documented in: docs/help/charts/axes-and-styling.md -->
<script lang="ts">
  /**
   * 156. Chart pattern fills (colorblind-safe)
   * ------------------------------------------
   * Color alone is a fragile encoding for readers with red/green or
   * blue/yellow color vision deficiency. SvGrid lets you layer SVG
   * pattern fills (`stripe`, `crosshatch`, `dots`, `diagonal`) over the
   * series color so two series with similar hues still read as distinct.
   *
   * Two ways to opt in:
   *  - `series[i].pattern: 'stripe'` per series, OR
   *  - `spec.patternFallback: true` cycles four patterns across every
   *    unflagged series. One flag, instant accessibility upgrade.
   */
  import {
    SvGrid,
    SvGridChart,
    rowsToChartSpec,
    tableFeatures,
    rowSortingFeature,
    columnFilteringFeature,
    type GridColumns,
    type SvGridApi,
    type ChartSpec,
  } from '@svgrid/grid'

  const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })

  type Row = { id: number; quarter: string; region: string; revenue: number }
  const QUARTERS = ['Q1', 'Q2', 'Q3', 'Q4']
  const REGIONS = ['Americas', 'EMEA', 'APAC', 'LATAM']
  let seed = 0xfeedbeef
  const rnd = () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 0xffffffff)
  let nid = 0
  const rows: Row[] = QUARTERS.flatMap((q, qi) =>
    REGIONS.map((region) => ({
      id: nid++,
      quarter: q,
      region,
      revenue: Math.round(80_000 + qi * 22_000 + rnd() * 80_000),
    })),
  )

  const columns: GridColumns<Row> = [
    { field: 'quarter', header: 'Quarter', width: 100 },
    { field: 'region', header: 'Region', width: 130 },
    { field: 'revenue', header: 'Revenue', width: 140, align: 'right',
      format: { type: 'currency', currency: 'USD', options: { maximumFractionDigits: 0 } } },
  ]

  let api = $state<SvGridApi<typeof features, Row> | null>(null)
  let displayed = $state<Row[]>(rows)
  let patternFallback = $state(true)
  let stacked = $state(false)
  function sync() { displayed = (api?.getDisplayedRows() as Row[]) ?? rows }

  const compact = (v: number) => (Math.abs(v) >= 1e6 ? (v / 1e6).toFixed(1) + 'M' : Math.abs(v) >= 1e3 ? (v / 1e3).toFixed(v % 1e3 ? 1 : 0) + 'k' : String(Math.round(v)))

  const spec = $derived.by<ChartSpec>(() => {
    const s = rowsToChartSpec(displayed, {
      type: 'bar',
      category: 'quarter',
      value: 'revenue',
      series: 'region',
      reduce: 'sum',
      stacked,
      width: 560,
      height: 320,
    })
    s.patternFallback = patternFallback
    s.yAxisTitle = 'Revenue (USD)'
    return s
  })
  /** Pane size, so the chart fills its card rather than a fixed viewBox. */
  let paneW = $state(0)
  let paneH = $state(0)
</script>

<section class="flex flex-col flex-1 min-h-0 gap-3">
  <div class="shrink-0 rounded-lg border px-4 py-3" style="border-color: var(--sg-border); background: var(--sg-header-bg);">
    <p class="text-sm font-semibold" style="color: var(--sg-fg);">
      Pattern fills - color-blind-safe series
    </p>
    <p class="mt-0.5 text-xs" style="color: var(--sg-muted);">
      Toggle the pattern fallback. Each series gets a distinct texture (stripe / crosshatch /
      dots / diagonal) layered over its color so it stays distinguishable in grayscale or for
      readers with deuteranopia / protanopia. Try it stacked - the textures preserve series
      identity even when the colors touch.
    </p>
    <div class="mt-2 flex flex-wrap items-center gap-2 text-xs">
      <label class="ic-chk"><input type="checkbox" bind:checked={patternFallback} /> Pattern fallback</label>
      <label class="ic-chk"><input type="checkbox" bind:checked={stacked} /> Stacked</label>
    </div>
  </div>

  <div class="flex flex-1 min-h-0 gap-3">
    <div class="flex-1 min-w-0 min-h-0">
      <SvGrid responsive={true}
      columnResize
        data={rows}
        columns={columns}
        features={features}
        sortable
        filterable
        selectionMode="none"
        rowHeight={28}
        containerHeight="100%"
        fitColumns={true}
        onApiReady={(a) => { api = a; sync() }}
        onFiltersChange={sync}
        onSortingChange={sync}
      />
    </div>
    <div class="rounded-lg border p-3" style="flex: 0 1 600px; min-width: 0; min-height: 0; border-color: var(--sg-border); background: var(--sg-bg);">
      <!-- Measured box, not the card: its height comes from the parent, so the
           chart cannot push the thing it is sized against. -->
      <div style="width: 100%; height: 100%; min-height: 0;" bind:clientWidth={paneW} bind:clientHeight={paneH}>
        {#if paneW > 40 && paneH > 40}
          <SvGridChart {spec} formatValue={compact} width={paneW} height={paneH} />
        {/if}
      </div>
    </div>
  </div>
</section>

<style>
  .ic-chk { display: inline-flex; align-items: center; gap: 4px; color: var(--sg-fg); font-size: 12px; }
  .ic-chk input[type='checkbox'] { accent-color: var(--sg-accent); }
</style>
```

[View this example on GitHub](https://github.com/sv-grid/sv-grid/blob/main/examples/src/demos/156-chart-patterns.svelte)
