Charts - 산점도
Charts - 산점도 (Scatter)
두 변수를 점으로 그려 관계·상관관계·이상치를 드러내는 산점도 차트를 사용해 봐요.
본문
개요 (Overview)
산점도 차트는 두 변수를 평면 위의 점으로 그려서, 한 변수가 다른 변수에 따라 어떻게 변하는지 보고 군집·추세·이상치를 발견할 수 있게 해 줘요. 각 점은 하나의 관측값이며, 두 축의 값에 따라 배치돼요. 산점도 차트는 통계 분석, 과학 데이터, 성능 지표에 자주 사용돼요.
import { ScatterChart, ScatterSeries } from '@mui/x-charts/ScatterChart';
import { ChartsTooltipContainer, useItemTooltip } from '@mui/x-charts/ChartsTooltip';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Divider from '@mui/material/Divider';
import Stack from '@mui/material/Stack';
import data from '../dataset/transistorCPUdata';
const chartSetting = {
yAxis: [{ width: 50, scaleType: 'log' as const }],
xAxis: [{ valueFormatter: (v: number | null) => (v ? v.toString() : '') }],
};
const constructors = ['Intel', 'Apple', 'AMD'];
const series = [
{
type: 'scatter',
label: 'Other',
highlightScope: { highlight: 'series', fade: 'global' },
markerSize: 3,
data: data
.filter(
(item) => !constructors.includes(item.constructor) && item.density !== null,
)
.map((item) => ({ x: item.year, y: item.density as number, id: item.id })),
},
...constructors.map((constructor): ScatterSeries => ({
label: constructor,
highlightScope: { highlight: 'series', fade: 'global' },
markerSize: 3,
data: data
.filter((item) => item.constructor === constructor && item.density !== null)
.map((item) => ({ x: item.year, y: item.density as number, id: item.id })),
})),
] satisfies ScatterSeries[];
const numberFormatter = new Intl.NumberFormat('en-US').format;
const TooltipPaper = styled('div', {
name: 'Tooltip',
slot: 'Paper',
})(({ theme }) => {
return {
padding: theme.spacing(1),
backgroundColor: (theme.vars || theme).palette.background.paper,
color: (theme.vars || theme).palette.text.primary,
borderRadius: (theme.vars || theme).shape?.borderRadius,
border: `solid ${(theme.vars || theme).palette.divider} 1px`,
};
});
function CustomTooltip() {
const item = useItemTooltip<'scatter'>();
return (
<ChartsTooltipContainer trigger="item">
<TooltipPaper>
<Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
<Box
sx={{
width: 20,
height: 20,
backgroundColor: item?.color,
borderRadius: 1,
mr: 2,
}}
/>
<Typography>{item?.label}</Typography>
</Box>
<Divider sx={{ my: 1 }} />
<Box
sx={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
}}
>
<Typography sx={{ mr: 3 }}>{item?.value.x}</Typography>
<Typography>
{item?.value.y == null
? 'NaN'
: `${numberFormatter(item?.value.y)} transistor/mm²`}
</Typography>
</Box>
</TooltipPaper>
</ChartsTooltipContainer>
);
}
export default function ScatterOverview() {
return (
<Stack sx={{ width: '100%' }}>
<Typography align="center">Processor density (in transistor/mm²)</Typography>
<ScatterChart
height={300}
series={series}
grid={{ horizontal: true, vertical: true }}
hitAreaRadius={20}
slots={{ tooltip: CustomTooltip }}
{...chartSetting}
/>
</Stack>
);
}
기초 (Basics)
산점도 시리즈는 보통 data 속성으로 점들을 정의해요. 각각의 점은 x와 y(위치)를 가진 객체 배열이에요.
좌표를 시리즈에 직접 두는 대신 dataset prop과 datasetKeys를 함께 사용할 수도 있어요—데이터셋 사용하기를 참고하세요.
각 점에 선택적 id를 추가하면 데이터가 바뀌어도 안정적인 정체성을 유지해요.
시리즈에 애니메이션을 적용한다면 id를 통해 추가되거나 제거된 점이 예측 가능하게 전환돼요. id가 없으면 배열에서 각 점의 인덱스에 따라 업데이트가 이뤄져서 기존 마커가 이상하게 재사용될 수 있어요.
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import data from '../dataset/random/scatterParallel.json';
export default function BasicScatter() {
return (
<ScatterChart
height={300}
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 })),
},
]}
/>
);
}
데이터셋 사용하기
데이터가 객체 배열로 저장되어 있다면 dataset 헬퍼 prop을 사용할 수 있어요.
이는 dataset={[{a: 1, b: 32, c: 873}, {a: 2, b: 41, c: 182}, ...]} 같은 객체 배열을 받아요.
산점도 시리즈는 다른 차트와 다른 패턴을 사용해요. 필수 x와 y 키가 있는 객체로 datasetKeys 속성을 사용하세요.
선택적 id, colorValue, sizeValue 키도 포함할 수 있어요.
자세한 내용은 Dataset 페이지를 참고하세요.
import { ScatterChart } from '@mui/x-charts/ScatterChart';
export default function ScatterDataset() {
return (
<ScatterChart
dataset={dataset}
series={[
{ datasetKeys: { x: 'x1', y: 'y1' }, label: 'Series A' },
{ datasetKeys: { x: 'x2', y: 'y2' }, label: 'Series B' },
]}
{...chartSetting}
/>
);
}
const dataset = [
{ x1: 373, y1: 434, x2: 304, y2: 349 },
{ x1: 173, y1: 437, x2: 208, y2: 347 },
{ x1: 68, y1: 292, x2: 151, y2: 280 },
{ x1: 121, y1: 116, x2: 185, y2: 176 },
{ x1: 322, y1: 61, x2: 278, y2: 170 },
{ x1: 466, y1: 210, x2: 346, y2: 246 },
{ x1: 418, y1: 403, x2: 326, y2: 333 },
{ x1: 224, y1: 449, x2: 235, y2: 352 },
{ x1: 87, y1: 335, x2: 158, y2: 311 },
{ x1: 104, y1: 167, x2: 166, y2: 218 },
{ x1: 262, y1: 70, x2: 251, y2: 161 },
{ x1: 421, y1: 167, x2: 335, y2: 199 },
{ x1: 442, y1: 352, x2: 341, y2: 302 },
{ x1: 294, y1: 474, x2: 264, y2: 366 },
{ x1: 101, y1: 386, x2: 174, y2: 318 },
{ x1: 64, y1: 198, x2: 154, y2: 227 },
{ x1: 222, y1: 75, x2: 223, y2: 181 },
{ x1: 411, y1: 105, x2: 316, y2: 204 },
{ x1: 457, y1: 290, x2: 349, y2: 274 },
{ x1: 348, y1: 455, x2: 291, y2: 357 },
{ x1: 165, y1: 427, x2: 195, y2: 358 },
{ x1: 65, y1: 277, x2: 150, y2: 265 },
{ x1: 153, y1: 94, x2: 197, y2: 175 },
{ x1: 340, y1: 93, x2: 294, y2: 163 },
{ x1: 476, y1: 253, x2: 352, y2: 264 },
{ x1: 385, y1: 425, x2: 317, y2: 332 },
{ x1: 221, y1: 448, x2: 221, y2: 376 },
{ x1: 60, y1: 327, x2: 154, y2: 281 },
{ x1: 129, y1: 128, x2: 175, y2: 213 },
{ x1: 304, y1: 67, x2: 267, y2: 173 },
{ x1: 447, y1: 175, x2: 343, y2: 223 },
{ x1: 425, y1: 378, x2: 335, y2: 313 },
{ x1: 273, y1: 463, x2: 250, y2: 377 },
{ x1: 80, y1: 387, x2: 166, y2: 304 },
{ x1: 86, y1: 172, x2: 159, y2: 224 },
{ x1: 247, y1: 64, x2: 238, y2: 172 },
{ x1: 419, y1: 126, x2: 328, y2: 200 },
{ x1: 463, y1: 317, x2: 347, y2: 301 },
{ x1: 308, y1: 473, x2: 278, y2: 352 },
{ x1: 147, y1: 405, x2: 183, y2: 356 },
{ x1: 64, y1: 224, x2: 151, y2: 246 },
{ x1: 175, y1: 78, x2: 210, y2: 163 },
{ x1: 384, y1: 96, x2: 308, y2: 187 },
{ x1: 473, y1: 275, x2: 354, y2: 273 },
{ x1: 387, y1: 455, x2: 306, y2: 367 },
{ x1: 193, y1: 445, x2: 208, y2: 372 },
{ x1: 51, y1: 298, x2: 151, y2: 264 },
{ x1: 154, y1: 116, x2: 187, y2: 205 },
{ x1: 342, y1: 73, x2: 283, y2: 184 },
{ x1: 467, y1: 199, x2: 348, y2: 246 },
];
const chartSetting = {
yAxis: [
{
label: 'rainfall (mm)',
width: 60,
},
],
height: 300,
};
상호작용 (Interaction)
산점도 점은 작을 수 있으므로, 차트는 포인터가 점 위에 정확히 있어야 하는 것을 요구하지 않아요. 포인터가 그리기 영역 안에 있으면 가장 가까운 점이 툴팁과 하이라이트에 사용돼요.
hitAreaRadius prop에 숫자를 전달하면 선택을 위해 포인터가 점에서 얼마나 떨어져 있을 수 있는지를 제한할 수 있어요.
포인터가 어떤 점에서도 그 거리보다 멀다면 항목이 선택되지 않아요.
hitAreaRadius를 "item"과 함께 사용하면 그리기 영역에서 포인터에 가장 가까운 점을 선택하는 대신, 포인터가 마커 바로 위에 있을 때만 상호작용이 트리거돼요.
/* eslint-disable no-nested-ternary */
import * as React from 'react';
import Stack from '@mui/material/Stack';
import FormControlLabel from '@mui/material/FormControlLabel';
import Typography from '@mui/material/Typography';
import Slider from '@mui/material/Slider';
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import data from '../dataset/random/scatterParallel.json';
export default function ClosestPointInteraction() {
const [option, setOption] = React.useState<'item' | 'undefined' | 'numeric'>(
'numeric',
);
const [hitAreaRadius, setVoronoiMaxRadius] = React.useState<number>(25);
const handleMaxRadiusChange = (event: Event, newValue: number | number[]) => {
if (typeof newValue !== 'number') {
return;
}
setVoronoiMaxRadius(newValue);
};
return (
<Stack direction="column" sx={{ width: '100%' }}>
<ScatterChart
height={300}
hitAreaRadius={
option === 'undefined'
? undefined
: option === 'item'
? 'item'
: hitAreaRadius
}
dataset={data}
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 })),
},
]}
/>
<div>
<Typography gutterBottom>Maximum radius</Typography>
<RadioGroup
onChange={(event) =>
setOption(event.target.value as 'item' | 'undefined' | 'numeric')
}
>
<Stack direction="row">
<FormControlLabel
checked={option === 'item'}
control={<Radio />}
label="'item'"
labelPlacement="end"
value="item"
/>
<FormControlLabel
checked={option === 'undefined'}
control={<Radio />}
label="undefined"
labelPlacement="end"
value="undefined"
/>
<FormControlLabel
checked={option === 'numeric'}
control={<Radio />}
label="numeric radius"
labelPlacement="end"
value="numeric"
/>
</Stack>
</RadioGroup>
<Typography id="max-radius-value" gutterBottom>
Numeric radius
</Typography>
<Slider
value={hitAreaRadius}
onChange={handleMaxRadiusChange}
valueLabelDisplay="auto"
min={1}
max={100}
aria-labelledby="max-radius-value"
disabled={option !== 'numeric'}
/>
</div>
</Stack>
);
}
클릭 이벤트
산점도 차트는 특정 점을 클릭하는 onItemClick 핸들러를 제공해요.
다음 시그니처를 사용해요.
const onItemClick = (
event, // The mouse event.
params, // An object that identifies the clicked elements.
) => {};
hitAreaRadius가 "item"이면 사용자는 점을 직접 클릭해야 하고, 마우스 이벤트는 그 엘리먼트에서 오게 돼요.
그 외에는 클릭 동작이 상호작용 섹션과 일치하며, 마우스 이벤트는 SVG 컨테이너에서 오게 돼요.
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 ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import UndoOutlinedIcon from '@mui/icons-material/UndoOutlined';
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
import { ScatterItemIdentifier } from '@mui/x-charts/models';
const scatterChartsParams = {
series: [
{
id: 'series-1',
data: [
{ x: 6.5e-2, y: -1.3, id: 0 },
{ x: -2.1, y: -7.0e-1, id: 1 },
{ x: -7.6e-1, y: -6.7e-1, id: 2 },
{ x: -1.5e-2, y: -2.0e-1, id: 3 },
{ x: -1.4, y: -9.9e-1, id: 4 },
{ x: -1.1, y: -1.5, id: 5 },
{ x: -7.0e-1, y: -2.7e-1, id: 6 },
{ x: -5.1e-1, y: -8.8e-1, id: 7 },
{ x: -4.0e-3, y: -1.4, id: 8 },
{ x: -1.3, y: -2.2, id: 9 },
],
label: 'A',
highlightScope: {
highlight: 'item',
},
},
{
id: 'series-2',
data: [
{ x: 1.8, y: -1.7e-2, id: 0 },
{ x: 7.1e-1, y: 2.6e-1, id: 1 },
{ x: -1.2, y: 9.8e-1, id: 2 },
{ x: 2.0, y: -2.0e-1, id: 3 },
{ x: 9.4e-1, y: -2.7e-1, id: 4 },
{ x: -4.8e-1, y: -1.6e-1, id: 5 },
{ x: -1.5, y: 1.1, id: 6 },
{ x: 1.3, y: 3.4e-1, id: 7 },
{ x: -4.2e-1, y: 1.0e-1, id: 8 },
{ x: 5.4e-2, y: 4.0e-1, id: 9 },
],
label: 'B',
highlightScope: {
highlight: 'item',
},
},
],
height: 300,
} as const;
function getHitRadius(option: 'item' | 'infinite' | '50px') {
switch (option) {
case 'item':
return 'item';
case 'infinite':
return undefined;
case '50px':
return 50;
default:
return undefined;
}
}
export default function ScatterClick() {
const [option, setOption] = React.useState<'item' | 'infinite' | '50px'>(
'infinite',
);
const [data, setData] = React.useState<ScatterItemIdentifier>();
const { ...other } = data ?? {};
const dataDisplayed = data && {
...other,
};
return (
<Stack direction="column" spacing={1} sx={{ width: '100%' }}>
<ToggleButtonGroup
value={option}
size="small"
exclusive
onChange={(event, newValue) => {
if (newValue !== null) {
setOption(newValue);
}
}}
>
<ToggleButton value="item">item</ToggleButton>
<ToggleButton value="infinite">infinite</ToggleButton>
<ToggleButton value="50px">50px</ToggleButton>
</ToggleButtonGroup>
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={{ xs: 0, md: 4 }}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1 }}>
<ScatterChart
{...scatterChartsParams}
hitAreaRadius={getHitRadius(option)}
onItemClick={(_: any, d: ScatterItemIdentifier) => setData(d)}
/>
</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={() => setData(undefined)}
>
<UndoOutlinedIcon fontSize="small" />
</IconButton>
</Box>
<HighlightedCode
code={
dataDisplayed
? JSON.stringify(dataDisplayed, null, 1)
: '// The data will appear here'
}
language="json"
copyButtonHidden
/>
</Stack>
</Stack>
</Stack>
);
}
버블 차트
산점도 차트는 크기와 색상 스케일을 지원해서 마크 하나당 두 개의 추가 값을 표현할 수 있어요.
이것들은 다음으로 구성돼요.
sizeValue/colorValue: 마크 데이터를 제공해요(data에 직접 또는datasetKeys로)sizeAxisId/colorAxisId시리즈 속성: 사용할zAxis스케일을 나타내요.
데모와 자세한 내용은 버블 차트 페이지를 참고하세요.
import * as React from 'react';
import { ScatterChartPro } from '@mui/x-charts-pro/ScatterChartPro';
import { scatterClasses } from '@mui/x-charts-pro/ScatterChart';
import { ChartsTooltipContainer, useItemTooltip } from '@mui/x-charts/ChartsTooltip';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { globalCo2GdpPopulation } from '../dataset/globalCo2GdpPopulation';
const regions = [
'Africa',
'Asia',
'Europe',
'North America',
'Oceania',
'South America',
];
const regionColors = [
'#e6194B',
'#3cb44b',
'#4363d8',
'#f58231',
'#911eb4',
'#42d4f4',
];
const compactCurrencyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
notation: 'compact',
maximumFractionDigits: 1,
});
const compactNumberFormatter = new Intl.NumberFormat('en-US', {
notation: 'compact',
});
function TooltipRow({ label, value }: { label: string; value: string }) {
return (
<Stack
direction="row"
spacing={2}
sx={{ justifyContent: 'space-between', alignItems: 'baseline' }}
>
<Typography variant="caption" sx={{ color: 'text.secondary' }}>
{label}
</Typography>
<Typography variant="caption" sx={{ fontWeight: 'medium' }}>
{value}
</Typography>
</Stack>
);
}
function CountryBubbleTooltipContent() {
const item = useItemTooltip<'scatter'>();
if (!item) {
return null;
}
const country = globalCo2GdpPopulation[item.identifier.dataIndex];
return (
<Paper
elevation={0}
sx={{
p: 1.5,
border: 'solid 1px',
borderColor: 'divider',
}}
>
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', mb: 1 }}>
<Box
sx={{
width: 12,
height: 12,
borderRadius: '50%',
backgroundColor: item.color,
}}
/>
<Typography sx={{ fontWeight: 'medium' }}>{country.name}</Typography>
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
{country.region}
</Typography>
</Stack>
<Stack spacing={0.5}>
<TooltipRow
label="GDP per capita"
value={compactCurrencyFormatter.format(item.value.x)}
/>
<TooltipRow label="CO₂ emissions" value={`${item.value.y.toFixed(1)} t`} />
<TooltipRow
label="Population"
value={compactNumberFormatter.format(country.population)}
/>
</Stack>
</Paper>
);
}
function CountryBubbleTooltip() {
return (
<ChartsTooltipContainer trigger="item">
<CountryBubbleTooltipContent />
</ChartsTooltipContainer>
);
}
export default function BubbleChartCO2Emissions() {
return (
<Stack sx={{ width: '100%' }}>
<ScatterChartPro
height={300}
hideLegend
dataset={globalCo2GdpPopulation}
grid={{ horizontal: true, vertical: true }}
slots={{ tooltip: CountryBubbleTooltip }}
sx={{
[`& .${scatterClasses.series} .${scatterClasses.marker}`]: {
fillOpacity: 0.5,
},
}}
xAxis={[
{
scaleType: 'log',
label: 'GDP per capita (international-$)',
max: 200_000,
valueFormatter: (value: number) =>
compactCurrencyFormatter.format(value),
zoom: true,
},
]}
yAxis={[
{
label: 'CO₂ emissions (t per person)',
width: 50,
zoom: true,
},
]}
zAxis={[
{
// Maps the population to the marker radius (continuous scale).
id: 'population',
dataKey: 'population',
sizeMap: {
type: 'continuous',
min: 1_000,
max: 1_500_000_000,
size: [3, 25],
},
},
{
// Maps the region to a marker color (ordinal scale).
id: 'region',
dataKey: 'region',
colorMap: {
type: 'ordinal',
values: regions,
colors: regionColors,
},
},
]}
hitAreaRadius="item"
series={[
{
datasetKeys: { x: 'gdpPerCapita', y: 'co2_emission', id: 'code' },
sizeAxisId: 'population',
colorAxisId: 'region',
highlightScope: { highlight: 'item', fade: 'none' },
},
]}
/>
<Stack
direction="row"
spacing={2}
useFlexGap
sx={{ flexWrap: 'wrap', justifyContent: 'center' }}
>
{regions.map((region, index) => (
<Stack
key={region}
direction="row"
spacing={0.5}
sx={{ alignItems: 'center' }}
>
<Box
sx={{
width: 12,
height: 12,
borderRadius: '50%',
backgroundColor: regionColors[index],
}}
/>
<Typography variant="caption">{region}</Typography>
</Stack>
))}
</Stack>
<Typography variant="caption" sx={{ textAlign: 'center' }}>
Bubble size is proportional to the population · Data for 2023, Our World in
Data
</Typography>
</Stack>
);
}
스타일링
그리드 (Grid)
grid prop으로 차트 배경에 그리드를 추가할 수 있어요.
자세한 내용은 Axis—Grid를 참고하세요.
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import data from '../dataset/random/scatterParallel.json';
export default function GridDemo() {
return (
<ScatterChart
height={300}
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 })),
},
]}
grid={{ vertical: true, horizontal: true }}
/>
);
}
CSS
CSS 셀렉터로 산점도 차트 엘리먼트를 커스터마이징할 수 있어요.
[data-series='<series ID>']: 해당 ID를 가진 시리즈의 마커 그룹[data-highlighted=true]: 하이라이트 상태의 마커[data-faded=true]: 페이드 상태의 마커
scatterClasses.root 클래스를 사용해서 모든 마커 그룹을 선택하세요.
아래 예시는 시리즈별로 하이라이트 스타일을 커스터마이징해요.
import { ScatterChart, ScatterSeries } from '@mui/x-charts/ScatterChart';
import data from '../dataset/random/scatterParallel.json';
const series: ScatterSeries[] = [
{
id: 'series-1',
label: 'Series A',
data: data.map((v) => ({ x: v.x1, y: v.y1, id: v.id })),
highlightScope: { highlight: 'item', fade: 'global' },
},
{
id: 'series-2',
label: 'Series B',
data: data.map((v) => ({ x: v.x2, y: v.y2, id: v.id })),
highlightScope: { highlight: 'item', fade: 'global' },
},
];
export default function ScatterCSSSelectors() {
return (
<ScatterChart
height={300}
hitAreaRadius={30}
series={series}
sx={{
'& [data-faded=true]': { opacity: 0.4 },
"& [data-series='series-1'] [data-faded=true]": { fill: 'gray' },
"& [data-series='series-1'] [data-highlighted=true]": {
stroke: 'blue',
strokeWidth: 3,
fill: 'none',
},
}}
/>
);
}
모양 (Shape)
marker 슬롯에 컴포넌트를 전달해서 산점도 점의 모양을 커스터마이징할 수 있어요.
범례와 툴팁을 커스텀 모양과 동기화하려면 아래 예시처럼 각 시리즈에 labelMarkType 속성을 설정하세요.
import { ScatterChart, ScatterMarkerProps } from '@mui/x-charts/ScatterChart';
import { ChartsLabelCustomMarkProps } from '@mui/x-charts/ChartsLabel';
import data from '../dataset/random/scatterParallel.json';
export default function ScatterCustomShape() {
return (
<ScatterChart
height={300}
series={[
{
id: '1',
label: 'Series A',
data: data.map((v) => ({ x: v.x1, y: v.y1, id: v.id })),
markerSize: 1,
labelMarkType: StarLabelMark,
},
{
id: '2',
label: 'Series B',
data: data.map((v) => ({ x: v.x2, y: v.y2, id: v.id })),
markerSize: 1,
labelMarkType: DiamondLabelMark,
},
]}
slots={{ marker: CustomMarker }}
/>
);
}
const star =
'M0,-7.528L1.69,-2.326L7.16,-2.326L2.735,0.889L4.425,6.09L0,2.875L-4.425,6.09L-2.735,0.889L-7.16,-2.326L-1.69,-2.326Z';
const diamond = 'M0,-7.423L4.285,0L0,7.423L-4.285,0Z';
function CustomMarker({
size,
x,
y,
seriesId,
isHighlighted,
isFaded,
dataIndex,
color,
...other
}: ScatterMarkerProps) {
const props = {
x: 0,
y: 0,
width: (isHighlighted ? 1.2 : 1) * size,
height: (isHighlighted ? 1.2 : 1) * size,
transform: `translate(${x}, ${y})`,
fill: color,
opacity: isFaded ? 0.3 : 1,
...other,
};
return (
<g {...props}>
<path
d={seriesId === '1' ? star : diamond}
scale={(isHighlighted ? 1.2 : 1) * size}
/>
</g>
);
}
function StarLabelMark({ color, ...props }: ChartsLabelCustomMarkProps) {
return (
<svg viewBox="-7.423 -7.423 14.846 14.846">
<path {...props} d={star} fill={color} />
</svg>
);
}
function DiamondLabelMark({ color, ...props }: ChartsLabelCustomMarkProps) {
return (
<svg viewBox="-7.423 -7.423 14.846 14.846">
<path {...props} d={diamond} fill={color} />
</svg>
);
}
크기 (Size)
각 시리즈에 markerSize prop을 사용해서 산점도 점의 크기를 설정하세요.
원의 경우 markerSize는 픽셀 단위의 반지름이에요.
값에 따라 마크 크기를 수정하려면 버블 차트 페이지를 참고하세요.
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import data from '../dataset/random/scatterParallel.json';
export default function ScatterCustomSize() {
return (
<ScatterChart
height={300}
series={[
{
label: 'Series A',
data: data.map((v) => ({ x: v.x1, y: v.y1, id: v.id })),
markerSize: 8,
},
{
label: 'Series B',
data: data.map((v) => ({ x: v.x2, y: v.y2, id: v.id })),
markerSize: 4,
},
]}
/>
);
}
플롯 커스터마이징
데이터가 플로팅되는 방식을 커스터마이징하려면 ScatterChart의 자식으로 커스텀 컴포넌트를 전달하세요.
useScatterSeries() 훅을 사용해서 커스텀 컴포넌트에서 산점도 차트의 시리즈를 읽어오세요.
이 훅은 각 시리즈의 시리즈 순서와 세부 정보(데이터 포인트, 색상 등)를 반환해요.
차트를 커스터마이징하는 더 많은 방법은 커스텀 컴포넌트를 참고하세요.
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import { useScatterSeries, useXScale, useYScale } from '@mui/x-charts/hooks';
const data1 = [
{ x: 95, y: 200, id: 1 },
{ x: 120, y: 100, id: 2 },
{ x: 170, y: 300, id: 3 },
{ x: 140, y: 250, id: 4 },
{ x: 150, y: 400, id: 5 },
{ x: 110, y: 280, id: 6 },
];
const data2 = [
{ x: 300, y: 300, id: 1 },
{ x: 200, y: 700, id: 2 },
{ x: 400, y: 500, id: 3 },
{ x: 340, y: 350, id: 4 },
{ x: 420, y: 280, id: 5 },
];
const series = [
{ id: 's1', data: data1, label: 'Open' },
{ id: 's2', data: data2, label: 'Closed' },
];
function LinkPoints({ seriesId, close }: { seriesId: string; close?: boolean }) {
const scatter = useScatterSeries(seriesId);
const xScale = useXScale();
const yScale = useYScale();
if (!scatter) {
return null;
}
const { color, data } = scatter;
if (!data) {
return null;
}
return (
<path
fill="none"
stroke={color}
strokeWidth={2}
d={`M ${data.map(({ x, y }) => `${xScale(x)}, ${yScale(y)}`).join(' L')}${
close ? 'Z' : ''
}`}
/>
);
}
export default function CustomScatter() {
return (
<ScatterChart series={series} height={300}>
<LinkPoints seriesId="s1" />
<LinkPoints seriesId="s2" close />
</ScatterChart>
);
}
성능 (Performance)
SVG 일괄 렌더링
산점도 차트는 점이 많을 수 있어서 렌더링이 느려질 수 있어요.
기본적으로 점은 SVG circle 엘리먼트로 그려지는데, 큰 데이터셋에서는 느릴 수 있어요.
renderer prop은 점을 그리는 방식을 선택해요.
기본값은 'svg-single'로 설정돼요.
experimentalFeatures.progressiveRendering을 true로 설정하면 점 개수에 따라 렌더러가 자동으로 선택돼요. 2,000점 이상이면 'svg-progressive', 그 외에는 'svg-single'을 사용해요.
렌더러 선택하기
CSS: CSS 셀렉터로 개별 점에 스타일을 적용할 수 있는지 여부.
상호작용: onItemClick 같은 점별 상호작용이 동작하는지 여부.
차단(Blocking): 모든 점이 그려질 때까지 메인 스레드가 차단되는지 여부.
단일 렌더러
renderer="svg-single"은 점 하나당 circle 엘리먼트 하나를 단일 동기 패스에서 그려요.
CSS 스타일링, marker 슬롯, 항목별 상호작용이 모두 동작하지만, 모든 점이 그려질 때까지 메인 스레드가 차단되므로 작은 데이터셋에만 적합해요.
점진적 렌더러
renderer="svg-progressive"도 점 하나당 circle 엘리먼트 하나를 그리며, CSS 스타일링, marker 슬롯, 항목별 상호작용을 유지해요.
차이점은 시리즈와 축이 렌더 경로 밖에서 처리되고, 점들이 배치로 나뉘며 그 배치의 그룹들이 즉시 마운트되어 여러 애니메이션 프레임에 걸쳐 점진적으로 그려진다는 것이에요.
큰 데이터셋을 그리는 동안에도 메인 스레드는 응답을 유지해요.
아래 예시는 20,000개의 점을 렌더링해요. 버튼을 사용해서 단일 렌더러와 점진적 렌더러를 비교해 보세요. 점진적 렌더러에서는 스피너가 계속 돌아가고 "first paint"가 낮게 유지되는 반면, 단일 렌더러는 모든 점이 그려질 때까지 메인 스레드를 차단해요. 차트를 확대·이동하면 점진적 렌더러가 상호작용하는 동안 첫 단계만 그린 상태를 유지하고, 상호작용이 멈추면 나머지를 채우는 것을 볼 수 있어요. 첫 단계는 각 시리즈의 처음 N개 점이므로, 데이터가 정렬되지 않은 경우에만 대표성이 있어요. 축을 따라 정렬된 데이터는 상호작용이 끝나기 전까지 부분적인 구름만 보일 수 있어요.
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import Tooltip from '@mui/material/Tooltip';
import { ScatterChartPro } from '@mui/x-charts-pro/ScatterChartPro';
import Chance from 'chance';
const NUMBER_OF_SERIES = 3;
const POINT_COUNT = 40000;
// Gaussian-ish blobs so the progressive, batched paint is easy to see. Points
// are split into `NUMBER_OF_SERIES` contiguous series, each offset into its
// own region.
function makeSeries(chance: Chance.Chance, count: number) {
const remainder = count % NUMBER_OF_SERIES;
return Array.from({ length: NUMBER_OF_SERIES }, (_, seriesIndex) => {
const size =
Math.floor(count / NUMBER_OF_SERIES) + (seriesIndex < remainder ? 1 : 0);
const offsetX = (seriesIndex % 2) * 50;
const offsetY = seriesIndex * 25;
const data = Array.from({ length: size }, () => {
const angle = chance.floating({ min: 0, max: 2 * Math.PI });
const radius = Math.sqrt(chance.floating({ min: 0, max: 1 })) * 100;
const noiseX = chance.floating({ min: -100, max: 10 });
const noiseY = chance.floating({ min: -100, max: 10 });
return {
x: offsetX + radius * Math.cos(angle) + noiseX,
y: offsetY + radius * Math.sin(angle) + noiseY,
};
});
return {
id: `series-${seriesIndex}`,
label: `Series ${seriesIndex + 1}`,
data,
markerSize: 2,
};
});
}
// Built once outside the component so toggling does not regenerate the points
// and the series keep stable references.
const syncSeries = makeSeries(new Chance(42), POINT_COUNT);
const asyncSeries = makeSeries(new Chance(43), POINT_COUNT);
// A spinner whose rotation is advanced in JS on every animation frame (not a
// CSS animation, which runs on the compositor and stays smooth regardless).
// If the main thread is blocked, this visibly stutters — a live indicator of
// whether the progressive render keeps the main thread responsive.
function MainThreadSpinner() {
const ref = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
let frame = 0;
let angle = 0;
const tick = () => {
angle = (angle + 6) % 360;
if (ref.current) {
ref.current.style.transform = `rotate(${angle}deg)`;
}
frame = requestAnimationFrame(tick);
};
frame = requestAnimationFrame(tick);
return () => cancelAnimationFrame(frame);
}, []);
return (
<Tooltip
title="Animated on the main thread. It keeps spinning smoothly while the main thread is free, and stutters or freezes when the renderer blocks it — watch it while switching modes."
arrow
>
<Stack direction="row" spacing={0.75} sx={{ alignItems: 'center' }}>
<div
ref={ref}
aria-label="main thread activity"
style={{
width: 16,
height: 16,
borderRadius: '50%',
border: '2px solid currentColor',
borderTopColor: 'transparent',
opacity: 0.6,
}}
/>
</Stack>
</Tooltip>
);
}
// Renders the timing readout in its own component so that updating the
// measured values does NOT re-render the (heavy) chart — otherwise each
// state update would reconcile thousands of points and stall the main
// thread, making the spinner stutter exactly when a value appears.
function RenderTimers(props: {
containerRef: React.RefObject<HTMLDivElement | null>;
startRef: React.RefObject<number | null>;
runId: number;
}) {
const { containerRef, startRef, runId } = props;
const [firstMs, setFirstMs] = React.useState<number | null>(null);
const [totalMs, setTotalMs] = React.useState<number | null>(null);
// Number of distinct paint steps (frames on which the point count grew).
const [paints, setPaints] = React.useState(0);
React.useEffect(() => {
setFirstMs(null);
setTotalMs(null);
setPaints(0);
if (runId === 0 || startRef.current === null) {
return undefined;
}
// Rendering is considered complete when the point count stops growing for
// this many consecutive frames (longer than the gap between batches).
const STABLE_FRAMES = 12;
let frame = 0;
let firstSeen = false;
let lastCount = 0;
let stableFrames = 0;
let paintCount = 0;
// Time of the most recent point-count change, so the reported total is the
// moment the last batch painted, not when stability was confirmed.
let lastChangeAt = 0;
const check = () => {
const now = performance.now();
const count = containerRef.current?.querySelectorAll('circle').length ?? 0;
if (!firstSeen && count > 0) {
firstSeen = true;
setFirstMs(now - startRef.current!);
}
if (firstSeen) {
if (count === lastCount) {
stableFrames += 1;
} else {
stableFrames = 0;
lastCount = count;
lastChangeAt = now;
paintCount += 1;
setPaints(paintCount);
}
if (stableFrames >= STABLE_FRAMES) {
setTotalMs(lastChangeAt - startRef.current!);
return;
}
}
frame = requestAnimationFrame(check);
};
frame = requestAnimationFrame(check);
return () => cancelAnimationFrame(frame);
}, [runId, containerRef, startRef]);
return (
<React.Fragment>
<Typography variant="body2" sx={{ minWidth: 110 }}>
first paint: {firstMs === null ? '—' : `${firstMs.toFixed(0)} ms`}
</Typography>
<Typography variant="body2" sx={{ minWidth: 110 }}>
total: {totalMs === null ? '—' : `${totalMs.toFixed(0)} ms`}
</Typography>
<Typography variant="body2" sx={{ minWidth: 90 }}>
paints: {paints}
</Typography>
</React.Fragment>
);
}
export default function ScatterAsyncRenderer() {
// Default to progressive so first paint on docs load does not block the
// main thread while rendering all points at once.
const [mode, setMode] = React.useState<'sync' | 'async'>('async');
const series = mode === 'sync' ? syncSeries : asyncSeries;
const containerRef = React.useRef<HTMLDivElement>(null);
// Bumped on every click; `RenderTimers` keys its measurement off it.
const [runId, setRunId] = React.useState(0);
const startRef = React.useRef<number | null>(null);
const select = (next: 'sync' | 'async') => {
startRef.current = performance.now();
setRunId((id) => id + 1);
setMode(next);
};
return (
<Stack spacing={2} sx={{ width: '100%' }}>
<Stack spacing={1} sx={{ alignItems: 'center' }}>
<Stack
direction="row"
spacing={2}
useFlexGap
sx={{
alignItems: 'center',
justifyContent: 'center',
flexWrap: 'wrap',
}}
>
<Typography variant="h6" sx={{ textAlign: 'center' }}>
{mode === 'sync'
? `${POINT_COUNT.toLocaleString()} points`
: `${POINT_COUNT.toLocaleString()} points`}
</Typography>
<Button
variant={mode === 'sync' ? 'contained' : 'outlined'}
size="small"
onClick={() => select('sync')}
>
Single
</Button>
<Button
variant={mode === 'async' ? 'contained' : 'outlined'}
size="small"
onClick={() => select('async')}
>
Progressive
</Button>
</Stack>
<Stack
direction="row"
spacing={2}
useFlexGap
sx={{
alignItems: 'center',
justifyContent: 'center',
flexWrap: 'wrap',
}}
>
<MainThreadSpinner />
<RenderTimers
containerRef={containerRef}
startRef={startRef}
runId={runId}
/>
</Stack>
</Stack>
<div ref={containerRef} style={{ width: '100%' }}>
<ScatterChartPro
key={runId}
series={series}
height={400}
xAxis={[{ zoom: true }]}
yAxis={[{ zoom: true }]}
// Force the renderer so the two modes are directly comparable:
// - `svg-single`: original synchronous per-item renderer.
// - `svg-progressive`: batched renderer that paints over several
// animation frames to keep the main thread responsive.
// (Leaving `renderer` unset would pick automatically by point count.)
renderer={mode === 'sync' ? 'svg-single' : 'svg-progressive'}
/>
</div>
</Stack>
);
}
일괄 렌더러
renderer="svg-batch"는 점들을 path 엘리먼트로 그룹화해서 그려요. 아주 큰 데이터셋에서 더 효율적이에요.
몇 가지 트레이드오프가 있어요.
- CSS로 개별 원을 스타일링할 수 없어요.
marker슬롯을 오버라이드할 수 없어요.- 투명 하이라이트: 하이라이트 상태는 원본 위에 원을 그려요. 하이라이트의 투명성 때문에 원본 원이 비쳐 보일 수 있어요.
동작도 몇 가지 면에서 달라요.
- 렌더링 순서가 바뀔 수 있어서, 겹치는 원이 다른 렌더러보다 다른 깊이로 나타날 수 있어요.
disableHitArea가true이면onItemClick이 실행되지 않아요. 히트 영역 로직에 의존하기 때문이에요.
아래 예시는 renderer prop을 사용해서 16,000개의 점을 더 나은 성능으로 렌더링해요.
import Stack from '@mui/material/Stack';
import Paper from '@mui/material/Paper';
import Divider from '@mui/material/Divider';
import { ChartsTooltipContainer, useItemTooltip } from '@mui/x-charts/ChartsTooltip';
import { ScatterChart, ScatterChartProps } from '@mui/x-charts/ScatterChart';
import Typography from '@mui/material/Typography';
import { schemePaired } from 'd3-scale-chromatic';
import { electricityGeneration2024Every6Hours } from '../dataset/electricityGeneration2024Every6Hours';
import { carbonEmissions2024Every6Hours } from '../dataset/carbonEmissions2024Every6Hours';
import { countryData, flags } from '../dataset/countryData';
const dateFormat = new Intl.DateTimeFormat(undefined, {
month: 'short',
day: 'numeric',
});
const timeRangeFormat = new Intl.DateTimeFormat(undefined, {
hour: '2-digit',
minute: '2-digit',
});
function getDatesFromIndex(index: number): [Date, Date] {
const from = new Date(2024, 0, 1, index * 6);
const to = new Date(2024, 0, 1, index * 6 + 6);
return [from, to];
}
const scatterChartsParams = {
series: Object.entries(electricityGeneration2024Every6Hours).map(
([countryCode, electricity]) => ({
id: countryCode,
data: electricity.map((value, index) => ({
x: value / 1000,
y: carbonEmissions2024Every6Hours[
countryCode as keyof typeof electricityGeneration2024Every6Hours
][index],
})),
markerSize: 1,
label:
countryData[countryCode as keyof typeof electricityGeneration2024Every6Hours]
.country,
highlightScope: {
highlight: 'series',
fade: 'global',
},
}),
),
xAxis: [
{ min: 0, label: 'Electricity Generation (GWh)', domainSeries: 'visible' },
],
yAxis: [
{
min: 0,
width: 60,
label: 'Life-cycle Carbon Intensity (gCO₂eq/kWh)',
domainSeries: 'visible',
},
],
height: 400,
colors: schemePaired,
slotProps: {
legend: {
toggleVisibilityOnClick: true,
position: { vertical: 'bottom' },
sx: { justifyContent: 'center' },
},
},
slots: {
tooltip: ElectricityTooltip,
},
} satisfies ScatterChartProps;
export default function ScatterBatchRenderer() {
return (
<Stack spacing={{ xs: 0, md: 2 }} sx={{ width: '100%' }}>
<Typography variant="h6" sx={{ alignSelf: 'center', textAlign: 'center' }}>
Life-cycle Carbon Intensity of Electricity Generation - 2024
</Typography>
<ScatterChart {...scatterChartsParams} renderer="svg-batch" />
<Typography variant="caption">Source: ENTSO-E, ElectricityMaps.com</Typography>
</Stack>
);
}
function ElectricityTooltip() {
return (
<ChartsTooltipContainer trigger="item">
<ElectricityTooltipContent />
</ChartsTooltipContainer>
);
}
function ElectricityTooltipContent() {
const item = useItemTooltip<'scatter'>();
if (!item) {
return null;
}
const [from, to] = getDatesFromIndex(item.identifier.dataIndex);
return (
<Paper sx={{ p: 1.5 }} elevation={4}>
<Typography
variant="subtitle2"
sx={{ justifyContent: 'space-between', display: 'flex' }}
>
{item.label} {flags[item.identifier.seriesId as keyof typeof flags]}
</Typography>
<Typography variant="body2">
{`${dateFormat.format(from)} ${timeRangeFormat.format(from)} - ${timeRangeFormat.format(to)}`}
</Typography>
<Divider sx={{ my: 1 }} />
<Typography variant="body1">
Generated:{' '}
<Typography component="span" variant="body2">
{item.value.x.toFixed(2)} GWh
</Typography>
</Typography>
<Typography variant="body1">
Emitting:{' '}
<Typography component="span" variant="body2">
{item.value.y.toFixed(2)} gCO₂eq/kWh
</Typography>
</Typography>
</Paper>
);
}
WebGL 렌더러
아주 큰 데이터셋의 경우 ScatterChartPremium은 SVG 뒤에 레이어로 깔린 전용 WebGL 캔버스에 점을 그리는 webgl 렌더러를 지원해요.
이것은 점별 SVG를 완전히 우회하고, 항목 수준의 상호작용을 처리량과 맞바꿔요.
아래 예시는 200,000개의 점을 렌더링해요.
import * as React from 'react';
import { ScatterChartPremium } from '@mui/x-charts-premium/ScatterChartPremium';
const POINTS_PER_SERIES = 200_000;
// Inline mulberry32 — deterministic, ~20x faster than `chance.floating`.
// 800k calls during module load with Chance takes several seconds and stalls
// the Next.js build; this runs in ~50ms.
/* eslint-disable no-bitwise */
function makeRandom(seed: number) {
let state = seed;
return () => {
state = (state + 0x6d2b79f5) | 0;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
};
}
/* eslint-enable no-bitwise */
function generateSeries(offset: number, spread: number, seed: number) {
const rand = makeRandom(seed);
const data = new Array(POINTS_PER_SERIES);
for (let i = 0; i < POINTS_PER_SERIES; i += 1) {
const u1 = Math.max(rand(), 1e-6);
const u2 = rand();
const r = Math.sqrt(-2 * Math.log(u1));
const theta = 2 * Math.PI * u2;
data[i] = {
id: i,
x: offset + r * Math.cos(theta) * spread,
y: offset + r * Math.sin(theta) * spread,
};
}
return data;
}
const DATA_1 = generateSeries(0, 1, 42);
const DATA_2 = generateSeries(4, 1.5, 7);
export default function ScatterWebGLRenderer() {
const series = React.useMemo(
() => [
{ label: 'Cluster A', data: DATA_1, markerSize: 1 },
{ label: 'Cluster B', data: DATA_2, markerSize: 1 },
],
[],
);
return (
<ScatterChartPremium
series={series}
xAxis={[{ min: -6, max: 12, zoom: true }]}
yAxis={[{ min: -6, max: 12, zoom: true }]}
height={400}
renderer="webgl"
slotProps={{
legend: {
toggleVisibilityOnClick: true,
},
}}
/>
);
}
합성 (Composition)
커스텀 차트를 구성할 때는 ChartsDataProvider를 사용해서 series, xAxis, yAxis를 공급하세요.
합성에서 설명한 공유 컴포넌트들에 더해 ScatterPlot을 사용해서 산점도 점을 그릴 수 있어요.
산점도 차트는 이렇게 구성돼요.
<ChartsDataProvider>
<ChartsWrapper>
<ChartsLegend />
<ChartsSurface>
<ChartsAxis />
<ChartsGrid />
<g data-drawing-container>
{/* Elements able to overflow the drawing area. */}
<ScatterPlot />
</g>
<FocusedScatterMark />
<ChartsOverlay />
<ChartsAxisHighlight />
</ChartsSurface>
<ChartsTooltip trigger="item" />
</ChartsWrapper>
</ChartsDataProvider>
:::info
data-drawing-container 속성은 자식들이 넘쳐도 그리기 영역의 일부로 표시해요.
자세한 내용은 Composition—clipping을 참고하세요. :::
회귀선 (Regression line)
커스텀 차트를 구성하고 직접 선을 그려서 산점도 플롯에 회귀선을 추가할 수 있어요.
import * as React from 'react';
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import { useSeries, useXScale, useYScale } from '@mui/x-charts/hooks';
import { ChartsClipPath } from '@mui/x-charts/ChartsClipPath';
import useId from '@mui/utils/useId';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { useTheme } from '@mui/material/styles';
import { rainbowSurgePalette } from '@mui/x-charts/colorPalettes';
import { diamonds } from '../dataset/diamonds';
const dollarFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 0,
});
export default function ScatterRegressionLine() {
return (
<Stack sx={{ width: '100%' }}>
<Typography variant="h6" component="span" sx={{ textAlign: 'center' }}>
Relation between Weight and Price of Diamonds
</Typography>
<ScatterChart
dataset={diamonds}
height={300}
xAxis={[{ min: 0, label: 'Weight (carats)' }]}
yAxis={[
{
min: 0,
width: 80,
valueFormatter: (value: number) => dollarFormatter.format(value),
label: 'Price (USD)',
},
]}
series={[
{
id: 'diamonds',
datasetKeys: { x: 'carat', y: 'price' },
markerSize: 2,
valueFormatter: (v) =>
`${dollarFormatter.format(v!.y)} for ${v!.x} carat`,
},
]}
>
<RegressionLine seriesId="diamonds" />
</ScatterChart>
<Typography variant="caption">Source: OpenML</Typography>
</Stack>
);
}
function RegressionLine({ seriesId }: { seriesId: string }) {
const theme = useTheme();
const palette = rainbowSurgePalette(theme.palette.mode);
const stroke = palette[2];
const allSeries = useSeries();
// Scatter's series processor is async, so `allSeries.scatter` is `undefined`
// until it settles. Keep hooks unconditional and bail out of rendering only.
const series = allSeries.scatter?.series[seriesId];
const xScale = useXScale(series?.xAxisId ?? undefined);
const yScale = useYScale(series?.yAxisId ?? undefined);
const clipPathId = `linear-regression-clip-${useId()}`;
if (!series) {
return null;
}
const { m, b } = linearRegression(series.data ?? []);
const xDomain = xScale.domain() as [number, number];
const x1 = xScale(xDomain[0]);
const x2 = xScale(xDomain[1]);
const y1 = yScale(m * xDomain[0] + b);
const y2 = yScale(m * xDomain[1] + b);
return (
<React.Fragment>
<ChartsClipPath id={clipPathId} />
<g clipPath={`url(#${clipPathId})`}>
<line x1={x1} y1={y1} x2={x2} y2={y2} stroke={stroke} strokeWidth={2} />
</g>
</React.Fragment>
);
}
function linearRegression(points: ReadonlyArray<{ x: number; y: number }>) {
const n = points.length;
// Calculate sums
let sumX = 0,
sumY = 0,
sumXY = 0,
sumX2 = 0;
for (let i = 0; i < n; i += 1) {
const x = points[i].x;
const y = points[i].y;
sumX += x;
sumY += y;
sumXY += x * y;
sumX2 += x * x;
}
// Calculate slope (m) and intercept (b)
const m = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
const b = (sumY - m * sumX) / n;
return { m, b };
}
더 알아보기
더 자세한 내용은 MUI X Charts 문서를 참고하세요.