스케일 훅
스케일 훅 (Scale hooks)
커스텀 차트 컴포넌트에서 D3 스케일 함수로 데이터 값을 픽셀 좌표로 변환할 수 있어요.
본문
스케일 훅은 차트 안에서 데이터 값을 픽셀 좌표로 변환하는 D3 스케일 함수를 노출해요. 축 ID를 전달하면 해당 축의 스케일을 얻을 수 있고, 전달하지 않으면 기본 축의 스케일을 반환합니다.
카테시안 차트 (Cartesian charts)
useXScale()과 useYScale()을 사용해 x축과 y축의 스케일 함수를 얻을 수 있어요.
import { useXScale, useYScale } from '@mui/x-charts/hooks';
function CustomComponent() {
const xScale = useXScale(); // Default x-axis
const xScaleById = useXScale('customAxisId'); // Specific x-axis
const yScale = useYScale(); // Default y-axis
const yScaleById = useYScale('leftAxis'); // Specific y-axis
// Convert data value to pixel coordinate
const xCoord = xScale(dataValue);
const yCoord = yScale(dataValue);
}
극좌표 차트 (Polar charts)
useRotationScale()과 useRadiusScale()을 사용해 극좌표 차트의 회전 및 반지름 스케일 함수를 얻을 수 있어요.
import { useRotationScale, useRadiusScale } from '@mui/x-charts/hooks';
function CustomComponent() {
const rotationScale = useRotationScale();
const rotationScaleById = useRotationScale('rotationAxisId');
const radiusScale = useRadiusScale();
const radiusScaleById = useRadiusScale('radiusAxisId');
}
유틸리티 함수 (Utility function)
값을 위치로 변환 (Convert values to positions)
getValueToPositionMapper()는 값을 위치로 변환하는 매퍼 함수를 반환하며, band 스케일에 대한 특별한 처리가 포함되어 있어요.
import { getValueToPositionMapper } from '@mui/x-charts/hooks';
function CustomComponent() {
const xScale = useXScale();
const xMapper = getValueToPositionMapper(xScale);
// For band scales, this centers the position within the band
const position = xMapper(value);
}
사용 예시 (Usage example)
아래 예시는 스케일 함수를 사용해 커스텀 요소를 배치하는 방법을 보여줘요.
import {
useXScale,
useYScale,
getValueToPositionMapper,
useLineSeries,
useXAxis,
} from '@mui/x-charts/hooks';
import { LineChart } from '@mui/x-charts/LineChart';
const data = [
{ x: 1, y: 2 },
{ x: 2, y: 5 },
{ x: 3, y: 3 },
{ x: 4, y: 8 },
{ x: 5, y: 1 },
];
function CustomDataPoints() {
const xScale = useXScale();
const yScale = useYScale();
const series = useLineSeries();
const xAxis = useXAxis();
// Use the value-to-position mapper to handle different scale types
const xMapper = getValueToPositionMapper(xScale);
const yMapper = getValueToPositionMapper(yScale);
return (
<g>
{series.map((s) =>
s.data.map((point, index) => {
const x = xMapper(xAxis.data?.[index]);
const y = yMapper(point);
return (
<g key={index}>
{/* Custom data point */}
<circle
cx={x}
cy={y}
r={6}
fill="red"
stroke="white"
strokeWidth={2}
/>
{/* Value label */}
<text
x={x}
y={y - 10}
textAnchor="middle"
fontSize="10"
fill="red"
fontWeight="bold"
>
({index + 1}, {point})
</text>
</g>
);
}),
)}
</g>
);
}
export default function UseScale() {
return (
<LineChart
height={300}
dataset={data}
xAxis={[
{
dataKey: 'x',
label: 'X Values',
},
]}
yAxis={[
{
dataKey: 'y',
label: 'Y Values',
},
]}
series={[
{
dataKey: 'y',
label: 'Sample Data',
color: '#8884d8',
},
]}
>
<CustomDataPoints />
</LineChart>
);
}
주의사항 (Caveats)
이 훅들은 차트 컨텍스트 안에서만 사용할 수 있어요. 사용 요건은 hooks overview를 참고하세요.