Charts - 하이라이팅
Charts - 하이라이팅 (Highlighting)
데이터 포인트와 시리즈를 강조해 빠른 시각적 피드백을 제공해요. 특정 데이터 포인트나 시리즈를 강조하거나, 차트의 나머지를 페이드아웃할 수 있고, 프로그래밍 방식으로 제어하거나 여러 차트에 걸쳐 동기화할 수 있어요.
본문
축 하이라이팅
마우스 위치에 기반해 데이터를 강조해요.
기본적으로 하이라이트는 선으로 표시되지만, x축이 scaleType: 'band'를 사용한다면 세로 밴드로도 표시할 수 있어요.
이 동작을 커스터마이징하려면 axisHighlight prop을 사용하세요:
axisHighlight={{
x: 'line', // Or 'none', or 'band'
y: 'line', // Or 'none', or 'band'
}}
import * as React from 'react';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import Stack from '@mui/material/Stack';
import { BarChart } from '@mui/x-charts/BarChart';
import { legendClasses } from '@mui/x-charts/ChartsLegend';
const barChartsParams = {
xAxis: [{ data: ['page A', 'page B', 'page C', 'page D', 'page E'] }],
series: [
{ data: [2, 5, 3, 4, 1], stack: '1', label: 'Series x' },
{ data: [10, 3, 1, 2, 10], stack: '1', label: 'Series y' },
{ data: [10, 3, 1, 2, 10], stack: '1', label: 'Series z' },
],
margin: { right: 10 },
sx: {
[`& .${legendClasses.root}`]: {
display: 'none',
},
},
height: 300,
};
export default function BandHighlight() {
const [xHighlight, setXHightlight] = React.useState<'band' | 'none' | 'line'>(
'band',
);
const [yHighlight, setYHightlight] = React.useState<'none' | 'line'>('none');
const handleChange =
(direction: 'x' | 'y') => (event: React.ChangeEvent<HTMLInputElement>) => {
if (direction === 'x') {
setXHightlight(
(event.target as HTMLInputElement).value as 'band' | 'none' | 'line',
);
}
if (direction === 'y') {
setYHightlight((event.target as HTMLInputElement).value as 'none' | 'line');
}
};
return (
<Stack direction={{ xs: 'column', md: 'row' }} sx={{ width: '100%', m: 2 }}>
<div style={{ flexGrow: 1 }}>
<BarChart
{...barChartsParams}
axisHighlight={{ x: xHighlight, y: yHighlight }}
/>
</div>
<Stack
direction={{ xs: 'row', md: 'column' }}
spacing={2}
sx={{ justifyContent: { xs: 'space-around', md: 'flex-start' }, m: 2 }}
>
<FormControl>
<FormLabel id="x-highlight-label">x highlight</FormLabel>
<RadioGroup
aria-labelledby="x-highlight-label"
value={xHighlight}
onChange={handleChange('x')}
>
<FormControlLabel value="none" control={<Radio />} label="None" />
<FormControlLabel value="line" control={<Radio />} label="Line" />
<FormControlLabel value="band" control={<Radio />} label="Band" />
</RadioGroup>
</FormControl>
<FormControl>
<FormLabel id="y-highlight-label">y highlight</FormLabel>
<RadioGroup
aria-labelledby="y-highlight-label"
value={yHighlight}
onChange={handleChange('y')}
>
<FormControlLabel value="none" control={<Radio />} label="None" />
<FormControlLabel value="line" control={<Radio />} label="Line" />
</RadioGroup>
</FormControl>
</Stack>
</Stack>
);
}
축 값 하이라이트
ChartsAxisHighlightValue를 사용해 축 값을 강조할 수 있어요.
기본적으로 하이라이트된 축을 따라가요.
하지만 value prop을 제공해 특정 값에 대해 렌더링할 수도 있어요.
이 컴포넌트는 다음 prop들을 받아요:
axisDirection:'x' | 'y', 하이라이트된 축의 방향.axisId: 하이라이트된 축의 id. 기본적으로 첫 번째 축.labelPosition:'start' | 'end' | 'both' | 'none', 라벨의 위치.
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import { ChartsReferenceLine } from '@mui/x-charts/ChartsReferenceLine';
import { ChartsAxisHighlightValue } from '@mui/x-charts/ChartsAxisHighlightValue';
import data from '../dataset/random/scatterParallel.json';
function valueFormatter(value: number | Date | string) {
if (typeof value === 'number') {
return Math.round(value).toString();
}
if (value instanceof Date) {
return value.toLocaleDateString();
}
return value;
}
export default function AxisValueHighlight() {
return (
<div style={{ width: '100%', height: 300, minHeight: 0, margin: 'auto' }}>
<ScatterChart
series={[
{
label: 'Series A',
data: data.map((v) => ({ x: v.x1, y: v.y1, id: v.id })),
},
{
label: 'Series B',
data: data.map((v) => ({ x: v.x2, y: v.y2, id: v.id })),
},
]}
slotProps={{ tooltip: { trigger: 'none' } }}
axisHighlight={{ x: 'line', y: 'line' }}
>
<ChartsReferenceLine
y={200}
lineStyle={{ stroke: 'red', strokeWidth: 1, strokeDasharray: '4 2' }}
/>
<ChartsReferenceLine y={0} lineStyle={{ stroke: 'green', strokeWidth: 1 }} />
<ChartsReferenceLine
y={500}
lineStyle={{ stroke: 'green', strokeWidth: 1 }}
/>
<ChartsAxisHighlightValue
axisDirection="y"
labelPosition="end"
value={200}
valueFormatter={valueFormatter}
sx={{ borderRadius: '0 8px 8px 0', bgcolor: 'rgba(255,0,0,0.2)' }}
/>
<ChartsAxisHighlightValue
axisDirection="y"
labelPosition="end"
value={500}
valueFormatter={valueFormatter}
sx={{ borderRadius: '0 8px 8px 0', bgcolor: 'rgba(0,255,0,0.2)' }}
/>
<ChartsAxisHighlightValue
axisDirection="y"
labelPosition="end"
value={0}
valueFormatter={valueFormatter}
sx={{ borderRadius: '0 8px 8px 0', bgcolor: 'rgba(0,255,0,0.2)' }}
/>
<ChartsAxisHighlightValue
axisDirection="x"
labelPosition="both"
valueFormatter={valueFormatter}
/>
<ChartsAxisHighlightValue
axisDirection="y"
labelPosition="both"
valueFormatter={valueFormatter}
/>
</ScatterChart>
</div>
);
}
하이라이트된 축 값 커스터마이징
이 컴포넌트는 두 개의 CSS 변수를 정의해요:
--clamped-offset: 축을 넘치지 않게 클램프된 아이템 중앙 맞춤(50%) 오프셋.--space: 드로잉 영역과 차트 컨테이너 사이의 사용 가능한 크기.
다음 데모는 다음을 보여줘요:
- 녹색 라벨: 기본적으로 라벨은 축 범위로 제한돼요(오른쪽 라벨). 왼쪽 것은
translate속성을 설정해 라벨이 넘치도록 하는 방법을 보여줘요. - 빨간 라벨:
--space를 사용해 라벨 크기를 제한하는 방법을 보여줘요.
import { useTheme } from '@mui/material/styles';
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import { ChartsReferenceLine } from '@mui/x-charts/ChartsReferenceLine';
import { ChartsAxisHighlightValue } from '@mui/x-charts/ChartsAxisHighlightValue';
import data from '../dataset/random/scatterParallel.json';
export default function AxisValueHighlightCustomization() {
const theme = useTheme();
const green = theme.palette.mode === 'dark' ? '#044412' : '#e5fedb';
const red = theme.palette.mode === 'dark' ? '#610909' : '#fad7d2';
const grey = theme.palette.mode === 'dark' ? '#333333' : '#cccccc';
return (
<div style={{ width: 400, height: 300, margin: 'auto' }}>
<ScatterChart
height={200}
series={[
{
label: 'Series A',
data: data.map((v) => ({ x: v.x1, y: v.y1, id: v.id })),
},
{
label: 'Series B',
data: data.map((v) => ({ x: v.x2, y: v.y2, id: v.id })),
},
]}
slotProps={{ tooltip: { trigger: 'none' } }}
axisHighlight={{ x: 'line', y: 'line' }}
>
<ChartsReferenceLine
y={580}
lineStyle={{ stroke: 'green', strokeWidth: 1 }}
/>
<ChartsAxisHighlightValue
axisDirection="y"
labelPosition="start"
value={580}
valueFormatter={() => 'without overflow'}
sx={{
translate: '-100% -50%',
borderRadius: '8px 0 0 8px',
bgcolor: green,
}}
/>
<ChartsAxisHighlightValue
axisDirection="y"
labelPosition="end"
value={580}
valueFormatter={() => 'with overflow'}
sx={{ borderRadius: '0 8px 8px 0', bgcolor: green }}
/>
<ChartsAxisHighlightValue
axisDirection="x"
labelPosition="end"
value={200}
valueFormatter={() => 'this uses the max height'}
sx={{
p: 0.5,
bgcolor: red,
maxWidth: 70,
maxHeight: 'var(--space)',
overflow: 'auto',
pointerEvents: 'auto',
}}
/>
<ChartsAxisHighlightValue
axisDirection="x"
labelPosition="end"
value={350}
valueFormatter={() => 'this one does not'}
sx={{
p: 0.5,
bgcolor: red,
maxWidth: 50,
}}
/>
<ChartsAxisHighlightValue
axisDirection="x"
labelPosition="start"
valueFormatter={(v) => `${Math.round(v as number)}`}
sx={{
translate: '-50% -100%',
borderRadius: '8px 8px 0 0',
bgcolor: grey,
}}
/>
</ScatterChart>
</div>
);
}
시리즈 하이라이팅
요소 위에 마우스를 올리면 기본적으로 툴팁이 표시돼요. 툴팁과 독립적으로 하이라이팅과 페이딩을 구성할 수도 있어요.
이 상호작용은 series의 highlightScope 속성으로 제어되며, 두 가지 옵션을 포함해요:
highlight: 어떤 항목을 강조할지 나타내요. 값은 다음과 같아요:'none': 아무것도 하지 않음 (기본값)'item': 항목 자체만 강조'series': 시리즈의 모든 항목 강조
fade: 어떤 항목을 페이드시킬지 나타내요(이미 강조되지 않은 경우). 값은 다음과 같아요:'none': 아무것도 하지 않음 (기본값)'series': 시리즈의 모든 항목 페이드'global': 차트의 모든 항목 페이드
:::info Line 차트에서는 slots를 사용해 상호작용 영역을 늘릴 수 있어요. 이에 대한 예시는 Line demos—Larger interaction area를 참고하세요. :::
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import FormControlLabel from '@mui/material/FormControlLabel';
import Switch from '@mui/material/Switch';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import { BarChart } from '@mui/x-charts/BarChart';
import { AnimatedLineProps, LineChart } from '@mui/x-charts/LineChart';
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import { PieChart } from '@mui/x-charts/PieChart';
import scatterDataset from '../dataset/random/scatterParallel.json';
type HighlightOptions = 'none' | 'item' | 'series';
type FadeOptions = 'none' | 'series' | 'global';
const barChartsParams = {
series: [
{ data: [3, 4, 1, 6, 5], label: 'A' },
{ data: [4, 3, 1, 5, 8], label: 'B' },
{ data: [4, 2, 5, 4, 1], label: 'C' },
],
height: 400,
};
const lineChartsParams = {
series: [
{ data: [3, 4, 1, 6, 5], label: 'A', area: false, stack: 'total' },
{ data: [4, 3, 1, 5, 8], label: 'B', area: false, stack: 'total' },
{ data: [4, 2, 5, 4, 1], label: 'C', area: false, stack: 'total' },
],
xAxis: [{ data: [1, 2, 3, 4, 5], type: 'linear' }],
height: 400,
};
const scatterChartsParams = {
dataset: scatterDataset,
series: [
{ datasetKeys: { id: 'id', x: 'x1', y: 'y1' }, label: 'A' },
{ datasetKeys: { id: 'id', x: 'x2', y: 'y2' }, label: 'B' },
],
height: 400,
};
const pieChartsParams = {
series: [
{
data: [{ value: 5 }, { value: 10 }, { value: 15 }],
label: 'Series 1',
outerRadius: 80,
highlight: { additionalRadius: 10 },
},
{
data: [{ value: 5 }, { value: 10 }, { value: 15 }],
label: 'Series 1',
innerRadius: 90,
highlight: { additionalRadius: 10 },
},
],
height: 400,
margin: { top: 50, bottom: 50 },
};
function CustomLine(props: AnimatedLineProps) {
const { d, ownerState, skipAnimation, className, ...other } = props;
return (
<React.Fragment>
<path
d={d}
stroke={
ownerState.gradientId ? `url(#${ownerState.gradientId})` : ownerState.color
}
strokeWidth={ownerState.isHighlighted ? 4 : 2}
strokeLinejoin="round"
fill="none"
filter={ownerState.isHighlighted ? 'brightness(120%)' : undefined}
opacity={ownerState.isFaded ? 0.3 : 1}
className={className}
/>
<path d={d} stroke="transparent" strokeWidth={25} fill="none" {...other} />
</React.Fragment>
);
}
export default function ElementHighlights() {
const [chartType, setChartType] = React.useState('bar');
const [withArea, setWithArea] = React.useState(false);
const [highlight, setHighlight] = React.useState<HighlightOptions>('item');
const [fade, setFade] = React.useState<FadeOptions>('global');
const handleChartType = (event: any, newChartType: string) => {
if (newChartType !== null) {
setChartType(newChartType);
}
};
return (
<Stack
direction={{ xs: 'column', xl: 'row' }}
spacing={1}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1 }}>
<ToggleButtonGroup
value={chartType}
exclusive
onChange={handleChartType}
aria-label="chart type"
fullWidth
>
{['bar', 'line', 'scatter', 'pie'].map((type) => (
<ToggleButton key={type} value={type}>
{type}
</ToggleButton>
))}
</ToggleButtonGroup>
{chartType === 'bar' && (
<BarChart
{...barChartsParams}
series={barChartsParams.series.map((series) => ({
...series,
highlightScope: {
highlight,
fade,
},
}))}
/>
)}
{chartType === 'line' && (
<LineChart
{...lineChartsParams}
series={lineChartsParams.series.map((series) => ({
...series,
area: withArea,
highlightScope: {
highlight,
fade,
},
}))}
slots={withArea ? {} : { line: CustomLine }}
/>
)}
{chartType === 'scatter' && (
<ScatterChart
{...scatterChartsParams}
series={scatterChartsParams.series.map((series) => ({
...series,
highlightScope: {
highlight,
fade,
},
}))}
/>
)}
{chartType === 'pie' && (
<PieChart
{...pieChartsParams}
series={pieChartsParams.series.map((series) => ({
...series,
highlightScope: {
highlight,
fade,
},
}))}
/>
)}
</Box>
<Stack
direction={{ xs: 'row', xl: 'column' }}
spacing={3}
useFlexGap
sx={{ justifyContent: 'center', flexWrap: 'wrap' }}
>
<TextField
select
label="highlight"
value={highlight}
onChange={(event) => setHighlight(event.target.value as HighlightOptions)}
sx={{ minWidth: 150 }}
>
<MenuItem value={'none'}>none</MenuItem>
<MenuItem value={'item'}>item</MenuItem>
<MenuItem value={'series'}>series</MenuItem>
</TextField>
<TextField
select
label="fade"
value={fade}
onChange={(event) => setFade(event.target.value as FadeOptions)}
sx={{ minWidth: 150 }}
>
<MenuItem value={'none'}>none</MenuItem>
<MenuItem value={'series'}>series</MenuItem>
<MenuItem value={'global'}>global</MenuItem>
</TextField>
{chartType === 'line' && (
<FormControlLabel
control={
<Switch
checked={withArea}
onChange={(event) => setWithArea(event.target.checked)}
/>
}
label="Fill line area"
/>
)}
</Stack>
</Stack>
);
}
제어 항목 하이라이트
highlightedItem과 onHighlightChange prop을 사용해 하이라이트된 항목을 제어할 수 있어요.
입력에 기반해 highlightedItem 값을 설정하고, 사용자가 항목 위에 마우스를 올릴 때 동기화할 수 있어요.
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import { HighlightItemIdentifier } from '@mui/x-charts/models';
import { BarChart, BarChartProps } from '@mui/x-charts/BarChart';
import FormControl from '@mui/material/FormControl';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormLabel from '@mui/material/FormLabel';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
export default function ControlledHighlight() {
const [highlightedItem, setHighLightedItem] =
React.useState<HighlightItemIdentifier<'bar'> | null>({
seriesId: 'A',
dataIndex: 0,
});
const [highlight, setHighlight] = React.useState<'none' | 'item' | 'series'>(
'item',
);
const [fade, setFade] = React.useState<'none' | 'series' | 'global'>('global');
const handleHighLightedSeries = (event: any, newHighLightedSeries: string) => {
if (newHighLightedSeries !== null) {
setHighLightedItem((prev) => ({
dataIndex: 0,
...prev,
seriesId: newHighLightedSeries,
}));
}
};
const handleHighLightedItem = (event: any) => {
setHighLightedItem((prev) => ({
seriesId: 'A',
...prev,
dataIndex: Number(event.target.value),
}));
};
return (
<Stack
direction={{ xs: 'column', xl: 'row' }}
spacing={1}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1 }}>
<Stack spacing={2} sx={{ alignItems: 'center' }}>
<ToggleButtonGroup
value={highlightedItem?.seriesId ?? null}
exclusive
onChange={handleHighLightedSeries}
aria-label="highlighted series"
fullWidth
>
{['A', 'B'].map((type) => (
<ToggleButton key={type} value={type}>
Series {type}
</ToggleButton>
))}
</ToggleButtonGroup>
<FormControl>
<FormLabel id="item-id-radio-group">Item ID</FormLabel>
<RadioGroup
aria-labelledby="item-id-radio-group"
name="radio-buttons-group"
value={highlightedItem?.dataIndex ?? null}
onChange={handleHighLightedItem}
row
>
<FormControlLabel value="0" control={<Radio />} label="0" />
<FormControlLabel value="1" control={<Radio />} label="1" />
<FormControlLabel value="2" control={<Radio />} label="2" />
<FormControlLabel value="3" control={<Radio />} label="3" />
<FormControlLabel value="4" control={<Radio />} label="4" />
</RadioGroup>
</FormControl>
</Stack>
<BarChart
{...barChartsProps}
series={barChartsProps.series.map((series) => ({
...series,
highlightScope: {
highlight,
fade,
},
}))}
highlightedItem={highlightedItem}
onHighlightChange={setHighLightedItem}
/>
</Box>
<Stack
direction={{ xs: 'row', xl: 'column' }}
spacing={3}
useFlexGap
sx={{ justifyContent: 'center', flexWrap: 'wrap' }}
>
<TextField
select
label="highlighted"
value={highlight}
onChange={(event) =>
setHighlight(event.target.value as 'none' | 'item' | 'series')
}
sx={{ minWidth: 150 }}
>
<MenuItem value={'none'}>none</MenuItem>
<MenuItem value={'item'}>item</MenuItem>
<MenuItem value={'series'}>series</MenuItem>
</TextField>
<TextField
select
label="faded"
value={fade}
onChange={(event) =>
setFade(event.target.value as 'none' | 'series' | 'global')
}
sx={{ minWidth: 150 }}
>
<MenuItem value={'none'}>none</MenuItem>
<MenuItem value={'series'}>series</MenuItem>
<MenuItem value={'global'}>global</MenuItem>
</TextField>
</Stack>
</Stack>
);
}
const barChartsProps: BarChartProps = {
series: [
{ data: [3, 4, 1, 6, 5], label: 'A', id: 'A' },
{ data: [4, 3, 1, 5, 8], label: 'B', id: 'B' },
],
height: 400,
};
제어 축 하이라이트
highlightedAxis prop을 사용해 하이라이트된 축 항목을 제어해요.
그 값은 { axisId: string, dataIndex: number } 객체의 배열이에요.
배열이 비어 있으면 아무것도 하이라이트되지 않아요.
onHighlightedAxisChange 핸들러는 포인터가 두 축 값의 경계를 넘을 때마다 트리거돼요.
데이터 포인트를 하나 이상 포함하는 축마다 하나의 { axisId, dataIndex } 객체 배열을 받아요.
:::warning
onHighlightedAxisChange 핸들러는 사용자가 차트 위로 포인터를 움직일 때 높은 빈도로 트리거될 수 있어요.
성능 문제를 피하려면 매 렌더링마다 props에 전달되는 객체를 재생성하지 마세요. 대신 컴포넌트 밖에서 정의하거나 메모이즈하세요. 이는 축과 시리즈에 특히 중요하며, 업데이트되면 상당한 계산을 트리거하기 때문이에요.
// ❌ 차트는 매 렌더링마다 새 축을 받아 불필요한 계산이 발생해요.
const Component = () => <BarChart xAxis={[{ data: [1, 2, 3]}]}>
// ✅ 정적 설정은 컴포넌트 밖에서 정의하세요.
const quarterAxis = [{ data: ['Q1', 'Q2', 'Q3', 'Q4'] }];
const Component = () => <BarChart xAxis={quarterAxis}>
// ✅ 동적 설정은 메모이즈하세요.
const Component = ({ data }) => {
const axis = React.useMemo(() => [{ data }], [data]);
return <BarChart xAxis={quarterAxis}>
}
:::
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import { BarChart, BarChartProps } from '@mui/x-charts/BarChart';
import FormControl from '@mui/material/FormControl';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormLabel from '@mui/material/FormLabel';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import { AxisItemIdentifier } from '@mui/x-charts/models';
import { LineChart, LineChartProps } from '@mui/x-charts/LineChart';
export default function ControlledAxisHighlight() {
const [highlightedAxis, setHighlightedAxis] = React.useState<AxisItemIdentifier[]>(
[
{
axisId: 'x-axis',
dataIndex: 2,
},
],
);
const handleAxisHighlight = (event: any) => {
setHighlightedAxis([
{
axisId: 'x-axis',
dataIndex: Number(event.target.value),
},
]);
};
return (
<Stack spacing={2} sx={{ alignItems: 'center', width: '100%' }}>
<FormControl>
<FormLabel id="axis-index-radio-group">Highlighted index</FormLabel>
<RadioGroup
aria-labelledby="axis-index-radio-group"
name="radio-buttons-group"
value={highlightedAxis[0]?.dataIndex ?? null}
onChange={handleAxisHighlight}
row
>
<FormControlLabel value="0" control={<Radio />} label="0" />
<FormControlLabel value="1" control={<Radio />} label="1" />
<FormControlLabel value="2" control={<Radio />} label="2" />
<FormControlLabel value="3" control={<Radio />} label="3" />
<FormControlLabel value="4" control={<Radio />} label="4" />
</RadioGroup>
</FormControl>
<Box sx={{ width: '100%' }}>
<BarChart
{...barChartsProps}
highlightedAxis={highlightedAxis}
onHighlightedAxisChange={(newState) => setHighlightedAxis(newState)}
/>
<LineChart
{...lineChartsProps}
highlightedAxis={highlightedAxis}
onHighlightedAxisChange={(newState) => setHighlightedAxis(newState)}
/>
</Box>
</Stack>
);
}
const barChartsProps: BarChartProps = {
series: [
{ data: [3, 4, 1, 6, 5], label: 'series A', id: 'A' },
{ data: [4, 3, 1, 5, 8], label: 'series B', id: 'B' },
],
xAxis: [{ id: 'x-axis', scaleType: 'band', data: [0, 2, 5, 10, 20] }],
height: 300,
};
const lineChartsProps: LineChartProps = {
series: [
{ data: [3, 4, 1, 6, 5], label: 'series A', id: 'A' },
{ data: [4, 3, 1, 5, 8], label: 'series B', id: 'B' },
],
xAxis: [{ id: 'x-axis', scaleType: 'linear', data: [0, 2, 5, 10, 20] }],
height: 300,
};
하이라이트 동기화
제어 하이라이트를 사용하면 여러 차트에 걸쳐 동기화할 수 있어요.
series가 같은 ID를 갖고 데이터가 같은 순서인지 확인하세요.
import * as React from 'react';
import Stack from '@mui/material/Stack';
import { BarChart, BarChartProps } from '@mui/x-charts/BarChart';
import { PieChart, PieChartProps } from '@mui/x-charts/PieChart';
import { HighlightItemIdentifier } from '@mui/x-charts/models';
export default function SyncHighlight() {
const [highlightedItem, setHighlightedItem] =
React.useState<HighlightItemIdentifier<'pie' | 'bar'> | null>(null);
return (
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={1}
sx={{ width: '100%' }}
>
<BarChart
{...barChartsProps}
highlightedItem={highlightedItem as HighlightItemIdentifier<'bar'> | null}
onHighlightChange={(item) =>
setHighlightedItem(
item ? { seriesId: item.seriesId, dataIndex: item.dataIndex } : null,
)
}
/>
<PieChart
{...pieChartProps}
highlightedItem={highlightedItem as HighlightItemIdentifier<'pie'> | null}
onHighlightChange={(item) =>
setHighlightedItem(
item ? { seriesId: item.seriesId, dataIndex: item.dataIndex } : null,
)
}
/>
</Stack>
);
}
const barChartsProps: BarChartProps = {
series: [
{
data: [3, 4, 1, 6, 5],
id: 'sync',
highlightScope: { highlight: 'item', fade: 'global' },
},
],
xAxis: [{ data: ['A', 'B', 'C', 'D', 'E'] }],
height: 200,
hideLegend: true,
};
const pieChartProps: PieChartProps = {
series: [
{
id: 'sync',
data: [
{ value: 3, label: 'A', id: 'A' },
{ value: 4, label: 'B', id: 'B' },
{ value: 1, label: 'C', id: 'C' },
{ value: 6, label: 'D', id: 'D' },
{ value: 5, label: 'E', id: 'E' },
],
highlightScope: { highlight: 'item', fade: 'global' },
},
],
height: 150,
hideLegend: true,
};