Accessible HTML legend for charts, used with the renderLegend prop
Tags: chart legend accessibility toggle
ChartLegend renders a chart legend as HTML toggle buttons instead of the canvas legend
ECharts draws. Pass it to a chart's renderLegend prop: the chart hides its built-in
legend and hands the legend's state and actions to your renderer.
Supported by LineChart, BarChart, AreaChart, ScatterChart, PieChart, DonutChart, FunnelChart and RadarChart.
Import
<script>
import { ChartLegend } from '@classic-homes/charts-svelte';
</script>// React
import { ChartLegend } from '@classic-homes/charts-react';Basic Usage
<script>
import { LineChart, ChartLegend } from '@classic-homes/charts-svelte';
</script>
{#snippet legend(props)}
<ChartLegend {...props} />
{/snippet}
<LineChart title="Revenue" {data} renderLegend={legend} legend={{ position: 'right' }} />// React
<LineChart
title="Revenue"
data={data}
legend={{ position: 'right' }}
renderLegend={(props) => <ChartLegend {...props} />}
/>Props
| Prop | Type | Default | Description |
|---|---|---|---|
items |
LegendItem[] |
required | Entries with name, color and visible |
toggle |
(name: string) => void |
required | Show or hide an item |
position |
'top' | 'right' | 'bottom' | 'left' |
'bottom' |
Placement, used to pick the orientation |
chartTitle |
string |
- | Labels the list as "{chartTitle} legend" |
orientation |
'horizontal' | 'vertical' |
vertical for left and right | Item flow |
class |
string |
- | Additional classes (className in React) |
setVisible |
(name: string, visible: boolean) => void |
- | Set an item's visibility |
showOnly |
(name: string) => void |
- | Show only this item |
showAll |
() => void |
- | Show every item |
Custom Renderers
renderLegend receives LegendRenderProps, so you can build any legend:
interface LegendRenderProps {
items: { name: string; color: string; visible: boolean }[];
position: 'top' | 'right' | 'bottom' | 'left';
chartTitle: string;
toggle: (name: string) => void;
setVisible: (name: string, visible: boolean) => void;
showOnly: (name: string) => void;
showAll: () => void;
}{#snippet legend({ items, showOnly, showAll })}
<div class="flex gap-2">
{#each items as item (item.name)}
<button type="button" onclick={() => showOnly(item.name)}>{item.name}</button>
{/each}
<button type="button" onclick={showAll}>All</button>
</div>
{/snippet}The legend is placed by legend.position and rendered outside the chart's role="img"
element, so its controls stay reachable by keyboard and screen readers. Use
onLegendChange to react to visibility changes from either legend.
Accessibility
- Each item is a
<button>witharia-pressedreflecting visibility - The list is labelled with the chart title
- Hidden items are dimmed and struck through, not only recoloured