Charts - 참조 요소
차트에 시각적 마커를 추가해서 추가 컨텍스트를 제공할 수 있어요.
본문
참조 요소는 차트 위에 겹쳐서 표시되는 시각적 마커로, 주목할 만한 데이터 값에 시선을 끌어요. 임계값, 목표값, 허용 범위, 또는 관심 있는 특정 데이터 포인트 같은 컨텍스트를 제공해서 사용자가 데이터를 해석하는 데 도움을 줘요.
이 페이지에는 세 가지 유형의 참조 요소에 대한 데모가 있어요.
- 참조 선(Reference line): 축의 특정 값에 차트를 가로질러 그려지는 선.
- 참조 영역(Reference area): 축의 두 값 사이의 음영 처리된 영역.
- 참조 포인트(Reference point): 특정 좌표에 배치되는 마커.
:::info 이 데모의 헬퍼를 재사용해서 여러분만의 컴포넌트를 만드는 것을 권장해요. 놓친 동작이 있다면 이슈를 열어주세요. :::
import * as React from 'react';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import { alpha, useTheme } from '@mui/material/styles';
import { ChartsReferenceLine } from '@mui/x-charts-pro/ChartsReferenceLine';
import { ChartsDataProviderPro } from '@mui/x-charts-pro/ChartsDataProviderPro';
import { ChartsSurface } from '@mui/x-charts-pro/ChartsSurface';
import { LinePlot } from '@mui/x-charts-pro/LineChart';
import { ChartsXAxis } from '@mui/x-charts-pro/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts-pro/ChartsYAxis';
import { ChartsTooltip } from '@mui/x-charts-pro/ChartsTooltip';
import { ChartsGrid } from '@mui/x-charts-pro/ChartsGrid';
import { ChartsZoomSlider } from '@mui/x-charts-pro/ChartsZoomSlider';
import { ChartsClipPath } from '@mui/x-charts-pro/ChartsClipPath';
import { ChartsAxisHighlight } from '@mui/x-charts/ChartsAxisHighlight';
import { ChartsLegend } from '@mui/x-charts-pro/ChartsLegend';
import { usaUnemploymentAndGdp } from '../dataset/usaUnemploymentAndGdp';
import { useReferencePoint } from './ReferencePoint';
import { ReferenceArea } from './ReferenceArea';
type RecessionPeriod = {
start: Date;
end: Date;
label: string;
};
type Election = {
year: number;
label: string;
};
const recessions: RecessionPeriod[] = [
{
start: new Date('2001-03-01'),
end: new Date('2001-11-01'),
label: 'Early 2000s',
},
{
start: new Date('2007-12-01'),
end: new Date('2009-06-01'),
label: 'Great Recession',
},
{ start: new Date('2020-02-01'), end: new Date('2020-04-01'), label: 'COVID-19' },
];
const elections: Election[] = [
{ year: 2001, label: 'George\nW. Bush' },
{ year: 2009, label: 'Barack\nObama' },
{ year: 2017, label: 'Donald\nTrump' },
{ year: 2021, label: 'Joe\nBiden' },
{ year: 2025, label: 'Donald\nTrump' },
];
function AreaWithLabel(period: RecessionPeriod) {
const theme = useTheme();
const labelFill = alpha(theme.palette.text.primary, 0.7);
const xStart = useReferencePoint({ x: period.start.getTime() });
const xEnd = useReferencePoint({ x: period.end.getTime() });
return (
<React.Fragment>
<ReferenceArea
x1={period.start.getTime()}
x2={period.end.getTime()}
fill="grey"
opacity={0.2}
/>
{xStart.x !== xEnd.x && (
<text
x={xStart.x}
y={xStart.y - 5}
textAnchor="start"
dominantBaseline="auto"
fill={labelFill}
fontSize="0.8rem"
fontWeight={500}
pointerEvents="none"
>
{period.label}
</text>
)}
</React.Fragment>
);
}
function ElectionMarker(election: Election) {
return (
<ChartsReferenceLine
x={new Date(election.year, 0, 20).getTime()}
key={election.year}
label={election.label}
labelAlign="start"
lineStyle={{
strokeDasharray: '2 2',
}}
labelStyle={{
textAnchor: 'end',
dominantBaseline: 'hanging',
fontSize: 10,
rotate: '270deg',
transformOrigin: 'top right',
transformBox: 'fill-box',
}}
/>
);
}
export default function ReferenceOverview() {
const clipPathId = React.useId();
return (
<Box sx={{ width: '100%' }}>
<Typography sx={{ textAlign: 'center' }}>
US unemployment rate comparison with GDP per capita
</Typography>
<ChartsDataProviderPro
height={300}
dataset={usaUnemploymentAndGdp}
series={[
{
type: 'line',
id: 'unemployment',
dataKey: 'unemploymentRate',
label: 'Unemployment rate',
color: '#af3838',
yAxisId: 'unemployment-axis',
valueFormatter: (value) => (value == null ? '' : `${value.toFixed(1)}%`),
},
{
type: 'line',
dataKey: 'gdpPerCapita',
label: 'GDP per capita',
color: '#4caf50',
yAxisId: 'gdp-axis',
connectNulls: true,
valueFormatter: (value) =>
value == null ? '' : `${(value / 1000).toFixed(1)}k`,
},
]}
xAxis={[
{
scaleType: 'time',
dataKey: 'date',
tickNumber: 4,
valueFormatter: (date, context) => {
if (context.location !== 'tick') {
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
});
}
return date.getMonth() === 0
? date.toLocaleDateString('en-US', {
year: 'numeric',
})
: date.toLocaleDateString('en-US', {
month: 'short',
});
},
zoom: {
slider: { enabled: true },
},
},
]}
yAxis={[
{
id: 'unemployment-axis',
scaleType: 'linear',
valueFormatter: (value) => `${value}%`,
width: 55,
position: 'left',
},
{
id: 'gdp-axis',
scaleType: 'linear',
width: 50,
position: 'right',
valueFormatter: (value) => `${(value / 1000).toLocaleString()}k`,
},
]}
>
<Box sx={{ display: 'flex', justifyContent: 'center', mt: 1 }}>
<ChartsLegend />
</Box>
<ChartsSurface>
<ChartsClipPath id={clipPathId} />
{recessions.map((period) => (
<AreaWithLabel key={period.start.toString()} {...period} />
))}
<ChartsGrid horizontal />
<g clipPath={`url(#${clipPathId})`}>
<LinePlot />
<ChartsAxisHighlight x="line" />
{elections.map((election) => (
<ElectionMarker key={election.year} {...election} />
))}
</g>
<ChartsXAxis />
<ChartsYAxis axisId="unemployment-axis" label="Unemployment Rate" />
<ChartsYAxis axisId="gdp-axis" label="GDP per capita in US$" />
<ChartsZoomSlider />
</ChartsSurface>
<ChartsTooltip />
</ChartsDataProviderPro>
<Typography
variant="caption"
component="p"
sx={{ color: 'text.secondary', textAlign: 'left', pt: 1 }}
>
Source: FRED
</Typography>
</Box>
);
}
참조 선
<ChartsReferenceLine /> 컴포넌트는 주어진 값에 수평 또는 수직선을 그려요.
흔한 사용 사례로는 임계값, 평균값, 목표값 표시가 있어요.
수직선에는 x prop을, 수평선에는 y prop을 제공하세요.
:::info
차트에 축이 여러 개일 때는 axisId prop으로 참조 값이 속한 축을 지정하세요.
기본적으로는 첫 번째로 정의된 축을 대상으로 해요.
:::
import * as React from 'react';
import { LineChart, LineChartProps } from '@mui/x-charts/LineChart';
import { ChartsReferenceLine } from '@mui/x-charts/ChartsReferenceLine';
export default function ReferenceLineBasic() {
return (
<LineChart {...chartsConfig}>
<ChartsReferenceLine y={4} />
<ChartsReferenceLine x="Mar" />
</LineChart>
);
}
const chartsConfig: LineChartProps = {
height: 300,
xAxis: [
{ scaleType: 'point', data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'] },
],
series: [{ data: [2, 5, 3, 7, 1, 6, 4] }],
};
라벨
참조 선 옆에 텍스트를 표시하려면 label prop을 추가할 수 있어요.
labelAlign prop으로 위치를 정할 수 있는데, 'start', 'middle'(기본값), 'end'를 받아요.
import * as React from 'react';
import { LineChart, LineChartProps } from '@mui/x-charts/LineChart';
import { ChartsReferenceLine } from '@mui/x-charts/ChartsReferenceLine';
export default function ReferenceLineLabel() {
return (
<LineChart {...chartsConfig}>
<ChartsReferenceLine y={7} label="Max" labelAlign="end" />
<ChartsReferenceLine y={4} label="Average" labelAlign="middle" />
<ChartsReferenceLine
y={1}
label="Min"
labelAlign="start"
// Move label below the line.
spacing={{ y: -5 }}
labelStyle={{ dominantBaseline: 'hanging' }}
/>
</LineChart>
);
}
const chartsConfig: LineChartProps = {
height: 300,
xAxis: [
{ scaleType: 'point', data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'] },
],
series: [{ data: [2, 5, 3, 7, 1, 6, 4] }],
};
스타일링
ChartsReferenceLine을 두 가지 방법으로 스타일링할 수 있어요:
referenceLineClasses덕분에 CSS 클래스 사용- 선과 라벨에 전달되는
style객체인lineStyle과labelStyleprop 사용
라벨에 여러 줄이 있으면 labelStyle을 사용해야 해요.
이 속성은 텍스트 크기를 측정해서 여러 줄의 간격을 올바르게 띄우는 데 사용돼요.
import * as React from 'react';
import { styled } from '@mui/material/styles';
import { LineChart, LineChartProps } from '@mui/x-charts/LineChart';
import {
ChartsReferenceLine,
referenceLineClasses,
} from '@mui/x-charts/ChartsReferenceLine';
const StyledReferenceLine = styled(ChartsReferenceLine)(() => ({
[`& .${referenceLineClasses.line}`]: {
strokeDasharray: '10 5',
stroke: 'red',
},
}));
export default function ReferenceLineStyled() {
return (
<LineChart {...chartsConfig}>
<StyledReferenceLine
y={6}
label="Threshold"
labelAlign="start"
labelStyle={{ fill: 'red', fontSize: 12 }}
/>
<ChartsReferenceLine
x="Apr"
label="Target"
lineStyle={{ stroke: 'green', strokeWidth: 2 }}
labelStyle={{ fill: 'green', fontSize: 12 }}
labelAlign="end"
/>
</LineChart>
);
}
const chartsConfig: LineChartProps = {
height: 300,
xAxis: [
{ scaleType: 'point', data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'] },
],
series: [{ data: [2, 5, 3, 7, 1, 6, 4] }],
};
참조 영역
다음 데모는 점(x1, y1)과 (x2, y2) 사이의 참조 영역 구현을 보여줘요.
좌표는 축 값일 수도 있고, 영역을 축 도메인의 최소/최대로 확장하려면 'start'/'end'일 수도 있어요.
생략된 좌표도 전체 축 범위로 기본 설정돼요.
커스터마이즈에는 사각형의 좌표를 반환하는 관련 useReferenceArea()를 사용하세요.
예를 들어 영역에 라벨을 추가할 수 있어요.
플롯 아래에 참조 영역을 두기 위해 조합(composition)을 사용하는 점을 주목하세요.
import * as React from 'react';
import { LineHighlightPlot, LinePlot } from '@mui/x-charts/LineChart';
import { ChartsDataProvider } from '@mui/x-charts/ChartsDataProvider';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ChartsWrapper } from '@mui/x-charts/ChartsWrapper';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsLegend } from '@mui/x-charts/ChartsLegend';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsTooltip } from '@mui/x-charts/ChartsTooltip';
import { ChartsAxisHighlight } from '@mui/x-charts/ChartsAxisHighlight';
import { ChartsReferenceLine } from '@mui/x-charts/ChartsReferenceLine';
import { ReferenceArea, ReferenceAreaLabel } from './ReferenceArea';
export default function ReferenceAreaBasic() {
return (
<ChartsDataProvider<'line'> {...chartsConfig}>
<ChartsWrapper>
<ChartsLegend />
<ChartsSurface>
<ReferenceArea x1={1.6} y1={0.8} y2={1.2} fill="green" fillOpacity={0.5} />
<ReferenceArea
y1={0.8}
y2={1.2}
x2={1.6}
stroke="none"
fill="red"
fillOpacity={0.5}
/>
<ReferenceAreaLabel
y1={0.8}
y2={1.2}
x1={1.6}
dx={5}
dy={-5}
stroke="none"
fill="green"
dominantBaseline="auto"
>
Error < 10%
</ReferenceAreaLabel>
<ChartsReferenceLine
x={0}
label="command starts"
labelAlign="start"
lineStyle={{ strokeDasharray: '10 5' }}
labelStyle={{ fontSize: '1rem', fontStyle: 'italic' }}
/>
<ChartsReferenceLine
x={1.6}
label="stability"
labelAlign="start"
lineStyle={{ strokeDasharray: '10 5' }}
labelStyle={{ fontSize: '1rem', fontStyle: 'italic' }}
/>
<LinePlot />
<ChartsAxisHighlight x="line" />
<LineHighlightPlot />
<ChartsXAxis />
<ChartsYAxis />
</ChartsSurface>
<ChartsTooltip trigger="axis" />
</ChartsWrapper>
</ChartsDataProvider>
);
}
const N = 120;
const tValues = Array.from({ length: N + 1 }, (_, i) => -0.1 + (i * 3) / N);
const commandValues = tValues.map((t) => (t < 0 ? 0 : 1));
const zValues = tValues.map((t) =>
t < 0 ? 0 : 1 - 1 * Math.exp(-t) * (Math.cos(8 * t) - 0.5 * Math.sin(8 * t)),
);
const IntlNumber = Intl.NumberFormat('en-US', {
notation: 'compact',
maximumFractionDigits: 2,
});
const valueFormatter = (value: number | null) =>
value === null ? '' : IntlNumber.format(value);
const chartsConfig = {
height: 300,
xAxis: [{ scaleType: 'linear', data: tValues, valueFormatter }],
series: [
{
type: 'line',
data: commandValues,
label: 'command',
curve: 'stepAfter',
valueFormatter,
},
{
type: 'line',
data: zValues,
showMark: false,
label: 'response',
valueFormatter,
},
],
} as const;
참조 포인트
이전 섹션과 같은 로직으로 차트에서 특정 점을 강조할 수 있어요.
import * as React from 'react';
import { LineChart, LineChartProps } from '@mui/x-charts/LineChart';
import { useXScale, useYScale } from '@mui/x-charts/hooks';
import type { ScaleLinear, ScalePoint } from '@mui/x-charts-vendor/d3-scale';
type UseReferencePointParams = {
x: string | number;
y: number;
};
type UseReferencePointResult = {
cx: number;
cy: number;
};
type ReferencePointProps = UseReferencePointParams &
Omit<React.SVGProps<SVGCircleElement>, 'cx' | 'cy'>;
function useReferencePoint(
params: UseReferencePointParams,
): UseReferencePointResult {
const xScale = useXScale() as ScaleLinear<any, any> | ScalePoint<any>;
const yScale = useYScale() as ScaleLinear<any, any>;
return {
cx: xScale(params.x as any) as number,
cy: yScale(params.y as any) as number,
};
}
function ReferencePoint(props: ReferencePointProps) {
const { x, y, ...other } = props;
const coordinates = useReferencePoint({ x, y });
return <circle {...coordinates} {...other} />;
}
export default function ReferencePointBasic() {
return (
<LineChart {...chartsConfig}>
<ReferencePoint x="Apr" y={7} r={6} fill="red" />
<ReferencePoint
x="Jun"
y={6}
r={8}
fill="none"
stroke="green"
strokeWidth={2}
/>
</LineChart>
);
}
const chartsConfig: LineChartProps = {
height: 300,
xAxis: [
{ scaleType: 'point', data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'] },
],
series: [{ data: [2, 5, 3, 7, 1, 6, 4] }],
};