차트 - 범례
차트 - 범례 (Legend)
차트 범례에서 시리즈와 데이터를 식별하는 방법을 커스터마이즈하는 방법에 대해 알아봅니다.
본문
범례는 심볼과 색상을 시리즈 라벨에 매핑하는 UI 요소로, 사용자가 차트의 서로 다른 데이터 시리즈를 식별하도록 돕습니다.
차트 컴포넌트에서 범례는 label 속성을 가진 시리즈와 그 색상을 연결합니다.
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import dataset from '../dataset/random/scatterParallel.json';
export default function BasicLegend() {
return (
<ScatterChart
series={[
{ label: 'Var A', datasetKeys: { id: 'id', x: 'x1', y: 'y1' } },
{ label: 'Var B', datasetKeys: { id: 'id', x: 'x2', y: 'y2' } },
]}
dataset={dataset}
height={300}
/>
);
}
표시 여부 토글 (Toggle visibility)
toggleVisibilityOnClick prop을 true로 설정하면 클릭으로 표시 여부를 토글하는 상호작용을 활성화할 수 있습니다.
범례 항목을 클릭하면 차트에서 해당 시리즈나 데이터 항목이 숨겨지거나 다시 표시됩니다.
숨겨진 항목은 범례에서 낮은 투명도로 표시됩니다.
기본적으로 축은 모든 시리즈를 기준으로 도메인을 계산합니다.
보이는 시리즈만 고려하려면 축 속성 domainSeries를 'visible'로 설정하세요.
이 데모는 시리즈를 숨기는 것이 x축에 어떤 영향을 줄 수 있는지 보여줍니다.
import * as React from 'react';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import { BarChart } from '@mui/x-charts/BarChart';
import { dataset, valueFormatter } from '../dataset/weather';
const series = [
{ dataKey: 'london', label: 'London', valueFormatter },
{ dataKey: 'paris', label: 'Paris', valueFormatter },
{ dataKey: 'newYork', label: 'New York', valueFormatter },
];
export default function ToggleSeriesVisibility() {
const [domainSeries, setDomainSeries] = React.useState<'all' | 'visible'>('all');
return (
<div style={{ width: '100%' }}>
<FormControlLabel
control={
<Checkbox
checked={domainSeries === 'visible'}
onChange={(event) =>
setDomainSeries(event.target.checked ? 'visible' : 'all')
}
/>
}
label="x-axis domain considers only visible series"
labelPlacement="end"
/>
<BarChart
dataset={dataset}
yAxis={[{ scaleType: 'band', dataKey: 'month' }]}
xAxis={[{ label: 'rainfall (mm)', domainSeries }]}
series={series}
layout="horizontal"
height={300}
slotProps={{ legend: { toggleVisibilityOnClick: true } }}
/>
</div>
);
}
스택 시리즈의 경계 케이스 (Stack series edge case)
시리즈가 스택되어 있는 경우 domainSeries: 'visible'을 사용하는 것을 권장합니다.
그렇지 않으면 바닥 시리즈를 숨길 때 다른 시리즈가 축 도메인 밖으로 나갈 수 있습니다.
이 데모에서는 파란색 시리즈(New York)를 숨기면 기대한 대로 다른 두 시리즈의 값이 감소합니다. 하지만 y축이 이를 고려하지 않으면 50보다 작은 값을 가진 노란색 시리즈가 드로잉 영역 밖으로 나가게 됩니다.
import * as React from 'react';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import { LineChart } from '@mui/x-charts/LineChart';
import { dataset, valueFormatter } from '../dataset/weather';
const series = [
{ dataKey: 'newYork', label: 'New York', valueFormatter, stack: 'a' },
{ dataKey: 'london', label: 'London', valueFormatter, stack: 'a' },
{ dataKey: 'paris', label: 'Paris', valueFormatter, stack: 'a' },
];
export default function StackLineVisibility() {
const [domainSeries, setDomainSeries] = React.useState<'all' | 'visible'>('all');
return (
<div style={{ width: '100%' }}>
<FormControlLabel
control={
<Checkbox
checked={domainSeries === 'visible'}
onChange={(event) =>
setDomainSeries(event.target.checked ? 'visible' : 'all')
}
/>
}
label="y-axis domain considers only visible series"
labelPlacement="end"
/>
<LineChart
dataset={dataset}
xAxis={[{ scaleType: 'band', dataKey: 'month' }]}
yAxis={[{ label: 'rainfall (mm)', domainSeries }]}
series={series}
height={300}
slotProps={{
legend: {
toggleVisibilityOnClick: true,
},
}}
/>
</div>
);
}
표시 여부 변경 콜백 (Visibility change callback)
차트 컴포넌트에서 onHiddenItemsChange()를 사용해 표시 여부 변경을 감지할 수 있습니다.
이 콜백 함수는 표시 여부 상태가 바뀔 때마다 숨겨진 항목 식별자들의 배열을 받습니다.
초기 숨김 항목을 설정하려면 initialHiddenItems prop을 사용합니다.
아래 데모는 시리즈의 표시 여부를 토글하고 현재 보이는 시리즈 수를 확인할 수 있는 라인 차트입니다.
import * as React from 'react';
import { LineChart } from '@mui/x-charts/LineChart';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import type { VisibilityIdentifier } from '@mui/x-charts/plugins';
const series = [
{ id: 'series-a', data: [20, 30, 25, 40, 30], label: 'Series A' },
{ id: 'series-b', data: [15, 25, 20, 35, 20], label: 'Series B' },
{ id: 'series-c', data: [10, 20, 15, 30, 25], label: 'Series C' },
];
export default function VisibilityOnChange() {
const [hiddenItems, setHiddenItems] = React.useState<VisibilityIdentifier[]>([]);
const visibleCount = series.length - hiddenItems.length;
return (
<Stack direction="column" spacing={2} sx={{ width: '100%' }}>
<LineChart
series={series}
height={300}
slotProps={{
legend: {
toggleVisibilityOnClick: true,
},
}}
initialHiddenItems={[{ type: 'line', seriesId: 'series-a' }]}
onHiddenItemsChange={(newHiddenItems) => setHiddenItems(newHiddenItems)}
/>
<Typography variant="body2" sx={{ textAlign: 'center' }}>
Visible series: {visibleCount} / {series.length}
</Typography>
</Stack>
);
}
:::info
toggleVisibilityOnClick prop을 onItemClick() 핸들러와 함께 사용할 수 있습니다.
둘 다 사용하면 onItemClick() 콜백이 먼저 실행되고, 그다음 onHiddenItemsChange()가 실행됩니다.
:::
제어된 표시 여부 (Controlled visibility)
hiddenItems prop을 사용해 표시 여부 상태를 외부에서 제어할 수 있습니다.
차트에서 숨겨야 할 항목 식별자들의 배열을 전달할 수 있습니다.
차트 유형마다 다른 식별자 형식을 사용합니다.
식별자를 만들 때는 VisibilityIdentifier 타입을 사용하세요.
시리즈 타입을 제네릭 매개변수로 받으며, 허용된 값을 좁히려면 VisibilityIdentifier<'line'>처럼 사용할 수 있습니다.
모든 식별자는 시리즈 타입(예: 'line', 'bar', 'pie')을 나타내는 type 필드를 요구합니다.
아래 데모는 버튼을 사용해 어떤 항목을 표시할지 제어하는 방법을 보여줍니다.
import * as React from 'react';
import { PieChart } from '@mui/x-charts/PieChart';
import Stack from '@mui/material/Stack';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import type { VisibilityIdentifierWithType } from '@mui/x-charts/plugins';
const data = [
{ value: 10, label: 'Series A' },
{ value: 15, label: 'Series B' },
{ value: 20, label: 'Series C' },
];
export default function ControlledVisibility() {
const [hiddenItems, setHiddenItems] = React.useState<
VisibilityIdentifierWithType<'pie'>[]
>([{ type: 'pie', seriesId: 'custom', dataIndex: 0 }]);
const handleShowAll = () => {
setHiddenItems([]);
};
const handleHideAll = () => {
setHiddenItems([
{ type: 'pie', seriesId: 'custom', dataIndex: 0 },
{ type: 'pie', seriesId: 'custom', dataIndex: 1 },
{ type: 'pie', seriesId: 'custom', dataIndex: 2 },
]);
};
const handleShowOnlyA = () => {
setHiddenItems([
{ type: 'pie', seriesId: 'custom', dataIndex: 1 },
{ type: 'pie', seriesId: 'custom', dataIndex: 2 },
]);
};
const handleToggleChange = (
_event: React.MouseEvent<HTMLElement>,
newValue: string | null,
) => {
if (newValue === 'all') {
handleShowAll();
} else if (newValue === 'none') {
handleHideAll();
} else if (newValue === 'onlyA') {
handleShowOnlyA();
}
};
const getCurrentValue = () => {
const allVisible = hiddenItems.length === 0;
const allHidden = hiddenItems.length === data.length;
const onlyAVisible =
hiddenItems.length === 2 &&
hiddenItems[0].dataIndex === 1 &&
hiddenItems[1].dataIndex === 2;
if (allVisible) {
return 'all';
}
if (allHidden) {
return 'none';
}
if (onlyAVisible) {
return 'onlyA';
}
return null;
};
return (
<Stack spacing={2}>
<FormControl sx={{ mb: 2 }}>
<FormLabel>Controlled Highlighting</FormLabel>
<ToggleButtonGroup
value={getCurrentValue()}
exclusive
onChange={handleToggleChange}
aria-label="highlight control"
size="small"
>
<ToggleButton value="all" aria-label="show all nodes">
Show All
</ToggleButton>
<ToggleButton value="none" aria-label="show no nodes">
Hide All
</ToggleButton>
<ToggleButton value="onlyA" aria-label="show only node A">
Show Only A
</ToggleButton>
</ToggleButtonGroup>
</FormControl>
<PieChart
series={[{ id: 'custom', data }]}
height={300}
width={300}
hiddenItems={hiddenItems}
slotProps={{
legend: {
toggleVisibilityOnClick: true,
},
}}
onHiddenItemsChange={(newIdentifiers) => setHiddenItems(newIdentifiers)}
/>
</Stack>
);
}
커스터마이징 (Customization)
아래에서 설명하는 클래스와 속성을 사용해 범례의 크기, 위치, 스타일을 커스터마이즈할 수 있습니다.
크기 (Dimensions)
CSS 속성을 사용해 범례의 많은 부분을 커스터마이즈할 수 있습니다.
범례 컨테이너의 주요 클래스는 .MuiChartsLegend-root입니다.
또는 CSS-in-JS(예: Material UI와 함께 Emotion 사용)를 쓴다면 legendClasses 변수로 요소를 타게팅할 수 있습니다.
각 범례 항목은 mark와 label이라는 두 가지 주요 요소로 구성됩니다.
아래 예시는 범례의 일부를 커스터마이즈하는 방법과 legendClasses 변수와 CSS 클래스를 모두 사용하는 방법을 보여줍니다.
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
import { PieChart } from '@mui/x-charts/PieChart';
import { legendClasses } from '@mui/x-charts/ChartsLegend';
const data = [
{ id: 0, value: 10, label: 'Series A' },
{ id: 1, value: 15, label: 'Series B' },
{ id: 2, value: 20, label: 'Series C' },
{ id: 3, value: 10, label: 'Series D' },
{ id: 4, value: 15, label: 'Series E' },
{ id: 5, value: 20, label: 'Series F' },
{ id: 6, value: 10, label: 'Series G' },
];
export default function LegendDimension() {
return (
<ChartsUsageDemo
componentName="Legend"
data={
{
direction: {
knob: 'select',
defaultValue: 'horizontal',
options: ['horizontal', 'vertical'],
},
markSize: { knob: 'number', defaultValue: 15, min: 0 },
markGap: { knob: 'number', defaultValue: 8, min: 0 },
itemGap: { knob: 'number', defaultValue: 16, min: 0 },
} as const
}
renderDemo={(props) => (
<PieChart
series={[{ data }]}
slotProps={{
legend: {
direction: props.direction,
sx: {
gap: `${props.itemGap}px`,
[`.${legendClasses.mark}`]: {
height: props.markSize,
width: props.markSize,
},
[`.${legendClasses.series}`]: {
gap: `${props.markGap}px`,
},
},
},
}}
height={200}
width={200}
/>
)}
getCode={({ props }) => {
return `import { PieChart } from '@mui/x-charts/PieChart';
import { legendClasses } from '@mui/x-charts/ChartsLegend';
<PieChart
{/** ... */}
slotProps={{
legend: {
direction: props.direction,
sx: {
gap: '${props.itemGap}px',
// CSS-in-JS
[\`.\\${legendClasses.mark}\`]: {
height: ${props.markSize},
width: ${props.markSize},
},
// CSS class
['.${legendClasses.series}']: {
gap: '${props.markGap}px',
},
},
},
}}
/>
`;
}}
/>
);
}
위치 (Position)
direction 속성을 사용해 범례를 'vertical' 또는 'horizontal' 레이아웃으로 표시할 수 있습니다.
또한 position: { vertical, horizontal } 속성으로 이동할 수 있는데, 이 속성은 부모 컨테이너에서 범례가 어떻게 정렬되는지 정의합니다.
vertical:'top','middle', 또는'bottom'horizontal:'left','middle', 또는'right'
기본적으로 범례는 차트 위에 배치됩니다.
위치 관리는 grid-template CSS 속성에 의존합니다.
커스텀 범례 컴포넌트를 만들면 컴포넌트를 올바르게 배치하기 위해 CSS 속성 grid-area를 'legend'로 설정해야 합니다.
:::warning
자체 포함 차트의 경우 position 속성은 slotProps.legend에서 사용할 수 있습니다.
커스텀 차트를 구성할 때는 이 동작이 ChartsWrapper의 legendPosition prop으로 처리됩니다.
또는 범례를 원하는 곳에 직접 배치할 수도 있습니다.
:::
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
import { PieChart } from '@mui/x-charts/PieChart';
const data = [
{ id: 0, value: 10, label: 'Series A' },
{ id: 1, value: 15, label: 'Series B' },
{ id: 2, value: 20, label: 'Series C' },
{ id: 3, value: 10, label: 'Series D' },
{ id: 4, value: 15, label: 'Series E' },
{ id: 5, value: 20, label: 'Series F' },
{ id: 6, value: 10, label: 'Series G' },
{ id: 7, value: 15, label: 'Series H' },
{ id: 8, value: 20, label: 'Series I' },
{ id: 9, value: 10, label: 'Series J' },
{ id: 10, value: 15, label: 'Series K' },
{ id: 11, value: 20, label: 'Series L' },
{ id: 12, value: 10, label: 'Series M' },
{ id: 13, value: 15, label: 'Series N' },
{ id: 14, value: 20, label: 'Series O' },
];
export default function LegendPosition() {
return (
<ChartsUsageDemo
componentName="Legend"
data={
{
direction: {
knob: 'select',
defaultValue: 'vertical',
options: ['horizontal', 'vertical'],
},
vertical: {
knob: 'select',
defaultValue: 'middle',
options: ['top', 'middle', 'bottom'],
},
horizontal: {
knob: 'select',
defaultValue: 'center',
options: ['start', 'center', 'end'],
},
itemsNumber: {
knob: 'number',
defaultValue: 3,
min: 1,
max: data.length,
},
} as const
}
renderDemo={(props) => (
<PieChart
series={[
{
data: data.slice(0, props.itemsNumber),
},
]}
height={200}
width={200}
slotProps={{
legend: {
direction: props.direction,
position: { vertical: props.vertical, horizontal: props.horizontal },
},
}}
/>
)}
getCode={({ props }) => {
return `import { PieChart } from '@mui/x-charts/PieChart';
<PieChart
{/** ... */}
slotProps={{
legend: {
direction: '${props.direction}',
position: {
vertical: '${props.vertical}',
horizontal: '${props.horizontal}'
}
}
}}
/>
`;
}}
/>
);
}
숨기기 (Hiding)
차트의 hideLegend prop으로 범례를 숨길 수 있습니다.
import * as React from 'react';
import Stack from '@mui/material/Stack';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import { PieChart } from '@mui/x-charts/PieChart';
const series = [
{
data: [
{ id: 0, value: 10, label: 'series A' },
{ id: 1, value: 15, label: 'series B' },
{ id: 2, value: 20, label: 'series C' },
],
},
];
export default function HiddenLegend() {
const [isHidden, setIsHidden] = React.useState(false);
const Toggle = (
<FormControlLabel
checked={isHidden}
control={<Checkbox onChange={(event) => setIsHidden(event.target.checked)} />}
label="hide the legend"
labelPlacement="end"
sx={{ margin: 'auto' }}
/>
);
return (
<Stack>
{Toggle}
<PieChart series={series} hideLegend={isHidden} width={200} height={200} />
</Stack>
);
}
라벨 스타일 (Label styling)
루트 컴포넌트의 폰트 속성을 타게팅하여 label 스타일을 바꿀 수 있습니다.
mark는 SVG 요소이므로 fill 속성으로 색상을 바꿀 수 있습니다.
아래 데모처럼 sx prop, CSS Modules, 또는 다른 CSS 방법을 사용해 이를 할 수 있습니다.
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
import { PieChart } from '@mui/x-charts/PieChart';
import { labelMarkClasses } from '@mui/x-charts/ChartsLabel';
const data = [
{ id: 0, value: 10, label: 'Series A' },
{ id: 1, value: 15, label: 'Series B' },
{ id: 2, value: 20, label: 'Series C' },
{ id: 3, value: 10, label: 'Series D' },
];
export default function LegendTextStyling() {
return (
<ChartsUsageDemo
componentName="Legend"
data={{
fontSize: { knob: 'number', defaultValue: 14 },
color: {
knob: 'select',
defaultValue: 'blue',
options: ['blue', 'red', 'green'],
},
markColor: {
knob: 'select',
defaultValue: 'blue',
options: ['blue', 'red', 'green'],
},
}}
renderDemo={(props) => (
<PieChart
series={[
{
data,
},
]}
height={200}
width={200}
slotProps={{
legend: {
sx: {
fontSize: props.fontSize,
color: props.color,
[`.${labelMarkClasses.fill}`]: {
fill: props.markColor,
},
},
},
}}
/>
)}
getCode={({ props }) => {
return `import { PieChart } from '@mui/x-charts/PieChart';
import { labelMarkClasses } from '@mui/x-charts/ChartsLabel';
<PieChart
{/** ... */}
slotProps={{
legend: {
sx: {
fontSize: ${props.fontSize},
color: ${props.color},
[\`.\\${labelMarkClasses.fill}\`]: {
fill: ${props.markColor},
},
},
},
}}
/>
`;
}}
/>
);
}
mark 모양 바꾸기 (Change mark shape)
시리즈 항목의 labelMarkType 속성을 사용해 mark 모양을 바꿀 수 있습니다.
pie 시리즈의 경우 labelMarkType 속성은 각 파이 조각에도 사용할 수 있습니다.
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
import { BarChart } from '@mui/x-charts/BarChart';
const series = [
{ id: 'id-0', data: [10], label: 'Series A' },
{ id: 'id-1', data: [15], label: 'Series B' },
{ id: 'id-2', data: [20], label: 'Series C' },
{ id: 'id-3', data: [10], label: 'Series D' },
];
export default function LegendMarkType() {
return (
<ChartsUsageDemo
componentName="Legend"
data={
{
markType: {
knob: 'select',
defaultValue: 'square',
options: ['square', 'circle', 'line'],
},
} as const
}
renderDemo={(props) => (
<BarChart
series={series.map((seriesItem) => ({
...seriesItem,
labelMarkType: props.markType,
}))}
xAxis={[{ data: ['A'] }]}
height={200}
/>
)}
getCode={({ props }) => {
return `import { BarChart } from '@mui/x-charts/BarChart';
<BarChart
{/** ... */}
series={
series.map((seriesItem) => ({
...seriesItem,
labelMarkType: '${props.markType}',
}))
}
/>
`;
}}
/>
);
}
커스텀 모양 (Custom shapes)
더 고급 사용 사례를 위해 각 시리즈의 labelMarkType 속성에 컴포넌트를 제공해 mark를 완전히 커스터마이즈할 수 있습니다.
import { BarChart } from '@mui/x-charts/BarChart';
import { ChartsLabelCustomMarkProps } from '@mui/x-charts/ChartsLabel';
function HTMLCircle({ className, color }: ChartsLabelCustomMarkProps) {
return (
<div className={className} style={{ borderRadius: '100%', background: color }} />
);
}
function SVGDiamond({ className, color }: ChartsLabelCustomMarkProps) {
return (
<svg viewBox="-7.423 -7.423 14.846 14.846">
<path
className={className}
d="M0,-7.423L4.285,0L0,7.423L-4.285,0Z"
fill={color}
/>
</svg>
);
}
export default function LegendCustomLabelMark() {
return (
<BarChart
series={[
{ id: 'id-0', data: [10, 15], label: 'Series A', labelMarkType: HTMLCircle },
{ id: 'id-1', data: [15, 20], label: 'Series B', labelMarkType: 'line' },
{ id: 'id-2', data: [20, 25], label: 'Series C' },
{ id: 'id-3', data: [10, 15], label: 'Series D', labelMarkType: SVGDiamond },
]}
xAxis={[{ data: ['Category 1', 'Category 2'] }]}
height={200}
/>
);
}
labelMarkType에 컴포넌트를 전달하면 범례뿐만 아니라 툴팁처럼 라벨 mark가 표시되는 다른 곳에도 영향을 줍니다.
시리즈를 기준으로 파이 차트의 mark 모양을 커스터마이즈하는 것은 조금 다릅니다. 자세한 내용은 이 예시를 참고하세요.
그라데이션과 패턴과의 호환성을 보장하려면 labelMarkType에서 HTML 대신 SVG를 사용하는 것을 고려하세요.
스크롤 가능한 범례 (Scrollable legend)
세로 범례에는 overflowY, 가로 범례에는 overflowX를 설정해 범례를 스크롤 가능하게 만들 수 있습니다.
스크롤을 활성화하려면 범례 컨테이너에 고정된 높이나 너비가 있어야 합니다.
import Stack from '@mui/material/Stack';
import { PieChart } from '@mui/x-charts/PieChart';
const series = [
{
data: [
{ id: 0, value: 10, label: 'Series A' },
{ id: 1, value: 15, label: 'Series B' },
{ id: 2, value: 20, label: 'Series C' },
{ id: 3, value: 10, label: 'Series D' },
{ id: 4, value: 15, label: 'Series E' },
{ id: 5, value: 20, label: 'Series F' },
{ id: 6, value: 10, label: 'Series G' },
{ id: 7, value: 15, label: 'Series H' },
{ id: 8, value: 20, label: 'Series I' },
{ id: 9, value: 10, label: 'Series J' },
{ id: 10, value: 15, label: 'Series K' },
{ id: 11, value: 20, label: 'Series L' },
{ id: 12, value: 10, label: 'Series M' },
{ id: 13, value: 15, label: 'Series N' },
{ id: 14, value: 20, label: 'Series O' },
],
},
];
export default function ScrollableLegend() {
return (
<Stack sx={{ height: 200, width: 200 }}>
<PieChart
series={series}
sx={{
height: '100%',
}}
slotProps={{
legend: {
sx: {
overflowY: 'scroll',
flexWrap: 'nowrap',
height: '100%',
},
},
}}
/>
</Stack>
);
}
시리즈 스타일링 (Series styling)
CSS를 사용해 범례에 있는 시리즈를 스타일링할 수 있습니다.
각 범례 항목에는 data-series 속성이 있으며, 그 값은 해당 항목이 나타내는 시리즈의 ID입니다.
import { LineChart, LineChartProps, lineClasses } from '@mui/x-charts/LineChart';
import { legendClasses } from '@mui/x-charts/ChartsLegend';
import { labelMarkClasses } from '@mui/x-charts/ChartsLabel';
const monthlySalesData = [
{ month: 'Jan', productA: 120, productB: 90 },
{ month: 'Feb', productA: 130, productB: 100 },
{ month: 'Mar', productA: 125, productB: 110 },
{ month: 'Apr', productA: 150, productB: 95 },
{ month: 'May', productA: 160, productB: 105 },
{ month: 'Jun', productA: 170, productB: 115 },
{ month: 'Jul', productA: 165, productB: 120 },
{ month: 'Aug', productA: 175, productB: 130 },
{ month: 'Sep', productA: 180, productB: 125 },
{ month: 'Oct', productA: 190, productB: 135 },
{ month: 'Nov', productA: 200, productB: 140 },
{ month: 'Dec', productA: 210, productB: 145 },
];
const settings = {
series: [
{
data: monthlySalesData.map((d) => d.productA),
label: 'Product A',
id: 'a',
},
{
data: monthlySalesData.map((d) => d.productB),
label: 'Product B',
id: 'b',
},
],
xAxis: [
{
scaleType: 'point',
data: monthlySalesData.map((d) => d.month),
},
],
yAxis: [{ width: 50, label: 'Sales' }],
height: 300,
margin: { right: 24 },
} satisfies LineChartProps;
export default function LegendStyleSeries() {
return (
<LineChart
{...settings}
sx={{
[`.${lineClasses.line}, .${labelMarkClasses.fill}`]: {
strokeWidth: 1,
},
[`.${lineClasses.line}[data-series="a"], .${legendClasses.item}[data-series="a"] .${labelMarkClasses.fill}`]:
{
strokeDasharray: '5 5',
},
[`.${lineClasses.line}[data-series="b"], .${legendClasses.item}[data-series="b"] .${labelMarkClasses.fill}`]:
{
strokeDasharray: '3 2',
},
[`.${labelMarkClasses.root}`]: {
width: 24,
},
}}
/>
);
}
커스텀 컴포넌트 (Custom component)
고급 커스터마이징을 위해 useLegend() 훅으로 직접 만든 범례를 만들 수 있습니다.
이 훅은 기본 범례가 그릴 항목들을 반환하므로 렌더링에 집중할 수 있습니다.
아래 데모는 labelMarkType을 useLegend()와 함께 사용해 커스텀 모양을 가진 범례를 만드는 방법을 보여줍니다.
이 접근 방식은 slots를 사용해 범례 항목을 렌더링합니다. 커스텀 차트를 구성할 때 이를 구현하는 방법은 HTML 컴포넌트를 참고하세요.
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { useTheme } from '@mui/material/styles';
import { useLegend } from '@mui/x-charts/hooks';
import { LineChart, lineClasses } from '@mui/x-charts/LineChart';
import {
ChartsLabelCustomMarkProps,
ChartsLabelMark,
} from '@mui/x-charts/ChartsLabel';
function LineWithMark({ color, className }: ChartsLabelCustomMarkProps) {
return (
<svg
viewBox="0 0 24 24"
stroke={color}
strokeWidth={3}
strokeLinecap="round"
fill="none"
className={className}
>
<path d="M 1 12.5 L 7 12.5 M 17 12.5 L 23 12.5" />
<circle cx={12} cy={12.5} r={5} />
</svg>
);
}
function DashedLine({ color, className }: ChartsLabelCustomMarkProps) {
return (
<svg
viewBox="0 0 24 24"
stroke={color}
strokeWidth={3}
fill="none"
className={className}
>
<path d="M 1 12.5 L 23 12.5" strokeDasharray="5 3" />
</svg>
);
}
function MyCustomLegend() {
const { items } = useLegend();
return (
<Stack direction="column" sx={{ justifySelf: 'start', marginLeft: 9 }}>
{items.map((item) => {
const { label, color, seriesId, markType } = item;
return (
<Box
key={seriesId}
sx={{
display: 'flex',
alignItems: 'center',
gap: 1,
backgroundColor:
seriesId === 'avg' ? 'rgba(156,40,40,0.5)' : 'transparent',
padding: 1,
}}
>
<ChartsLabelMark type={markType} color={color} />
<Typography sx={{ display: 'inline-block' }}>{`${label}`}</Typography>
</Box>
);
})}
</Stack>
);
}
const dataset = [
{ month: 'Jan', '1991_2020_avg': 4.1, 2023: 3.9 },
{ month: 'Fev', '1991_2020_avg': 4.7, 2023: 8.9 },
{ month: 'Mar', '1991_2020_avg': 7.5, 2023: 9.5 },
{ month: 'Apr', '1991_2020_avg': 10.6, 2023: 11.5 },
{ month: 'May', '1991_2020_avg': 13.8, 2023: 15.5 },
{ month: 'Jun', '1991_2020_avg': 16.7, 2023: 16.4 },
{ month: 'Jul', '1991_2020_avg': 18.9, 2023: 19.5 },
{ month: 'Aug', '1991_2020_avg': 18.8, 2023: 20.5 },
{ month: 'Sep', '1991_2020_avg': 15.8, 2023: 16.4 },
{ month: 'Oct', '1991_2020_avg': 11.9, 2023: 13.2 },
{ month: 'Nov', '1991_2020_avg': 7.6, 2023: 8.1 },
{ month: 'Dec', '1991_2020_avg': 4.7, 2023: 6.1 },
];
export default function CustomLegend() {
const theme = useTheme();
return (
<Box
sx={{ height: 300, width: '100%', display: 'flex', flexDirection: 'column' }}
>
<LineChart
dataset={dataset}
series={[
{
id: 'avg',
label: 'temp. avg. 1991-2020 (°C)',
dataKey: '1991_2020_avg',
color: theme.palette.text.primary,
labelMarkType: DashedLine,
},
{
id: '2023-temp',
label: 'temp. 2023 (°C)',
dataKey: '2023',
color: theme.palette.primary.main,
labelMarkType: LineWithMark,
showMark: true,
},
]}
xAxis={[{ dataKey: 'month', scaleType: 'band', id: 'x-axis' }]}
sx={{
[`& .${lineClasses.line}[data-series="avg"]`]: {
strokeDasharray: '10 5',
},
}}
slots={{ legend: MyCustomLegend }}
/>
</Box>
);
}
컬러 범례 (Color legend)
colorMap와 연결된 범례를 표시하려면 다음을 사용할 수 있습니다.
colorMap.type='continuous'를 사용한다면ContinuousColorLegendcolorMap.type='piecewise'를 사용한다면PiecewiseColorLegend
원하는 범례를 표시하려면 legend slot을 재정의하거나, composition API를 사용해 필요한 만큼 범례를 추가할 수 있습니다.
import { LineChart, LineChartProps } from '@mui/x-charts/LineChart';
import { PiecewiseColorLegend } from '@mui/x-charts/ChartsLegend';
import Stack from '@mui/material/Stack';
import { dataset } from './tempAnomaly';
const data: LineChartProps = {
dataset,
series: [
{
label: 'Global temperature anomaly relative to 1961-1990',
dataKey: 'anomaly',
valueFormatter: (value) => `${value?.toFixed(2)}°`,
},
],
xAxis: [
{
scaleType: 'time',
dataKey: 'year',
disableLine: true,
valueFormatter: (value) => value.getFullYear().toString(),
colorMap: {
type: 'piecewise',
thresholds: [new Date(1961, 0, 1), new Date(1990, 0, 1)],
colors: ['blue', 'gray', 'red'],
},
},
],
yAxis: [
{
disableLine: true,
disableTicks: true,
valueFormatter: (value: number) => `${value}°`,
},
],
grid: { horizontal: true },
height: 300,
margin: { top: 20, right: 20 },
};
export default function VeryBasicColorLegend() {
return (
<Stack sx={{ width: '100%' }}>
<LineChart
{...data}
xAxis={[
{
...data.xAxis![0],
colorMap: {
type: 'piecewise',
thresholds: [new Date(1961, 0, 1), new Date(1990, 0, 1)],
colors: ['blue', 'gray', 'red'],
},
},
]}
slots={{ legend: PiecewiseColorLegend }}
slotProps={{ legend: { axisDirection: 'x' } }}
/>
</Stack>
);
}
데이터 선택 (Select data)
표시할 컬러 매핑을 선택하려면 다음 prop들을 사용합니다.
axisDirection:'x','y', 또는'z'—colorMap정의가 포함된 축을 나타냅니다.axisId: 사용할 축의 ID (선택한 방향에 여러 축이 있을 경우)
import Typography from '@mui/material/Typography';
import { LineChart } from '@mui/x-charts/LineChart';
import { ChartsReferenceLine } from '@mui/x-charts/ChartsReferenceLine';
import { PiecewiseColorLegend } from '@mui/x-charts/ChartsLegend';
import Stack from '@mui/material/Stack';
import { dataset } from './tempAnomaly';
export default function BasicColorLegend() {
return (
<Stack sx={{ width: '100%' }}>
<Typography variant="body1">
Global temperature anomaly relative to 1961-1990 average
</Typography>
<LineChart
dataset={dataset}
series={[
{
label: 'Global temperature anomaly relative to 1961-1990',
dataKey: 'anomaly',
valueFormatter: (value) => `${value?.toFixed(2)}°`,
},
]}
xAxis={[
{
scaleType: 'time',
dataKey: 'year',
disableLine: true,
valueFormatter: (value) => value.getFullYear().toString(),
colorMap: {
type: 'piecewise',
thresholds: [new Date(1961, 0, 1), new Date(1990, 0, 1)],
colors: ['blue', 'gray', 'red'],
},
},
]}
yAxis={[
{
disableLine: true,
disableTicks: true,
valueFormatter: (value: number) => `${value}°`,
},
]}
grid={{ horizontal: true }}
height={300}
slotProps={{
legend: {
axisDirection: 'x',
direction: 'vertical',
},
}}
slots={{
legend: PiecewiseColorLegend,
}}
>
<ChartsReferenceLine y={0} />
</LineChart>
</Stack>
);
}
위치 (Position)
컬러 범례의 위치는 시리즈 범례와 같은 방식으로 작동합니다.
라벨 위치 (Label position)
labelPosition prop을 사용해 라벨을 mark나 그라데이션과 관련해 배치할 수 있습니다.
허용되는 값은 'start', 'end', 'extremes'입니다.
piecewise 범례에는 추가로 'inline-start'와 'inline-end' 옵션이 있습니다.
direction='horizontal'일 때,'start'는 라벨을 시각적 mark 위에,'end'는 아래에 배치합니다.direction='vertical'일 때,'start'는 라벨을 시각적 mark의 왼쪽에,'end'는 오른쪽에 배치합니다.'extremes'를 사용하면 라벨이 시각적 mark의 시작과 끝 양쪽에 배치됩니다.
piecewise 범례에서는 두 가지 추가 값이 허용됩니다.
direction='horizontal'일 때,'inline-start'와'inline-end'는 라벨을 mark와 같은 줄(inline)에 배치합니다.direction='vertical'일 때, 이 값들은'start'와'end'와 동일하게 작동합니다.
import { interpolateRdYlBu } from 'd3-scale-chromatic';
import {
ContinuousColorLegend,
piecewiseColorDefaultLabelFormatter,
PiecewiseColorLegend,
PiecewiseLabelFormatterParams,
} from '@mui/x-charts/ChartsLegend';
import { ChartsDataProvider } from '@mui/x-charts/ChartsDataProvider';
import { ChartsAxesGradients } from '@mui/x-charts/internals';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Divider from '@mui/material/Divider';
export default function LegendLabelPositions() {
const piecewiseFormatter = (params: PiecewiseLabelFormatterParams) =>
params.index === 0 || params.index === params.length
? piecewiseColorDefaultLabelFormatter(params)
: '';
return (
<ChartsDataProvider
series={[]}
width={200}
height={200}
yAxis={[
{
valueFormatter: (value: number) => `${value}°`,
colorMap: {
type: 'continuous',
min: -0.5,
max: 1.5,
color: (t) => interpolateRdYlBu(1 - t),
},
},
]}
xAxis={[
{
valueFormatter: (value: number) => `${value}°`,
colorMap: {
type: 'piecewise',
thresholds: [0, 1.5],
colors: [
interpolateRdYlBu(0.9),
interpolateRdYlBu(0.5),
interpolateRdYlBu(0.1),
],
},
},
]}
>
<Stack
direction="column"
spacing={2}
sx={{ width: '100%', height: '100%', gap: 4 }}
>
<Stack direction="column" sx={{ width: '100%', height: '100%', gap: 2 }}>
<Typography variant="h4">Continuous</Typography>
<Typography variant="h5">Horizontal</Typography>
<Stack
direction="row"
sx={{ flexWrap: 'wrap', gap: 2, '&>div': { flex: 1 } }}
>
<div>
<Typography>start</Typography>
<ContinuousColorLegend
axisDirection="y"
direction="horizontal"
labelPosition="start"
/>
</div>
<div>
<Typography>end</Typography>
<ContinuousColorLegend
axisDirection="y"
direction="horizontal"
labelPosition="end"
/>
</div>
<div>
<Typography>extremes</Typography>
<ContinuousColorLegend
axisDirection="y"
direction="horizontal"
labelPosition="extremes"
/>
</div>
</Stack>
<Divider />
<Typography variant="h5">Vertical</Typography>
<Stack
direction="row"
sx={{
flexWrap: 'wrap',
height: 150,
gap: 2,
'&>div': {
flex: 1,
height: '100%',
display: 'flex',
flexDirection: 'column',
},
'& .MuiContinuousColorLegend-root': { flex: 1 },
}}
>
<div>
<Typography>start</Typography>
<ContinuousColorLegend
axisDirection="y"
direction="vertical"
labelPosition="start"
/>
</div>
<div>
<Typography>end</Typography>
<ContinuousColorLegend
axisDirection="y"
direction="vertical"
labelPosition="end"
/>
</div>
<div>
<Typography>extremes</Typography>
<ContinuousColorLegend
axisDirection="y"
direction="vertical"
labelPosition="extremes"
/>
</div>
</Stack>
</Stack>
<Stack direction="column" sx={{ width: '100%', height: '100%', gap: 2 }}>
<Typography variant="h4">Piecewise</Typography>
<Typography variant="h5">Horizontal</Typography>
<Stack
direction="row"
sx={{ flexWrap: 'wrap', gap: 2, '&>div': { flex: 1 } }}
>
<div>
<Typography>start</Typography>
<PiecewiseColorLegend
axisDirection="x"
direction="horizontal"
labelPosition="start"
labelFormatter={piecewiseFormatter}
/>
</div>
<div>
<Typography>end</Typography>
<PiecewiseColorLegend
axisDirection="x"
direction="horizontal"
labelPosition="end"
labelFormatter={piecewiseFormatter}
/>
</div>
<div>
<Typography>extremes</Typography>
<PiecewiseColorLegend
axisDirection="x"
direction="horizontal"
labelPosition="extremes"
labelFormatter={piecewiseFormatter}
/>
</div>
<div>
<Typography>inline-start</Typography>
<PiecewiseColorLegend
axisDirection="x"
direction="horizontal"
labelPosition="inline-start"
/>
</div>
<div>
<Typography>inline-end</Typography>
<PiecewiseColorLegend
axisDirection="x"
direction="horizontal"
labelPosition="inline-end"
/>
</div>
</Stack>
<Divider />
<Typography variant="h5">Vertical</Typography>
<Stack
direction="row"
sx={{
flexWrap: 'wrap',
gap: 2,
'&>div': {
flex: 1,
height: '100%',
display: 'flex',
flexDirection: 'column',
},
}}
>
<div>
<Typography>start</Typography>
<PiecewiseColorLegend
axisDirection="x"
direction="vertical"
labelPosition="start"
/>
</div>
<div>
<Typography>end</Typography>
<PiecewiseColorLegend
axisDirection="x"
direction="vertical"
labelPosition="end"
/>
</div>
<div>
<Typography>extremes</Typography>
<PiecewiseColorLegend
axisDirection="x"
direction="vertical"
labelPosition="extremes"
labelFormatter={piecewiseFormatter}
/>
</div>
<div>
<Typography>inline-start</Typography>
<PiecewiseColorLegend
axisDirection="x"
direction="vertical"
labelPosition="inline-start"
/>
</div>
<div>
<Typography>inline-end</Typography>
<PiecewiseColorLegend
axisDirection="x"
direction="vertical"
labelPosition="inline-end"
/>
</div>
</Stack>
</Stack>
</Stack>
<svg width={0} height={0}>
<ChartsAxesGradients />
</svg>
</ChartsDataProvider>
);
}
연속 컬러 매핑 (Continuous color mapping)
length와 thickness prop을 사용해 그라데이션의 모양을 수정할 수 있습니다.
length는 숫자(px 단위) 또는 퍼센트 문자열일 수 있습니다.
"100%"는 부모 차원에 해당합니다.
라벨을 포맷하려면 minLabel/maxLabel prop을 사용합니다.
표시할 문자열 또는 ({value, formattedValue}) => string 함수를 받습니다.
reverse prop으로 그라데이션을 반대로 뒤집을 수도 있습니다.
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
import { interpolateRdYlBu } from 'd3-scale-chromatic';
import { LineChart } from '@mui/x-charts/LineChart';
import { ChartsReferenceLine } from '@mui/x-charts/ChartsReferenceLine';
import { ContinuousColorLegend } from '@mui/x-charts/ChartsLegend';
import { dataset } from './tempAnomaly';
export default function ContinuousInteractiveDemo() {
return (
<ChartsUsageDemo
componentName="Legend"
data={
{
direction: {
knob: 'select',
defaultValue: 'horizontal',
options: ['horizontal', 'vertical'],
},
labelPosition: {
knob: 'select',
defaultValue: 'end',
options: ['start', 'end', 'extremes'],
},
length: {
knob: 'number',
defaultValue: 50,
min: 10,
},
thickness: {
knob: 'number',
defaultValue: 12,
min: 1,
max: 20,
},
reverse: {
knob: 'switch',
defaultValue: false,
},
} as const
}
renderDemo={(props) => (
<LineChart
dataset={dataset}
series={[
{
label: 'Global temperature anomaly relative to 1961-1990',
dataKey: 'anomaly',
valueFormatter: (value) => `${value?.toFixed(2)}°`,
},
]}
xAxis={[
{
scaleType: 'time',
dataKey: 'year',
disableLine: true,
valueFormatter: (value) => value.getFullYear().toString(),
},
]}
yAxis={[
{
disableLine: true,
disableTicks: true,
valueFormatter: (value: number) => `${value}°`,
colorMap: {
type: 'continuous',
min: -0.5,
max: 1.5,
color: (t) => interpolateRdYlBu(1 - t),
},
},
]}
grid={{ horizontal: true }}
height={300}
slots={{ legend: ContinuousColorLegend }}
slotProps={{
legend: {
axisDirection: 'y',
direction: props.direction,
thickness: props.thickness,
labelPosition: props.labelPosition,
reverse: props.reverse,
sx: {
[props.direction === 'horizontal' ? 'width' : 'height']:
`${props.length}${props.direction === 'horizontal' ? '%' : 'px'}`,
},
},
}}
>
<ChartsReferenceLine y={0} />
</LineChart>
)}
getCode={({ props }) => {
return `import { ContinuousColorLegend } from '@mui/x-charts/ChartsLegend';
<LineChart
{/** ... */}
slots={{ legend: ContinuousColorLegend }}
slotProps={{
legend: {
axisDirection: 'y',
direction: '${props.direction}',
thickness: ${props.thickness},
labelPosition: '${props.labelPosition}',
reverse: ${props.reverse},
sx: { ${props.direction === 'horizontal' ? 'width' : 'height'}: '${props.length}${props.direction === 'horizontal' ? '%' : 'px'}' },
},
}}
/>
`;
}}
/>
);
}
piecewise 컬러 매핑 (Piecewise color mapping)
piecewise 범례는 컬러 매핑에 있어 시리즈 범례와 유사하며, 커스터마이징에 대해 동일한 prop들을 받습니다.
기본으로 생성되는 라벨을 재정의하려면 labelFormatter prop을 제공합니다.
이 prop은 piece의 최솟값이나 최댓값을 받아 라벨을 반환합니다.
첫 번째와 마지막 piece의 값은 null일 수 있습니다.
null을 반환하면 해당 piece가 범례에서 제거됩니다.
빈 문자열을 반환하면 라벨은 제거되지만 mark는 계속 표시됩니다.
labelFormatter = ({ index, length, min, max, formattedMin, formattedMax }) =>
string | null;
markType prop으로 mark 타입을 바꿀 수 있습니다.
컬러 값은 시리즈가 아니라 축을 기반으로 하므로, markType을 범례에 직접 설정해야 합니다.
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
import { LineChart } from '@mui/x-charts/LineChart';
import {
piecewiseColorDefaultLabelFormatter,
PiecewiseColorLegend,
} from '@mui/x-charts/ChartsLegend';
import { ChartsReferenceLine } from '@mui/x-charts/ChartsReferenceLine';
import { dataset } from './tempAnomaly';
export default function PiecewiseInteractiveDemo() {
return (
<ChartsUsageDemo
componentName="Legend"
data={
{
direction: {
knob: 'select',
defaultValue: 'horizontal',
options: ['horizontal', 'vertical'],
},
labelPosition: {
knob: 'select',
defaultValue: 'extremes',
options: ['start', 'end', 'extremes', 'inline-start', 'inline-end'],
},
markType: {
knob: 'select',
defaultValue: 'square',
options: ['square', 'circle', 'line'],
},
onlyShowExtremes: {
knob: 'switch',
defaultValue: false,
},
padding: {
knob: 'number',
defaultValue: 0,
},
} as const
}
renderDemo={(props) => (
<LineChart
dataset={dataset}
series={[
{
label: 'Global temperature anomaly relative to 1961-1990',
dataKey: 'anomaly',
valueFormatter: (value) => `${value?.toFixed(2)}°`,
},
]}
xAxis={[
{
scaleType: 'time',
dataKey: 'year',
disableLine: true,
valueFormatter: (value) => value.getFullYear().toString(),
colorMap: {
type: 'piecewise',
thresholds: [new Date(1961, 0, 1), new Date(1990, 0, 1)],
colors: ['blue', 'gray', 'red'],
},
},
]}
yAxis={[
{
disableLine: true,
disableTicks: true,
valueFormatter: (value: number) => `${value}°`,
},
]}
grid={{ horizontal: true }}
height={300}
slots={{
legend: PiecewiseColorLegend,
}}
slotProps={{
legend: {
axisDirection: 'x',
direction: props.direction,
markType: props.markType,
labelPosition: props.labelPosition,
labelFormatter: props.onlyShowExtremes
? (params) =>
params.index === 0 || params.index === params.length
? piecewiseColorDefaultLabelFormatter(params)
: ''
: undefined,
sx: {
padding: props.padding,
},
},
}}
>
<ChartsReferenceLine y={0} />
</LineChart>
)}
getCode={({ props }) => {
return `import {
PiecewiseColorLegend,
piecewiseColorDefaultLabelFormatter,
} from '@mui/x-charts/ChartsLegend';
<LineChart
{/** ... */}
slots={{ legend: PiecewiseColorLegend }}
slotProps={{
legend: {
axisDirection: 'x',
direction: '${props.direction}',
markType: '${props.markType}',
labelPosition: '${props.labelPosition}',
sx: { padding: ${props.padding} },${props.onlyShowExtremes ? "\n labelFormatter: (params) =>\n params.index === 0 || params.index === params.length\n ? piecewiseColorDefaultLabelFormatter(params) \n : ''" : ''}
},
}}
/>
`;
}}
/>
);
}
클릭 이벤트 (Click event)
ChartsLegend 또는 PiecewiseColorLegend 컴포넌트에 onItemClick() 함수를 전달해 클릭 이벤트를 처리할 수 있습니다.
둘 다 다음 시그니처를 제공합니다.
const clickHandler = (
event, // The click event
context, // An object that identifies the clicked item
index, // The index of the clicked item
) => {};
context 객체는 범례 유형에 따라 다른 속성을 담고 있습니다.
아래 데모에서 범례 항목을 클릭해 그 내용을 확인해보세요.
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import UndoOutlinedIcon from '@mui/icons-material/UndoOutlined';
import { ChartsLegend, PiecewiseColorLegend } from '@mui/x-charts/ChartsLegend';
import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
import { ChartsDataProvider } from '@mui/x-charts/ChartsDataProvider';
const pieSeries = [
{
type: 'pie',
id: 'series-1',
data: [
{ label: 'Pie A', id: 'P1-A', value: 400 },
{ label: 'Pie B', id: 'P2-B', value: 300 },
],
},
] as const;
const barSeries = [
{
type: 'bar',
id: 'series-1',
label: 'Series 1',
data: [0, 1, 2],
},
{
type: 'bar',
id: 'series-2',
label: 'Series 2',
data: [0, 1, 2],
},
] as const;
const lineSeries = [
{
type: 'line',
id: 'series-1',
label: 'Series 1',
data: [0, 1, 2],
},
{
type: 'line',
id: 'series-2',
label: 'Series 2',
data: [0, 1, 2],
},
] as const;
export default function LegendClick() {
const [itemData, setItemData] = React.useState<any>();
return (
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={{ xs: 0, md: 4 }}
sx={{ width: '100%' }}
>
<Box
sx={{
flexGrow: 1,
display: 'flex',
flexDirection: 'column',
justifyContent: 'start',
alignItems: 'start',
}}
>
<Typography>Chart Legend</Typography>
<ChartsDataProvider series={barSeries} width={400} height={60}>
<ChartsLegend
direction="horizontal"
// @ts-ignore
onItemClick={(event, context, index) => setItemData([context, index])}
/>
</ChartsDataProvider>
<Typography>Pie Chart Legend</Typography>
<ChartsDataProvider series={pieSeries} width={400} height={60}>
<ChartsLegend
direction="horizontal"
onItemClick={(event, context, index) => setItemData([context, index])}
/>
</ChartsDataProvider>
<Typography>Piecewise Color Legend</Typography>
<ChartsDataProvider
// @ts-ignore
series={lineSeries}
width={400}
height={60}
xAxis={[
{
scaleType: 'linear',
data: [0, 1, 3],
disableLine: true,
colorMap: {
type: 'piecewise',
thresholds: [0, 2],
colors: ['blue', 'gray', 'red'],
},
},
]}
>
<PiecewiseColorLegend
direction="horizontal"
axisDirection="x"
// @ts-ignore
onItemClick={(event, context, index) => setItemData([context, index])}
/>
</ChartsDataProvider>
</Box>
<Stack direction="column" sx={{ width: { xs: '100%', md: '40%' } }}>
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<Typography>Click on the chart</Typography>
<IconButton
aria-label="reset"
size="small"
onClick={() => {
// @ts-ignore
setItemData(null);
}}
>
<UndoOutlinedIcon fontSize="small" />
</IconButton>
</Box>
<HighlightedCode
code={`// Index from item click: ${itemData ? itemData[1] : ''}
// Context from item click
${itemData ? JSON.stringify(itemData[0], null, 2) : '// The data will appear here'}
`}
language="json"
copyButtonHidden
/>
</Stack>
</Stack>
);
}