Skip to content

Chart legend

Usage with charts ​

  • For usage with Line chart, refer to the example in the Line chart.
  • For usage with Bar chart, refer to the example in the Stacked bar chart.
  • For usage with Donut chart, refer to the example in the Donut chart.

Table view ​

tsx
import { Chart, type LegendDataMap } from '@semcore/ui/d3-chart';
import { Text } from '@semcore/ui/typography';
import React from 'react';

import LineChartMockData from './mock';
const data = LineChartMockData.ThreeLines;
const legendItems = Object.keys(data[0])
  .filter((key) => key !== 'x')
  .reduce<LegendDataMap<'Table'>>((acc, item, index) => {
    acc[item] = {
      label: `Item ${index + 1}`,
      columns: [
        <Text use='secondary' key={1}>
          {(42 * (index + 3)) / 10}
          %
        </Text>,
        <Text use='primary' key={2}>{42 * (index + 3)}</Text>,
      ],
    };

    return acc;
  }, {});

const Demo = () => {
  return (
    <Chart.Line
      data={data}
      plotWidth={500}
      plotHeight={200}
      groupKey='x'
      xTicksCount={data.length / 2}
      aria-label='Line chart'
      showLegend={true}
      legendProps={{
        legendType: 'Table',
        legendMap: legendItems,
      }}
      direction='row'
    />
  );
};

export default Demo;

Legend with metrics ​

Passing rows instead of columns changes the legend table layout.

tsx
import DiffDown from '@semcore/icon/DiffDown/m';
import DiffUp from '@semcore/icon/DiffUp/m';
import { Chart, Metric, type LegendDataMap } from '@semcore/ui/d3-chart';
import React from 'react';

import LineChartMockData from './mock';

const metricData = [
  {
    value: '15%',
    diffValue: '1%',
    diffUse: 'good' as const,
    diffIcon: DiffUp,
    href: '/some-report',
  },
  {
    value: '3.5K',
    diffValue: '0.5',
    diffUse: 'bad' as const,
    diffIcon: DiffDown,
  },
  {
    value: '12.3',
    diffValue: 'no change',
    diffUse: 'neutral' as const,
    href: '/some-report',
  },
];

const data = LineChartMockData.ThreeLines;
const legendItems = Object.keys(data[0])
  .filter((key) => key !== 'x')
  .reduce<LegendDataMap<'Table'>>((acc, item, index) => {
    acc[item] = {
      label: `Item ${index + 1}`,
      rows: [
        <Metric
          key={1}
          value={metricData[index].value}
          diffValue={metricData[index].diffValue}
          href={metricData[index].href}
          diffIcon={metricData[index].diffIcon}
          diffUse={metricData[index].diffUse}
        />,
      ],
    };

    return acc;
  }, {});

const Demo = () => {
  return (
    <Chart.Line
      data={data}
      plotWidth={500}
      plotHeight={200}
      groupKey='x'
      xTicksCount={data.length / 2}
      aria-label='Line chart'
      showLegend={true}
      legendProps={{
        legendType: 'Table',
        legendMap: legendItems,
      }}
    />
  );
};

export default Demo;

Released under the MIT License.

Released under the MIT License.