Legend
Charts with a legend field take true, false, or options:
ts
createChart(host, {
type: 'xy',
legend: { position: 'right', align: 'start' },
categories: ['Q1', 'Q2', 'Q3', 'Q4'],
series: [/* … */],
});| Option | Values |
|---|---|
position | bottom (default), top, left, right |
align | center (default), start, end: along the bottom or top line, or down the column on a side |
onClick | (name, visible) => …: called before a name is switched; return false to keep it as it is |
- On a side, the legend takes a column of about a quarter of the width, one name by line. Under 360 pixels wide it goes back to the bottom, so small charts keep their room.
xy,scatter,pie,radar,density,ecdf,qq,flowmap,dotdensityandpiemaptake the options. On apie,legend: truewrites a legend instead of the labels around it;falsehides it.
onClick
visible is the state the name is about to take.
ts
legend: {
onClick: (name, visible) => {
if (!visible && name === 'Total') return false; // Total cannot be switched off
track('legend', name, visible);
},
},The onToggle render option is still called after each switch.
A legend of your own
Turn the legend off, read its names with legendItems(), and switch them with toggle():
ts
const chart = createChart(host, { ...spec, legend: false });
function drawLegend() {
list.replaceChildren(
...chart.legendItems().map(({ name, color, visible }) => {
const button = document.createElement('button');
button.textContent = name;
button.style.borderLeft = `12px solid ${color}`;
button.setAttribute('aria-pressed', String(visible));
button.onclick = () => {
chart.toggle(name);
drawLegend();
};
return button;
}),
);
}
drawLegend();legendItems() returns { name, color, visible } for each name: those of the legend drawn, or, without one, the series (or the slices of a pie) of the spec. Colours chosen with setColor or setPalette are included.