본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Charts - 버블(Bubble)

원문 보기 위키 갱신

버블 차트는 데이터 값을 점의 크기와 색상에 매핑해 스캐터를 확장해서, 2차원 공간에서 3차원 또는 4차원을 드러내요.

출처: MUI X documentation

본문

개요(Overview)

버블 차트는 각 점이 데이터 값에 따라 가변적인 크기와 색상을 가질 수 있는 스캐터 차트예요. x와 y 위치는 두 변수를 인코딩하고, 버블 크기와 색상은 추가 변수를 인코딩해요.

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>
  );
}

데이터를 색상에 매핑하기

다른 차트와 마찬가지로 시리즈 색상을 직접 또는 색상 팔레트로 수정할 수 있어요.

축의 colorMap을 사용해 색상을 수정할 수도 있는데, colorMap은 값을 색상에 매핑해요. 스캐터 차트는 다음 우선순위 순서를 사용해요:

  1. z-축 색상
  2. y-축 색상
  3. x-축 색상
  4. 시리즈 색상

:::info z-축은 위치 외의 값으로 스캐터 점을 스타일링할 수 있게 해주는 세 번째 축이에요. zAxis prop으로 전달하세요.

매핑된 값은 각 시리즈 데이터 점의 colorValue 속성 또는 z-축 데이터에서 올 수 있어요. 색상 값을 설정하는 방법은 세 가지예요:

<ScatterChart
  // First option
  series={[{ data: [{ id: 0, x: 1, y: 1, colorValue: 5 }] }]}
  // Second option
  zAxis={[{ data: [5] }]}
  // Third option
  dataset={[{ price: 5 }]}
  zAxis={[{ dataKey: 'price' }]}
/>

:::

colorMap 속성은 Styling—값 기반 색상을 참고하세요.

import * as React from 'react';
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import { ScatterValueType } from '@mui/x-charts/models';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
import { Chance } from 'chance';

const POINTS_NUMBER = 50;
const chance = new Chance(42);

export default function ColorScale() {
  const [colorX, setColorX] = React.useState<'None' | 'piecewise' | 'continuous'>(
    'piecewise',
  );
  const [colorY, setColorY] = React.useState<'None' | 'piecewise' | 'continuous'>(
    'None',
  );
  const [colorZ, setColorZ] = React.useState<
    'None' | 'piecewise' | 'continuous' | 'ordinal'
  >('None');

  return (
    <Stack direction="column" spacing={1} sx={{ width: '100%', maxWidth: 600 }}>
      <Stack
        direction="row"
        sx={{
          gap: 1,
          flexWrap: 'wrap',
          width: '100%',

          '&>div': {
            display: 'flex',
            flexDirection: 'column',
          },
        }}
      >
        <div>
          <Typography variant="caption">x-axis colorMap</Typography>
          <ToggleButtonGroup
            color="primary"
            size="small"
            exclusive
            value={colorX}
            onChange={(_, value: 'None' | 'piecewise' | 'continuous') =>
              setColorX(value)
            }
            aria-label="Platform"
          >
            <ToggleButton value="None">None</ToggleButton>
            <ToggleButton value="piecewise">piecewise</ToggleButton>
            <ToggleButton value="continuous">continuous</ToggleButton>
          </ToggleButtonGroup>
        </div>
        <div>
          <Typography variant="caption">y-axis colorMap</Typography>
          <ToggleButtonGroup
            color="primary"
            size="small"
            exclusive
            value={colorY}
            onChange={(_, value: 'None' | 'piecewise' | 'continuous') =>
              setColorY(value)
            }
            aria-label="Platform"
          >
            <ToggleButton value="None">None</ToggleButton>
            <ToggleButton value="piecewise">piecewise</ToggleButton>
            <ToggleButton value="continuous">continuous</ToggleButton>
          </ToggleButtonGroup>
        </div>
        <div>
          <Typography variant="caption">z-axis colorMap</Typography>
          <ToggleButtonGroup
            color="primary"
            size="small"
            exclusive
            value={colorZ}
            onChange={(_, value: 'None' | 'piecewise' | 'continuous' | 'ordinal') =>
              setColorZ(value)
            }
            aria-label="Platform"
          >
            <ToggleButton value="None">None</ToggleButton>
            <ToggleButton value="piecewise">piecewise</ToggleButton>
            <ToggleButton value="continuous">continuous</ToggleButton>
            <ToggleButton value="ordinal">ordinal</ToggleButton>
          </ToggleButtonGroup>
        </div>
      </Stack>
      <ScatterChart
        height={300}
        grid={{ horizontal: true, vertical: true }}
        series={series}
        yAxis={[
          {
            min: -3,
            max: 3,
            tickInterval: [-3, -1.5, 0, 1.5, 3],
            colorMap:
              (colorY === 'continuous' && {
                type: 'continuous',
                min: -2,
                max: 2,
                color: ['blue', 'red'],
              }) ||
              (colorY === 'piecewise' && {
                type: 'piecewise',
                thresholds: [-1.5, 0, 1.5],
                colors: ['lightblue', 'blue', 'orange', 'red'],
              }) ||
              undefined,
          },
        ]}
        xAxis={[
          {
            min: -3,
            max: 3,
            tickInterval: [-3, -1.5, 0, 1.5, 3],
            colorMap:
              (colorX === 'continuous' && {
                type: 'continuous',
                min: -2,
                max: 2,
                color: ['green', 'orange'],
              }) ||
              (colorX === 'piecewise' && {
                type: 'piecewise',
                thresholds: [-1.5, 0, 1.5],
                colors: ['#d01c8b', '#f1b6da', '#b8e186', '#4dac26'],
              }) ||
              undefined,
          },
        ]}
        zAxis={[
          {
            data:
              colorZ === 'ordinal'
                ? [
                    ...[...Array(POINTS_NUMBER)].map(() => 'A'),
                    ...[...Array(POINTS_NUMBER)].map(() => 'B'),
                    ...[...Array(POINTS_NUMBER)].map(() => 'C'),
                    ...[...Array(POINTS_NUMBER)].map(() => 'D'),
                  ]
                : undefined,
            colorMap:
              (colorZ === 'continuous' && {
                type: 'continuous',
                min: -2,
                max: 2,
                color: ['green', 'orange'],
              }) ||
              (colorZ === 'piecewise' && {
                type: 'piecewise',
                thresholds: [-1.5, 0, 1.5],
                colors: ['#d01c8b', '#f1b6da', '#b8e186', '#4dac26'],
              }) ||
              (colorZ === 'ordinal' && {
                type: 'ordinal',

                values: ['A', 'B', 'C', 'D'],
                colors: ['#d01c8b', '#f1b6da', '#b8e186', '#4dac26'],
              }) ||
              undefined,
          },
        ]}
      />
      <HighlightedCode
        code={[
          `<ScatterChart`,
          '  /* ... */',
          '  series={[{ data: data.map(point => ({...point, colorValue: point.x + point.y})) }]}',
          // ColorX
          ...(colorX === 'None' ? ['  xAxis={[{}]}'] : []),
          ...(colorX === 'continuous'
            ? [
                '  xAxis={[{',
                `    colorMap: {`,
                `      type: 'continuous',`,
                `      min: -2,`,
                `      max: 2,`,
                `      color: ['green', 'orange']`,
                `    }`,
                '  }]}',
              ]
            : []),
          ...(colorX === 'piecewise'
            ? [
                '  xAxis={[{',
                `    colorMap: {`,
                `      type: 'piecewise',`,
                `      thresholds: [-1.5, 0, 1.5],`,
                `      colors: ['#d01c8b', '#f1b6da', '#b8e186', '#4dac26'],`,
                `    }`,
                '  }]}',
              ]
            : []),

          // ColorY
          ...(colorY === 'None' ? ['  yAxis={[{}]}'] : []),
          ...(colorY === 'continuous'
            ? [
                '  yAxis={[{',
                `    colorMap: {`,
                `      type: 'continuous',`,
                `      min: -2,`,
                `      max: 2,`,
                `      color: ['blue', 'red']`,
                `    }`,
                '  }]}',
              ]
            : []),
          ...(colorY === 'piecewise'
            ? [
                '  yAxis={[{',
                `    colorMap: {`,
                `      type: 'piecewise',`,
                `      thresholds: [-1.5, 0, 1.5],`,
                `      colors: ['lightblue', 'blue', 'orange', 'red'],`,
                `    }`,
                '  }]}',
              ]
            : []),

          // ColorZ
          ...(colorZ === 'None' ? ['  zAxis={[{}]}'] : []),
          ...(colorZ === 'continuous'
            ? [
                '  zAxis={[{',
                `    colorMap: {`,
                `      type: 'continuous',`,
                `      min: -2,`,
                `      max: 2,`,
                `      color: ['green', 'orange'],`,
                `    }`,
                '  }]}',
              ]
            : []),
          ...(colorZ === 'piecewise'
            ? [
                '  zAxis={[{',
                `    colorMap: {`,
                `      type: 'piecewise',`,
                `      thresholds: [-1.5, 0, 1.5],`,
                `      colors: ['#d01c8b', '#f1b6da', '#b8e186', '#4dac26'],`,
                `    }`,
                '  }]}',
              ]
            : []),
          ...(colorZ === 'ordinal'
            ? [
                '  zAxis={[{',
                `    data: ['A', ..., 'B', ..., 'C', ..., 'D', ...],`,
                `    colorMap: {`,
                `      type: 'ordinal',`,
                `      values: ['A', 'B', 'C', 'D'],`,
                `      colors: ['#d01c8b', '#f1b6da', '#b8e186', '#4dac26'],`,
                `    }`,
                '  }]}',
              ]
            : []),
          `/>`,
        ].join('\n')}
        language="jsx"
        copyButtonHidden
      />
    </Stack>
  );
}

const series = [
  {
    data: [
      ...getGaussianSeriesData([-1, -1]),
      ...getGaussianSeriesData([-1, 1]),
      ...getGaussianSeriesData([1, 1]),
      ...getGaussianSeriesData([1, -1]),
    ],
  },
].map((s) => ({
  ...s,
  valueFormatter: (v: ScatterValueType | null) =>
    v && `(${v.x.toFixed(1)}, ${v.y.toFixed(1)})`,
}));

function getGaussianSeriesData(
  mean: [number, number],
  stdev: [number, number] = [0.5, 0.5],
  N: number = 50,
) {
  return [...Array(N)].map((_, i) => {
    const x =
      Math.sqrt(-2.0 * Math.log(1 - chance.floating({ min: 0, max: 0.99 }))) *
        Math.cos(2.0 * Math.PI * chance.floating({ min: 0, max: 0.99 })) *
        stdev[0] +
      mean[0];
    const y =
      Math.sqrt(-2.0 * Math.log(1 - chance.floating({ min: 0, max: 0.99 }))) *
        Math.cos(2.0 * Math.PI * chance.floating({ min: 0, max: 0.99 })) *
        stdev[1] +
      mean[1];
    return { x, y, colorValue: x + y, id: `${mean.join(',')}${i}` };
  });
}

데이터를 크기에 매핑하기

값을 각 스캐터 점의 크기에 매핑할 수도 있어요.

z-축에 sizeMap을 설정하고 sizeAxisId prop으로 시리즈가 그것을 가리키게 하세요. 매핑된 값은 각 데이터 점의 sizeValue 속성 또는 z-축 데이터에서 와요.

sizeMap은 colorMap과 같은 continuous, piecewise, ordinal 타입을 지원하지만, 값을 픽셀 단위의 마커 반지름에 매핑해요. 시리즈는 colorAxisId와 sizeAxisId를 모두 설정해 두 값으로 한 번에 점을 스타일링할 수 있어요.

import * as React from 'react';
import { ScatterChart } from '@mui/x-charts/ScatterChart';

const data = [
  { x: 1, y: 2, sizeValue: 2 },
  { x: 2.4, y: 1.5, sizeValue: 8 },
  { x: 3.1, y: 3.4, sizeValue: 14 },
  { x: 1.8, y: 4.2, sizeValue: 5 },
  { x: 4.5, y: 2.8, sizeValue: 20 },
  { x: 3.7, y: 1.2, sizeValue: 11 },
  { x: 2.1, y: 3.9, sizeValue: 17 },
  { x: 4.9, y: 4.6, sizeValue: 3 },
  { x: 0.8, y: 1.1, sizeValue: 9 },
  { x: 3.3, y: 2.2, sizeValue: 25 },
  { x: 2.7, y: 4.8, sizeValue: 6 },
  { x: 4.1, y: 3.1, sizeValue: 13 },
];

export default function SizeScale() {
  return (
    <ScatterChart
      height={300}
      grid={{ horizontal: true, vertical: true }}
      series={[{ data, sizeAxisId: 'size' }]}
      zAxis={[
        {
          id: 'size',
          sizeMap: { type: 'continuous', min: 0, max: 25, size: [3, 24] },
        },
      ]}
    />
  );
}

커스텀 컴포넌트에서 zAxis 사용하기

zAxis는 기본 스캐터 플롯이 내부적으로 사용하는 색상 및 크기 스케일을 제공해요.

커스텀 마커는 이미 이 스케일을 통해 매핑된 color와 size 값을 받으므로, 선 색상(stroke color)과 선 두께(stroke width) 같은 추가 시각 속성을 쉽게 파생할 수 있어요.

더 고급 사용 사례에서는 커스텀 컴포넌트가 useZAxis() 훅으로 z-축 스케일에 직접 접근하고, useScatterSeries() 훅으로 시리즈 데이터에 접근할 수 있어요.

아래 예시는 Iris 꽃 데이터셋을 일부 분류 예측과 함께 렌더링해요. 4개의 z-축을 사용해 다음을 매핑해요:

  • 종(species)을 채우기 색상으로
  • 예측된 종을 선 색상으로
  • 꽃잎 길이를 마크 크기로
  • 신뢰도(confidence)를 선 두께로
import * as React from 'react';
import { ScatterChart, ScatterMarkerProps } from '@mui/x-charts/ScatterChart';
import { ChartsTooltipContainer, useItemTooltip } from '@mui/x-charts/ChartsTooltip';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import { useZAxis } from '@mui/x-charts/hooks';
import { irisData } from '../dataset/irisDataset';

const species = ['Setosa', 'Versicolor', 'Virginica'];
const speciesColors = ['#2e7d32', '#ed6c02', '#9c27b0'];
const speciesPredictionColors = ['#5aa35e', '#be7f4b', '#ba68c9'];

function IrisMarker(props: ScatterMarkerProps) {
  const { x, y, color, size, isHighlighted, isFaded, dataIndex, ...other } = props;

  // Get and use color/size scale to determine stroke color and width based on prediction and confidence z-axes.
  const predictionAxis = useZAxis('prediction');
  const confidenceAxis = useZAxis('confidence');
  const strokeWidth =
    confidenceAxis?.sizeScale?.(confidenceAxis.data?.[dataIndex]) ?? 0;
  const strokeColor =
    predictionAxis?.colorScale?.(predictionAxis.data?.[dataIndex]) ?? 'gray';

  const r = (isHighlighted ? 1.2 : 1) * size;
  return (
    <circle
      cx={0}
      cy={0}
      r={r}
      transform={`translate(${x}, ${y})`}
      fill={color}
      fillOpacity={isFaded ? 0.15 : 0.35}
      stroke={strokeColor}
      strokeWidth={strokeWidth}
      strokeOpacity={isFaded ? 0.3 : 1}
      cursor={other.onClick ? 'pointer' : 'unset'}
      {...other}
    />
  );
}

/**
 * Explains how the scatter plot encodes multiple dimensions of the dataset.
 */
function IrisAnnotation() {
  return (
    <Typography variant="caption" sx={{ textAlign: 'center' }}>
      Fill color represents the actual species, stroke color represents the predicted
      species, bubble size represents petal length, and stroke width represents
      prediction confidence.
    </Typography>
  );
}

function IrisTooltip() {
  return (
    <ChartsTooltipContainer trigger="item">
      <IrisTooltipContent />
    </ChartsTooltipContainer>
  );
}

function IrisTooltipContent() {
  const item = useItemTooltip<'scatter'>();

  function numberFormatter(value: number | string | undefined) {
    if (typeof value === 'number') {
      return new Intl.NumberFormat('en-US').format(value);
    }
    return String(value);
  }

  // Get the full data item from irisData using dataIndex from identifier
  const dataIndex = item?.identifier.dataIndex;
  const dataItem = dataIndex !== undefined ? irisData[dataIndex] : null;

  if (!item || !dataItem) {
    return null;
  }

  return (
    <Paper sx={{ p: 1.5 }} elevation={4}>
      <Box
        sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', mb: 1 }}
      >
        <Box
          sx={{
            width: 20,
            height: 20,
            backgroundColor: item?.color,
            borderRadius: 1,
            mr: 2,
          }}
        />
        <Typography sx={{ fontWeight: 600 }}>{dataItem.species}</Typography>
      </Box>
      <Divider sx={{ my: 1 }} />
      <Box sx={{ display: 'grid', gridTemplateColumns: '1fr', gap: 0.75 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
          <Typography variant="caption">Sepal Length:</Typography>
          <Typography variant="caption" sx={{ fontWeight: 500 }}>
            {numberFormatter(dataItem.sepalLength)} cm
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
          <Typography variant="caption">Sepal Width:</Typography>
          <Typography variant="caption" sx={{ fontWeight: 500 }}>
            {numberFormatter(dataItem.sepalWidth)} cm
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
          <Typography variant="caption">Petal Length:</Typography>
          <Typography variant="caption" sx={{ fontWeight: 500 }}>
            {numberFormatter(dataItem.petalLength)} cm
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
          <Typography variant="caption">Petal Width:</Typography>
          <Typography variant="caption" sx={{ fontWeight: 500 }}>
            {numberFormatter(dataItem.petalWidth)} cm
          </Typography>
        </Box>
        <Divider sx={{ my: 0.5 }} />
        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
          <Typography variant="caption">Predicted:</Typography>
          <Typography variant="caption" sx={{ fontWeight: 500 }}>
            {dataItem.prediction}
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
          <Typography variant="caption">Confidence:</Typography>
          <Typography variant="caption" sx={{ fontWeight: 500 }}>
            {numberFormatter(dataItem.confidence)}%
          </Typography>
        </Box>
      </Box>
    </Paper>
  );
}

export default function ScatterZAxis() {
  return (
    <Stack sx={{ width: '100%' }}>
      <ScatterChart
        dataset={irisData}
        height={300}
        grid={{ horizontal: true, vertical: true }}
        series={[
          {
            id: 'data',
            colorAxisId: 'species',
            sizeAxisId: 'petal',
            datasetKeys: { x: 'sepalLength', y: 'sepalWidth' },
            highlightScope: { highlight: 'item', fade: 'global' },
          },
        ]}
        xAxis={[{ label: 'Sepal length (cm)' }]}
        yAxis={[{ label: 'Sepal width (cm)' }]}
        zAxis={[
          {
            id: 'species',
            dataKey: 'species',
            colorMap: {
              type: 'ordinal',
              values: species,
              colors: speciesColors,
            },
          },
          {
            id: 'petal',
            dataKey: 'petalLength',
            sizeMap: {
              type: 'continuous',
              min: 1,
              max: 7,
              size: [3, 10],
            },
          },
          {
            id: 'prediction',
            dataKey: 'prediction',
            colorMap: {
              type: 'ordinal',
              values: species,
              colors: speciesPredictionColors,
            },
          },
          {
            id: 'confidence',
            dataKey: 'confidence',
            sizeMap: {
              type: 'continuous',
              min: Math.min(...irisData.map((item) => item.confidence)),
              max: 100,
              size: [0.5, 3],
            },
          },
        ]}
        slots={{ marker: IrisMarker, tooltip: IrisTooltip }}
      ></ScatterChart>
      <IrisAnnotation />
    </Stack>
  );
}

다양한 크기 스케일

기본적으로 type: 'continuous'인 sizeMap은 값을 제곱근(square root) 스케일로 변환해요. 그 덕분에 값이 반지름이 아니라 버블의 표면적에 비례하게 돼요.

sizeMap.interpolator: 'log' | 'linear' | 'sqrt'로 그 동작을 바꾸거나, sizeMap.size에 함수를 제공할 수 있어요.

그렇게 할 때는 크기 인코딩이 오해를 불러일으키지 않도록 설명(copy)에서 선택을 명확히 하세요.

import * as React from 'react';
import { ScatterChartPro } from '@mui/x-charts-pro/ScatterChartPro';
import { ChartsReferenceLine } from '@mui/x-charts-pro/ChartsReferenceLine';

const values = [1, 2, 3, 5, 7, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100];

const scales = ['linear', 'sqrt', 'log'] as const;
const series = scales.map((interpolator) => ({
  data: values.map((v) => ({ x: v, y: interpolator, sizeValue: v })),
  sizeAxisId: interpolator,
}));

export default function DifferentSizeScale() {
  return (
    <ScatterChartPro
      height={300}
      grid={{ horizontal: true, vertical: true }}
      // @ts-expect-error - scatter are not supposed to contain string values for now
      series={series}
      yAxis={[{ scaleType: 'band', data: scales }]}
      xAxis={[{ zoom: true }]}
      zAxis={[
        {
          id: 'sqrt',
          sizeMap: {
            type: 'continuous',
            min: 5,
            max: 100,
            size: [2, 30],
            interpolator: 'sqrt',
          },
        },
        {
          id: 'linear',
          sizeMap: {
            type: 'continuous',
            min: 5,
            max: 100,
            size: [2, 30],
            interpolator: 'linear',
          },
        },
        {
          id: 'log',
          sizeMap: {
            type: 'continuous',
            min: 5,
            max: 100,
            size: [2, 30],
            interpolator: 'log',
          },
        },
      ]}
      slots={{ tooltip: () => null }}
    >
      <ChartsReferenceLine x={5} label="min" labelAlign="start" />
    </ScatterChartPro>
  );
}