`usePolarGeometry()`
usePolarGeometry()
커스텀 SVG 요소와 변환을 배치하기 위해 극좌표 차트의 지오메트리에 접근할 수 있어요.
본문
usePolarGeometry()는 극좌표 차트의 지오메트리를 반환해서, 차트의 중심 좌표, 스케일, 좌표 변환기에 접근할 수 있게 해줘요.
사용법
이 훅은 차트의 중심 좌표(cx, cy), angleScale과 radiusScale, 그리고 극좌표와 데카르트 좌표 사이의 point/pointInverse 변환기를 반환해요.
angleScale은 회전 축(중심을 도는 각도 축)의 스케일이고, radiusScale은 반지름 축(중심으로부터의 방사형 거리)의 스케일이에요.
차트 스케일이 준비되지 않았을 때는 null을 반환해요.
import { usePolarGeometry } from '@mui/x-charts/hooks';
function PolarGeometryOverlay() {
const geometry = usePolarGeometry();
if (!geometry) {
return null; // Chart scales not ready or axes don't meet requirements
}
const { cx, cy, point } = geometry;
// Example: Position a custom marker at a specific radius and angle
const [x, y] = point(100, Math.PI / 4); // radius: 100px, angle: 45 degrees
// point() returns an offset from the center, so add cx/cy
return <circle cx={cx + x} cy={cy + y} r={5} fill="red" />;
}
기본적으로 angleScale과 radiusScale은 지원되는 모든 스케일 타입의 유니온으로 타이핑돼요.
제네릭 인자로 회전 축과 반지름 축의 스케일 이름을 전달하면 정확하게 타이핑된 스케일을 얻을 수 있어요. 예를 들어 band 회전 축에서 bandwidth()를 호출하고 싶다면:
const geometry = usePolarGeometry<'band', 'linear'>();
if (geometry) {
// angleScale is ScaleBand, radiusScale is ScaleLinear
const band = geometry.angleScale.bandwidth();
const radius = geometry.radiusScale(100);
}
import * as React from 'react';
import { usePolarGeometry } from '@mui/x-charts/hooks';
import { RadialBarChart, RadialBarPlot } from '@mui/x-charts-premium/RadialBarChart';
import { ChartsRadiusAxis } from '@mui/x-charts/ChartsRadiusAxis';
import { ChartsRotationAxis } from '@mui/x-charts/ChartsRotationAxis';
const trustData = [
{ country: 'Denmark', trust: 65 },
{ country: 'Finland', trust: 62 },
{ country: 'Netherlands', trust: 60 },
{ country: 'Sweden', trust: 58 },
{ country: 'Norway', trust: 61 },
];
/**
* Custom overlay using usePolarGeometry hook
*/
function PolarGeometryOverlay() {
const geometry = usePolarGeometry<'band', 'linear'>();
if (!geometry) {
return null;
}
// Draw a reference ring at value 50
const radius = geometry.radiusScale(50);
const [x, y] = geometry.point(radius, Math.PI / 4);
return (
<React.Fragment>
{/* Reference ring */}
<circle
cx={geometry.cx}
cy={geometry.cy}
r={radius}
fill="none"
stroke="#999"
strokeDasharray="4"
opacity={0.5}
strokeWidth={1}
/>
{/* Custom marker at a specific angle and radius */}
<circle
cx={geometry.cx + x}
cy={geometry.cy + y}
r={4}
fill="red"
opacity={0.8}
/>
</React.Fragment>
);
}
/**
* Simple demo: Radial bar chart with custom geometry overlay
*/
export default function UsePolarGeometry() {
return (
<RadialBarChart
dataset={trustData}
series={[{ dataKey: 'trust' }]}
rotationAxis={[{ dataKey: 'country', scaleType: 'band' }]}
radiusAxis={[{ scaleType: 'linear' }]}
margin={{ top: 50, bottom: 50, left: 50, right: 50 }}
width={400}
height={400}
>
<ChartsRadiusAxis />
<ChartsRotationAxis />
<RadialBarPlot />
<PolarGeometryOverlay />
</RadialBarChart>
);
}
주의사항
이 훅은 차트 컨텍스트 안에서만 사용할 수 있어요. 사용 요구사항은 hooks 개요를 참고하세요.