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

Charts - 성능(Performance)

원문 보기 위키 갱신

대규모 데이터셋을 렌더링할 때 차트를 빠르고 반응성 있게 유지하는 방법을 알아봅니다.

본문

차트의 성능은 여러 요인으로 나눌 수 있습니다: 계산 시간, React 재렌더링 시간, DOM 업데이트 시간. 이 페이지는 렌더링을 부드럽게 유지하는 데 가장 영향력 있는 옵션을 설명합니다.

안정적인 참조 제공하기(Provide stable references)

차트는 축/시리즈에서 많은 상태를 파생하며 관련 prop이 참조(reference)로 변경될 때마다 이를 다시 계산합니다. 매 렌더링마다 새 배열이나 객체를 전달하면 데이터 자체가 변경되지 않았더라도 이 작업이 다시 실행되고 추가 재렌더링이 발생합니다.

다음 prop은 안정적인 참조의 이점을 얻습니다:

  • series
  • xAxis, yAxis, zAxis
  • dataset
  • margin
  • colors

값이 절대 변경되지 않으면 컴포넌트 밖에서 정의해 렌더링 전반에 걸쳐 동일한 참조가 재사용되도록 하세요:

// Defined once, outside the component.
const xAxis = [{ scaleType: 'band', data: ['A', 'B', 'C'] }];

function MyChart() {
  return <BarChart xAxis={xAxis} series={series} height={300} />;
}

값이 props나 state에 의존하면 useMemo로 감싸 입력이 변경될 때만 다시 계산되도록 하세요:

function MyChart({ data }) {
  const series = React.useMemo(() => [{ data }], [data]);

  return <LineChart series={series} height={300} />;
}

:::warning 문서는 JSX에서 많은 인라인 객체와 배열을 직접 사용합니다(예: margin={{ top: 10 }} 또는 series={[{ data }]}).

문서 섹션에서 명확성을 위해 그렇게 합니다. 하지만 매 렌더링마다 새 참조가 만들어져 내부 메모이제이션을 무효화합니다. :::

애니메이션 건너뛰기

애니메이션은 작은 차트에는 편리하지만 매 프레임마다 DOM을 업데이트해야 합니다. 데이터 포인트가 많으면 이 작업이 배가됩니다.

skipAnimation prop을 설정해 전환 없이 최종 상태를 직접 렌더링하세요:

<LineChart series={series} skipAnimation />

라인 차트에서 마크 제거하기

라인 시리즈에 showMark를 true로 설정하면 모든 데이터 포인트마다 마크 요소가 렌더링됩니다. 수천 개의 포인트가 있는 시리즈라면 성능에 영향을 줄 수 있는 수천 개의 DOM 노드가 추가됩니다.

마크를 비활성화하거나 그 수를 줄이세요.

// One mark per 100 values.
showMark: ({ index }) => index % 100 === 0;
// Only a mark at the end of the series.
showMark: 'end';
// Only a mark at the beginning of the series.
showMark: 'start';

자세한 내용은 Line charts—Optimization을 참고하세요.

더 효율적인 렌더러 사용하기

기본적으로 각 항목은 자체 SVG 요소로 그려집니다 — 막대마다 <rect>, 산점도 포인트마다 <circle>. 유연하지만 확장성이 좋지 않습니다: DOM 노드 수가 데이터 포인트 수와 함께 늘어납니다.

막대 및 산점도 차트는 renderer prop을 받아 더 효율적인 그리기 전략으로 전환할 수 있습니다:

  • 'svg-single' (기본): 모든 항목을 자체 SVG 요소로 렌더링합니다.
  • 'svg-batch': 모든 항목을 몇 개의 <path> 요소로 일괄 처리해 대규모 데이터셋의 DOM 노드 수를 크게 줄입니다.
<BarChart series={series} renderer="svg-batch" />

일괄 렌더러는 CSS로 개별 항목 스타일을 지정할 수 없는 것 같은 몇 가지 트레이드오프가 있습니다. 제한 사항 전체 목록과 실시간 데모는 전용 섹션을 참고하세요:

WebGL 렌더러

가장 큰 데이터셋의 경우 BarChartPremium, ScatterChartPremium, HeatmapPremium이 GPU를 사용해 항목을 단일 <canvas> 요소로 그리는 'webgl' 렌더러를 지원합니다. 이것은 항목 수준의 상호작용을 수십만 개의 포인트를 렌더링할 수 있는 능력과 맞바꿉니다.

<ScatterChartPremium series={series} renderer="webgl" />

자세한 내용과 데모는 Bar charts—WebGL renderer, Scatter charts—WebGL renderer, Heatmap—WebGL renderer를 참고하세요.

샘플링(Sampling)

차트에 그리기 영역이 요소를 너무 작게 만들지 않고는 보여줄 수 없는 것보다 더 많은 데이터가 있으면, 렌더링 전에 데이터를 적절한 수준의 세부 정보로 줄일 수 있습니다. 이것은 확대 가능한 차트와 정적 차트 모두에 적용됩니다.

BarChartPro와 LineChartPro는 방법을 선택하는 sampling prop을 받습니다:

  • 'none' (기본): 모든 요소를 렌더링합니다.
  • 'minmax': 각 버킷의 최소/최대를 유지합니다.
  • 'm4': 픽셀 정확도 — 각 버킷의 첫 번째, 최소, 최대, 마지막 포인트를 유지합니다(라인 시리즈).
  • 'lttb': Largest-Triangle-Three-Buckets, 버킷당 하나의 대표 포인트를 유지해 모양을 보존합니다(라인 시리즈).

확대 가능한 차트에서는 확대할수록 더 많은 세부 정보가 점차 드러납니다. 뷰가 모든 요소를 해상도로 처리할 수 있게 되면 샘플링이 꺼집니다. 정적 차트(zoom 없음)는 전체 범위에서 샘플링되므로 대규모 데이터셋도 적절한 수준의 세부 정보로 렌더링됩니다.

샘플링은 또한 렌더링되는 요소 수에 상한(2,000)을 유지합니다. 뷰가 그 아래로 들어가면 차트는 모든 보이는 요소를 그대로 렌더링합니다. 확대된 뷰가 여전히 그보다 많은 요소를 보유하고 있으면 각 요소가 스스로 그릴 만큼 넓어도 샘플링이 유지됩니다 — 따라서 매우 조밀한 데이터셋이 어느 확대 수준에서도 렌더러를 압도하지 않습니다.

:::info 줌 minSpan은 백분율이므로, 가장 확대된 뷰는 항상 약 dataLength × minSpan / 100개의 요소를 렌더링합니다. 매우 큰 데이터셋에서는 축 zoom.minSpan을 작게 유지해 가장 깊은 확대에서 너무 많은 요소가 한 번에 렌더링되지 않도록 하세요. :::

방법 비교하기

동일한 8,784개 포인트 시리즈를 각 방법으로 같은 줌에서 렌더링했습니다. 'none'이 기준(모든 포인트)이며, 나머지는 전체 모양을 보존하면서 훨씬 적은 요소로 이를 근사합니다.

import * as React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { LineChartPro } from '@mui/x-charts-pro/LineChartPro';
import type { ZoomData } from '@mui/x-charts-pro/models';
import { electricityGeneration2024Hourly } from '../dataset/electricityGeneration2024Hourly';

// Real dataset: average electricity generation (MW) for every hour of 2024 (8,784 points).
const data = electricityGeneration2024Hourly.DEU;
const xData = data.map((_, index) => index);

const compactFormatter = new Intl.NumberFormat('en-US', { notation: 'compact' });

const METHODS = [
  { value: 'none', label: 'None — every point' },
  { value: 'minmax', label: 'Min/max' },
  { value: 'm4', label: 'M4' },
  { value: 'lttb', label: 'LTTB' },
] as const;

export default function SamplingMethodComparison() {
  // Shared controlled zoom so the charts stay aligned: zooming one zooms all, comparing the methods
  // over the same range.
  const [zoomData, setZoomData] = React.useState<ZoomData[]>([
    { axisId: 'x', start: 0, end: 100 },
  ]);

  return (
    <Box
      sx={{
        display: 'grid',
        gridTemplateColumns: { xs: '1fr', sm: '1fr 1fr' },
        gap: 2,
        width: '100%',
      }}
    >
      {METHODS.map((method) => (
        <Box key={method.value}>
          <Typography variant="caption" color="text.secondary">
            {method.label}
          </Typography>
          <LineChartPro
            series={[{ data, showMark: false }]}
            xAxis={[{ data: xData, id: 'x', zoom: true }]}
            yAxis={[
              {
                width: 40,
                valueFormatter: (value: number) => compactFormatter.format(value),
              },
            ]}
            height={160}
            sampling={method.value}
            zoomData={zoomData}
            onZoomChange={setZoomData}
            hideLegend
          />
        </Box>
      ))}
    </Box>
  );
}

막대 샘플링

막대는 각 범위의 값 엔벨로프를 유지하는 버킷으로 병합되므로, 봉우리와 골짜기가 살아남습니다. 'none' 외의 어떤 방법도 이를 활성화합니다(막대는 항상 min/max 엔벨로프를 사용합니다).

<BarChartPro series={series} sampling="minmax" />
import * as React from 'react';
import Stack from '@mui/material/Stack';
import FormControlLabel from '@mui/material/FormControlLabel';
import Switch from '@mui/material/Switch';
import { BarChartPro } from '@mui/x-charts-pro/BarChartPro';
import tripCounts from '../dataset/nyc-yellow-taxi-2024-trip-count.json';

// Real dataset: NYC yellow taxi trips per hour over 2024 (8,781 points). Each entry is
// `[dayOfYear, hour, tripCount]`.
const data = tripCounts.map((entry) => entry[2]);
const categories = data.map((_, index) => String(index));

const compactFormatter = new Intl.NumberFormat('en-US', { notation: 'compact' });

export default function BarSampling() {
  const [enabled, setEnabled] = React.useState(true);

  return (
    <Stack sx={{ width: '100%' }} spacing={1}>
      <FormControlLabel
        control={
          <Switch
            checked={enabled}
            onChange={(event) => setEnabled(event.target.checked)}
          />
        }
        label={`Sampling ${enabled ? 'on' : 'off'} (${data.length.toLocaleString()} bars — zoom in to reach the raw data)`}
      />
      <BarChartPro
        // Small `minSpan` so zooming steps through every sampling level down to the raw data.
        xAxis={[{ data: categories, zoom: { minSpan: 1 }, tickSpacing: 100 }]}
        yAxis={[
          {
            label: 'Trips',
            valueFormatter: (value: number) => compactFormatter.format(value),
          },
        ]}
        series={[{ data, label: 'Trips' }]}
        height={300}
        sampling={enabled ? 'minmax' : 'none'}
      />
    </Stack>
  );
}

라인 샘플링

라인은 세 가지 알고리즘을 모두 지원합니다. 데이터에 가장 잘 맞는 것을 선택하세요. Comparing methods를 참고하세요.

<LineChartPro series={series} sampling="m4" />
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import { LineChartPro } from '@mui/x-charts-pro/LineChartPro';
import { electricityGeneration2024Hourly } from '../dataset/electricityGeneration2024Hourly';

// Real dataset: average electricity generation (MW) for every hour of 2024 (8,784 points).
const data = electricityGeneration2024Hourly.DEU;
const xData = data.map((_, index) => index);

const compactFormatter = new Intl.NumberFormat('en-US', { notation: 'compact' });

const METHODS = [
  { value: 'none', label: 'None' },
  { value: 'm4', label: 'M4' },
  { value: 'minmax', label: 'Min/max' },
  { value: 'lttb', label: 'LTTB' },
] as const;

type Method = (typeof METHODS)[number]['value'];

export default function LineSampling() {
  const [sampling, setSampling] = React.useState<Method>('m4');

  return (
    <Stack sx={{ width: '100%' }} spacing={1}>
      <ToggleButtonGroup
        size="small"
        exclusive
        value={sampling}
        onChange={(event, value) => value !== null && setSampling(value)}
        aria-label="Sampling method"
      >
        {METHODS.map((option) => (
          <ToggleButton key={option.value} value={option.value}>
            {option.label}
          </ToggleButton>
        ))}
      </ToggleButtonGroup>
      <Typography variant="caption" color="text.secondary">
        {data.length.toLocaleString()} hourly points — zoom in to reach the raw data
      </Typography>
      <LineChartPro
        xAxis={[{ data: xData, zoom: true }]}
        yAxis={[
          {
            label: 'Generation (MW)',
            valueFormatter: (value: number) => compactFormatter.format(value),
          },
        ]}
        series={[{ data, label: 'Generation (MW)', showMark: false }]}
        height={300}
        sampling={sampling}
      />
    </Stack>
  );
}

null 값을 가진 시리즈도 샘플링됩니다. 간격은 보존되므로 선이 이를 다리로 연결하지 않고 그 지점에서 끊깁니다.

import * as React from 'react';
import Stack from '@mui/material/Stack';
import FormControlLabel from '@mui/material/FormControlLabel';
import Switch from '@mui/material/Switch';
import Typography from '@mui/material/Typography';
import { LineChartPro } from '@mui/x-charts-pro/LineChartPro';
import { electricityGeneration2024Hourly } from '../dataset/electricityGeneration2024Hourly';

// Real dataset: average electricity generation (MW) for every hour of 2024 (8,784 points).
const base = electricityGeneration2024Hourly.DEU;
const xData = base.map((_, index) => index);

const compactFormatter = new Intl.NumberFormat('en-US', { notation: 'compact' });

// Same series with a few hour-long gaps (null) punched in.
const withGaps: (number | null)[] = base.map((value, index) =>
  index % 1500 >= 700 && index % 1500 < 760 ? null : value,
);

export default function LineSamplingNulls() {
  const [hasGaps, setHasGaps] = React.useState(true);
  const data = hasGaps ? withGaps : base;

  return (
    <Stack sx={{ width: '100%' }} spacing={1}>
      <FormControlLabel
        control={
          <Switch
            checked={hasGaps}
            onChange={(event) => setHasGaps(event.target.checked)}
          />
        }
        label="Insert null gaps"
      />
      <Typography variant="caption" color="text.secondary">
        Sampling is set to <code>m4</code>. Series with <code>null</code> values are
        still sampled; the gaps are preserved, so the line breaks instead of bridging
        them.
      </Typography>
      <LineChartPro
        xAxis={[{ data: xData, zoom: true }]}
        yAxis={[
          {
            label: 'Generation (MW)',
            valueFormatter: (value: number) => compactFormatter.format(value),
          },
        ]}
        series={[{ data, label: 'Generation (MW)', showMark: false }]}
        height={300}
        sampling="m4"
      />
    </Stack>
  );
}

더 알아보기

출처: MUI X documentation