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

Charts - 컴포지션

원문 보기 위키 갱신

Charts - 컴포지션 (Composition)

컴포지션을 사용해 고급 커스텀 차트를 만드는 방법을 알아볼게요.

출처: MUI X documentation

본문

개요 (Overview)

컴포지션(Composition)을 사용하면 미리 구성된 단일 컴포넌트 대신 개별 구성 요소로 차트를 조립할 수 있어요. 시리즈 타입을 섞고, 커스텀 SVG 및 WebGL 레이어를 쌓고, 훅을 통해 차트의 스케일을 재사용해 데이터와 정렬된 고유한 요소를 렌더링할 수 있어요. 이를 통해 공통 좌표계, 축, 툴팁, 상호작용을 유지하면서 표준 차트 컴포넌트를 넘어서는 시각화를 만들 수 있어요.

아래 예보(forecast)는 막대, 라인, 축, 동기화된 툴팁, 커스텀 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 { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { BarPlot } from '@mui/x-charts/BarChart';
import { LineHighlightPlot, LinePlot, MarkPlot } from '@mui/x-charts/LineChart';
import { ChartsAxisHighlight } from '@mui/x-charts/ChartsAxisHighlight';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsGrid } from '@mui/x-charts/ChartsGrid';
import {
  ChartsTooltipContainer,
  ChartsTooltipPaper,
  ChartsTooltipTable,
  ChartsTooltipRow,
  ChartsTooltipCell,
  useAxesTooltip,
} from '@mui/x-charts/ChartsTooltip';
import { ChartsLabelMark } from '@mui/x-charts/ChartsLabel';
import { axisClasses } from '@mui/x-charts/ChartsAxis';
import { AxisItemIdentifier } from '@mui/x-charts/models';
import { forecast } from '../dataset/weatherForecast';
import {
  DayAndTimeHeader,
  WeatherMarkers,
  MaxPrecipitationBars,
  LegendItem,
} from './weatherCompositionComponents';

export default function WeatherComposition() {
  const [highlightedAxis, setHighlightedAxis] = React.useState<AxisItemIdentifier[]>(
    [],
  );

  const sync = {
    highlightedAxis,
    onHighlightedAxisChange: setHighlightedAxis,
  };

  return (
    <Stack spacing={1} sx={{ width: '100%' }}>
      <Stack
        spacing={2}
        sx={(theme) => ({
          width: '100%',
          [`& .${axisClasses.tick}, & .${axisClasses.line}`]: {
            stroke: theme.palette.divider,
          },
          [`& .${axisClasses.tickLabel}`]: {
            fill: theme.palette.secondary,
          },
        })}
      >
        <ForecastChart {...sync} />
        <WindChart {...sync} />
      </Stack>
      <Stack
        direction="row"
        spacing={2}
        sx={{ flexWrap: 'wrap', rowGap: 0.5, justifyContent: 'center' }}
      >
        <LegendItem color={colors.temperature} label="Temperature C" />
        <LegendItem color={colors.precipitation} label="Precipitation mm" />
        <LegendItem color={colors.maxPrecipitation} label="Max precip. mm" hatch />
        <LegendItem color={colors.wind} label="Wind m/s" />
        <LegendItem color={colors.windGust} label="Wind gust m/s" dashed />
      </Stack>
    </Stack>
  );
}

type AxisSyncProps = {
  highlightedAxis: AxisItemIdentifier[];
  onHighlightedAxisChange: (axisItems: AxisItemIdentifier[]) => void;
};

function ForecastChart(props: AxisSyncProps) {
  return (
    <ChartsContainer
      {...props}
      dataset={forecast}
      xAxis={[
        {
          id: 'time',
          scaleType: 'band',
          dataKey: 'time',
          height: 0,
          valueFormatter: (value: Date) =>
            value.toLocaleDateString('en-US', {
              month: 'short',
              day: 'numeric',
              hour: 'numeric',
            }),
        },
      ]}
      yAxis={[
        {
          id: 'temperature',
          min: 6,
          max: 26,
          width: 50,
          valueFormatter: (value: number) => `${value}°`,
        },
        {
          id: 'precipitation',
          label: 'Precipitation (mm)',
          position: 'right',
          min: 0,
          max: 8,
          width: 56,
        },
      ]}
      series={weatherSeries}
      height={310}
      margin={{ top: 64, right: 24, bottom: 8, left: 36 }}
    >
      <ChartsGrid horizontal />

      <DayAndTimeHeader />
      <MaxPrecipitationBars />
      <BarPlot />
      <LinePlot />
      <MarkPlot />
      <WeatherMarkers />
      <ChartsYAxis axisId="precipitation" />
      <ChartsYAxis disableLine axisId="temperature" />
      <ChartsAxisHighlight x="band" />
      <ChartsAxisHighlight x="line" />
      <ChartsTooltipContainer>
        <WeatherTooltip type="weather" />
      </ChartsTooltipContainer>
    </ChartsContainer>
  );
}

function WindChart(props: AxisSyncProps) {
  return (
    <ChartsContainer
      {...props}
      dataset={forecast}
      xAxis={[
        {
          id: 'time',
          scaleType: 'band',
          dataKey: 'time',
          height: 0,
          valueFormatter: (value: Date) =>
            value.toLocaleDateString('en-US', {
              month: 'short',
              day: 'numeric',
              hour: 'numeric',
            }),
        },
      ]}
      yAxis={[
        {
          id: 'wind',
          position: 'right',
          min: 0,
          width: 56,
          tickInterval: [0, 4, 8],
        },
      ]}
      series={windSeries}
      height={150}
      margin={{ top: 8, right: 24, bottom: 32, left: 86 }}
      sx={{ [`& [data-series=gust]`]: { strokeDasharray: '4 4' } }}
    >
      <ChartsGrid horizontal />

      <LinePlot />
      <LineHighlightPlot />
      <ChartsYAxis axisId="wind" label="Wind m/s" />
      <ChartsAxisHighlight x="band" />
      <ChartsAxisHighlight x="line" />
      <ChartsTooltipContainer>
        <WeatherTooltip type="wind" />
      </ChartsTooltipContainer>
    </ChartsContainer>
  );
}

function WeatherTooltip({ type }: { type: 'weather' | 'wind' }) {
  const tooltipData = useAxesTooltip();

  if (
    !tooltipData ||
    tooltipData.length === 0 ||
    (type === 'weather' &&
      !tooltipData[0].seriesItems.some((item) => item.seriesId === 'temperature')) ||
    (type === 'wind' &&
      !tooltipData[0].seriesItems.some((item) => item.seriesId === 'wind'))
  ) {
    return null;
  }

  const { dataIndex, axisFormattedValue } = tooltipData[0];
  const item = forecast[dataIndex];

  if (!item) {
    return null;
  }

  const rows = [
    {
      label: 'Temperature',
      color: colors.temperature,
      mark: 'line',
      value: `${item.temperature}°C`,
    },
    {
      label: 'Precipitation',
      color: colors.precipitation,
      mark: 'square',
      value: `${item.precipitation}mm`,
    },
    {
      label: 'Max precip.',
      color: colors.maxPrecipitation,
      mark: 'square',
      value: `${item.maxPrecipitation}mm`,
    },
    { label: 'Wind', color: colors.wind, mark: 'line', value: `${item.wind} m/s` },
    {
      label: 'Wind gust',
      color: colors.windGust,
      mark: 'line',
      value: `${item.gust} m/s`,
    },
  ] as const;

  return (
    <ChartsTooltipPaper>
      <ChartsTooltipTable>
        <Typography component="caption">{axisFormattedValue}</Typography>
        <tbody>
          {rows.map((row) => (
            <ChartsTooltipRow key={row.label}>
              <ChartsTooltipCell component="th">
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <ChartsLabelMark type={row.mark} color={row.color} />
                  {row.label}
                </Box>
              </ChartsTooltipCell>
              <ChartsTooltipCell component="td">{row.value}</ChartsTooltipCell>
            </ChartsTooltipRow>
          ))}
        </tbody>
      </ChartsTooltipTable>
    </ChartsTooltipPaper>
  );
}

const colors = {
  temperature: '#c21807',
  precipitation: '#1565c0',
  maxPrecipitation: '#64b5f6',
  wind: '#7e22ce',
  windGust: '#7c4dff',
};

const weatherSeries = [
  {
    id: 'precipitation',
    type: 'bar',
    dataKey: 'precipitation',
    yAxisId: 'precipitation',
    label: 'Precipitation',
    color: colors.precipitation,
    valueFormatter: (value: number | null) => (value !== null ? `${value}mm` : ''),
  },
  {
    id: 'temperature',
    type: 'line',
    dataKey: 'temperature',
    yAxisId: 'temperature',
    label: 'Temperature',
    color: colors.temperature,
    showMark: false,
    curve: 'natural',
    valueFormatter: (value: number | null) => (value !== null ? `${value}°C` : ''),
  },
] as const;

const windSeries = [
  {
    id: 'wind',
    type: 'line',
    dataKey: 'wind',
    yAxisId: 'wind',
    label: 'Wind',
    color: colors.wind,
    curve: 'linear',
    valueFormatter: (value: number | null) => (value !== null ? `${value} m/s` : ''),
  },
  {
    id: 'gust',
    type: 'line',
    dataKey: 'gust',
    yAxisId: 'wind',
    label: 'Wind gust',
    color: colors.windGust,
    curve: 'linear',
    valueFormatter: (value: number | null) => (value !== null ? `${value} m/s` : ''),
  },
] as const;

MUI X Charts 컴포넌트는 컨텍스트 프로바이더 기반의 아키텍처를 따르며, 시리즈와 축 정의를 전문화된 컴포넌트에 전달할 수 있어요. 이 컴포넌트들이 데이터를 변환해 자손 요소들이 사용할 수 있게 만들어요. 그런 다음 이 자손 요소들을 컴포즈할 수 있어요.

차트를 만드는 데 사용되는 주요 컴포넌트 타입은 구조 컴포넌트(structural)와 그래픽 컴포넌트(graphical) 두 가지예요.

구조 컴포넌트 (Structural components)

구조 컴포넌트는 차트의 크기, 표면, 데이터를 정의하는 데 사용돼요.

  • 기본 (Basics)
    • ChartsDataProvider는 자손 요소들에게 데이터를 제공해요.
    • ChartsLayerContainer는 차트의 반응성(responsiveness)을 처리하고 레이어를 담는 div예요.
    • ChartsSvgLayer는 SVG 요소인 레이어를 렌더링하며, 축, 플롯 등을 렌더링하는 데 사용할 수 있어요.
    • ChartsWebGLLayer는 WebGL 캔버스인 레이어를 렌더링하며, 플롯을 렌더링하는 데 사용할 수 있어요.
  • 헬퍼 (Helpers)
    • ChartsContainer는 Data Provider와 Surface 컴포넌트를 결합해요.
    • ChartsSurface는 레이어 컨테이너와 SVG 레이어를 결합해요.
    • ChartsWrapper는 surface, tooltip, legend를 그리드에 배치하는 스타일된 div예요.

:::info 이 문서의 데모는 ChartsContainer 컴포넌트를 사용해요. ChartsDataProvider와 ChartsSurface를 사용하는 데모는 HTML components 문서를 참고하세요. :::

Chart Data Provider와 Surface 사용법

width와 height props가 ChartsDataProvider에 전달되는 점에 주목하세요.

ChartsLegend는 컨텍스트에 접근하기 위해 ChartsDataProvider 안에 배치되지만, 차트 자체 밖에 표시하고 싶으므로 ChartsLayerContainer 밖에 배치돼요.

<ChartsDataProvider
  // The configuration of the chart
  series={[{ type: 'bar', data: [100, 200] }]}
  xAxis={[{ scaleType: 'band', data: ['A', 'B'] }]}
  width={500}
  height={300}
>
  <ChartsLegend />
  <ChartsLayerContainer>
    <ChartsSvgLayer>{children}</ChartsSvgLayer>
  </ChartsLayerContainer>
</ChartsDataProvider>

Chart Surface 사용법

ChartsSurface 컴포넌트는 ChartsLayerContainer와 ChartsSvgLayer로 구성돼요. 차트에 SVG 레이어가 하나뿐일 때 바로 가기로 사용할 수 있어요.

ChartsSurface를 사용하면 모든 자식이 SVG 요소 안에 렌더링돼요. 즉, 두 SVG 레이어 사이에 캔버스를 렌더링하는 것처럼 서로 다른 레이어를 번갈아 배치할 수 없어요.

<ChartsDataProvider
  // The configuration of the chart
  series={[{ type: 'bar', data: [100, 200] }]}
  xAxis={[{ scaleType: 'band', data: ['A', 'B'] }]}
  width={500}
  height={300}
>
  <ChartsLegend />
  <ChartsSurface>{children}</ChartsSurface>
</ChartsDataProvider>

Chart Container 사용법

ChartsContainer는 ChartsDataProvider와 ChartsSurface를 직접 결합한 것이에요. 이 두 컴포넌트 사이에서 props를 전달하는 역할을 해요.

ChartsContainer를 사용하면 모든 자식이 ChartsSurface 안에 들어간다는 큰 단점이 있어요. 이전 예시처럼 ChartsLegend와 같은 HTML 요소를 렌더링할 수 없어요.

<ChartsContainer
  // The configuration of the chart
  series={[{ type: 'bar', data: [100, 200] }]}
  xAxis={[{ scaleType: 'band', data: ['A', 'B'] }]}
  width={500}
  height={300}
>
  {children} // Only SVG components here
</ChartsContainer>

Chart Wrapper 사용법

차트는 종종 그래픽과 범례로 구성돼요. ChartsWrapper는 이런 요소들을 그리드 구조로 배치하는 데 도움을 줘요.

자식들은 CSS gridArea 속성이 'chart', 'legend', 또는 'toolbar'로 설정되어야 해요. 이는 내장 컴포넌트에서 기본적으로 처리돼요.

레이아웃은 wrapper props로 수정할 수 있어요.

<ChartsDataProvider height={300} series={ /* ... */ }>
  <ChartsWrapper legendDirection='horizontal' legendPosition={{ vertical: 'bottom' }}>
    <ChartsLegend direction='horizontal' />
    <ChartsSurface>
      {children}
    </ChartsSurface>
  </ChartsWrapper>
</ChartsDataProvider>

그래픽 컴포넌트 (Graphical components)

그래픽 컴포넌트는 차트의 시각적 요소를 렌더링하는 데 사용돼요. 앞서 설명한 ChartsDataProvider의 자손이에요. 너무 많아서 나열할 수 없지만, 흔한 예시는 다음과 같아요:

  • LinePlot
  • BarPlot
  • ChartsXAxis
  • ChartsLegend
  • ChartsTooltip

이 목적을 위해 커스텀 컴포넌트를 직접 만들 수도 있어요.

컨테이너 옵션 (Container options)

반응형 크기 (Responsive dimensions)

ChartsContainer는 기본적으로 반응형이에요. 부모 요소가 정의한 사용 가능한 공간에 맞게 크기를 자동 조정해요.

width와 height props를 제공해 차트의 크기를 정의할 수 있어요.

:::warning 차트가 반응형이 되려면 부모 요소가 고유(intrinsic) 크기를 가져야 해요. 부모의 크기가 콘텐츠에 의존하면 반응형 차트가 렌더링되지 않아요. :::

아래 데모에서는 고정 크기(width={500} height={300}) 차트와 크기가 정의되지 않은 차트를 전환해 그 차이를 확인할 수 있어요.

import * as React from 'react';
import Paper from '@mui/material/Paper';
import Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { BarPlot } from '@mui/x-charts/BarChart';
import { LinePlot, MarkPlot } from '@mui/x-charts/LineChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';

export default function BasicComposition() {
  const [isResponsive, setIsResponsive] = React.useState(false);

  const sizingProps = isResponsive ? {} : { width: 500, height: 300 };
  return (
    <Box sx={{ width: '100%', overflow: 'auto' }}>
      <FormControlLabel
        checked={isResponsive}
        control={
          <Checkbox onChange={(event) => setIsResponsive(event.target.checked)} />
        }
        label="Use responsive container"
        labelPlacement="end"
      />
      <Paper sx={{ margin: 1, height: 300 }} elevation={3}>
        <ChartsContainer
          series={[
            {
              type: 'bar',
              data: [1, 2, 3, 2, 1],
            },
            {
              type: 'line',
              data: [4, 3, 1, 3, 4],
              showMark: true,
            },
          ]}
          xAxis={[
            {
              data: ['A', 'B', 'C', 'D', 'E'],
              scaleType: 'band',
              id: 'x-axis-id',
              height: 48,
            },
          ]}
          {...sizingProps}
        >
          <BarPlot />
          <LinePlot />
          <MarkPlot />
          <ChartsXAxis label="X axis" axisId="x-axis-id" />
        </ChartsContainer>
      </Paper>
    </Box>
  );
}

속성 (Properties)

ChartsContainer는 단일 그래픽 요소에만 특화된 props를 제외한 모든 props를 받아요. 여기에는 다음이 포함돼요:

시리즈 (Series)

series prop은 시리즈 정의의 배열이에요. 각 시리즈 타입에 대한 자세한 내용은 다음 문서를 참고하세요:

자체 포함 차트( self-contained Chart) 컴포넌트를 사용할 때는 시리즈 타입이 차트 타입과 일치한다고 가정해요. 예를 들어 BarChart는 series가 'bar' 타입이라고 가정해요.

<BarChart
  series={[
    {
      // No need to specify the series type
      data: [1, 2, 3],
    },
  ]}
/>

커스텀 차트를 컴포즈할 때 ChartsContainer는 시리즈 타입을 모르므로 명시적으로 정의해야 해요. 예를 들어 아래 커스텀 차트는 BarPlot과 LinePlot을 모두 사용하며, 각각 data에 해당하는 type이 필요해요.

<ChartsContainer
  series={[
    // This series is for the bar plot
    { data: [1, 2, 3], type: 'bar' },
    // This series is for the line plot
    { data: [3, 2, 1], type: 'line' },
  ]}
>
  <BarPlot /> {/* Only displays the series with type: 'bar' */}
  <LinePlot /> {/* Only displays series with type: 'line' */}
</ChartsContainer>

이런 시리즈는 단일 컴포넌트 차트와 같은 방식으로 dataset prop을 사용할 수 있어요. 자세한 내용은 Bars—Using a dataset 문서를 참고하세요.

아래 데모에서 차트는 BarPlot과 LinePlot을 결합해 구성돼요. 시리즈 type 속성을 수정해 라인과 막대 렌더링을 전환할 수 있어요.

<ChartsContainer
  series={[
    { type, data: [1, 2, 3, 2, 1] },
    { type, data: [4, 3, 1, 3, 4] },
  ]}
>
  <BarPlot />
  <LinePlot />
  <ChartsXAxis label="X axis" axisId="x-axis-id" />
</ChartsContainer>
import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { BarPlot } from '@mui/x-charts/BarChart';
import { LinePlot } from '@mui/x-charts/LineChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';

export default function SwitchSeriesType() {
  const [type, setType] = React.useState<'line' | 'bar'>('line');

  return (
    <Box sx={{ width: '100%' }}>
      <TextField
        select
        value={type}
        onChange={(event) => setType(event.target.value as 'line' | 'bar')}
        label="series type"
        sx={{ minWidth: 150 }}
      >
        <MenuItem value="line">line</MenuItem>
        <MenuItem value="bar">bar</MenuItem>
      </TextField>
      <div>
        <ChartsContainer
          series={[
            {
              type,
              data: [1, 2, 3, 2, 1],
            },
            {
              type,
              data: [4, 3, 1, 3, 4],
            },
          ]}
          xAxis={[
            {
              data: ['A', 'B', 'C', 'D', 'E'],
              scaleType: 'band',
              id: 'x-axis-id',
              height: 48,
            },
          ]}
          height={200}
        >
          <BarPlot />
          <LinePlot />
          <ChartsXAxis label="X axis" axisId="x-axis-id" />
        </ChartsContainer>
      </div>
    </Box>
  );
}

하위 컴포넌트 (Subcomponents)

:::info CSS z-index 속성은 SVG 요소에 존재하지 않으므로, 컴포즈된 컴포넌트에서 SVG 요소의 순서가 겹침을 정의하는 유일한 방법이에요. 나중에 렌더링되는 요소가 먼저 렌더링된 요소 위에 표시돼요. :::

플로팅 (Plotting)

데이터를 표시하려면 LinePlot, AreaPlot, MarkPlot, BarPlot 등과 같은 [Type]Plot 이름의 컴포넌트를 사용할 수 있어요.

클리핑 (Clipping)

ChartsClipPath 컴포넌트를 사용해 차트 요소가 지정된 드로잉 영역 안에만 머물도록 보장할 수 있어요. 이 컴포넌트는 경계 역할을 하는 직사각형 클립 경로를 정의해요.

적용 방법은 다음과 같아요:

  1. 클립 경로 정의: <ChartsClipPath id={clipPathId} />를 사용해 드로잉 영역에 대한 클립 경로를 설정해요. clipPathId는 고유한 식별자여야 해요.
  2. 차트 감싸기: 클립하고 싶은 차트 요소를 <g> 요소 안에 넣어요. clipPath 속성을 url(#${clipPathId})로 설정해 앞서 정의한 클립 경로를 참조해요. 예: <g clipPath={`url(#${clipPathId})`}>
<ChartsContainer>
  <g clipPath={`url(#${clipPathId})`}>
    // The plotting to clip in the drawing area.
    <ScatterPlot />
    <LinePlot />
  </g>
  <ChartsClipPath id={clipPathId} /> // Defines the clip path of the drawing area.
</ChartsContainer>

아래 데모에서는 스캐터와 라인 플롯에 대한 클리핑을 켜고 끌 수 있어요. 라인 마커가 클립 영역을 벗어나 축 위에 렌더링되는 방식을 관찰해 보세요.

import * as React from 'react';
import Slider from '@mui/material/Slider';
import Box from '@mui/material/Box';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import useId from '@mui/utils/useId';

import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { ScatterPlot } from '@mui/x-charts/ScatterChart';
import { LinePlot, MarkPlot } from '@mui/x-charts/LineChart';
import { ChartsClipPath } from '@mui/x-charts/ChartsClipPath';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsGrid } from '@mui/x-charts/ChartsGrid';

import { Chance } from 'chance';

const chance = new Chance(42);

const data = Array.from({ length: 100 }, () => ({
  x: chance.floating({ min: -25, max: 25 }),
  y: chance.floating({ min: -25, max: 25 }),
})).map((d, index) => ({ ...d, id: index }));

const minDistance = 10;

export default function LimitOverflow() {
  const [isLimited, setIsLimited] = React.useState(false);
  const [xLimits, setXLimites] = React.useState<number[]>([-20, 20]);

  const id = useId();
  const clipPathId = `${id}-clip-path`;

  const handleChange = (
    event: Event,
    newValue: number | number[],
    activeThumb: number,
  ) => {
    if (!Array.isArray(newValue)) {
      return;
    }

    if (newValue[1] - newValue[0] < minDistance) {
      if (activeThumb === 0) {
        const clamped = Math.min(newValue[0], 100 - minDistance);
        setXLimites([clamped, clamped + minDistance]);
      } else {
        const clamped = Math.max(newValue[1], minDistance);
        setXLimites([clamped - minDistance, clamped]);
      }
    } else {
      setXLimites(newValue as number[]);
    }
  };

  return (
    <Box sx={{ width: '100%', maxWidth: 500 }}>
      <FormControlLabel
        checked={isLimited}
        control={
          <Checkbox onChange={(event) => setIsLimited(event.target.checked)} />
        }
        label="Clip the plot"
        labelPlacement="end"
      />
      <ChartsContainer
        xAxis={[
          {
            label: 'x',
            min: xLimits[0],
            max: xLimits[1],
            data: [-30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25],
            height: 48,
          },
        ]}
        series={[
          { type: 'scatter', data, markerSize: 8 },
          {
            type: 'line',
            data: [10, 13, 12, 5, -6, -3, 4, 20, 18, 17, 12, 11],
            showMark: true,
          },
        ]}
        height={300}
      >
        <ChartsGrid vertical horizontal />
        <g clipPath={`url(#${clipPathId})`}>
          <ScatterPlot />
          <LinePlot />
        </g>
        <ChartsXAxis />
        <ChartsYAxis />
        <MarkPlot />
        {isLimited && <ChartsClipPath id={clipPathId} />}
      </ChartsContainer>
      <Slider
        value={xLimits}
        onChange={handleChange}
        valueLabelDisplay="auto"
        min={-40}
        max={40}
      />
    </Box>
  );
}

:::warning 위 데모는 useId()로 고유한 ID를 생성해요.

const id = useId();
const clipPathId = `${id}-clip-path`;

특히 페이지에 여러 차트가 있을 때 클립 경로에 고유한 ID를 생성하는 것이 중요해요. "my-id" 같은 정적 ID를 할당하면 충돌이 발생해요. :::

축 (Axis)

Axis—Composition에 설명된 것처럼 축을 추가하려면 ChartsXAxis와 ChartsYAxis를 사용해요. 이 컴포넌트들은 컨테이너에 정의된 축 중 어떤 것을 렌더링할지 나타내는 axisId prop을 받아요. axisId가 제공되지 않으면 기본적으로 첫 번째 축을 사용해요.

그리드 (Grid)

컴포넌트에 그리드를 추가하려면 ChartsGrid를 사용해요. 자세한 내용은 Axis—Grid 문서를 참고하세요.

범례 (Legend)

차트에 대한 정보를 담은 범례를 표시하려면 ChartsLegend를 사용해요.

:::warning ChartsLegend는 v8부터 HTML 요소예요. 데이터에 접근하려면 ChartsDataProvider 안에서 렌더링해야 하지만, SVG 요소가 아니므로 ChartsSurface 밖에 있어야 해요.

즉 ChartsContainer 안에서는 사용할 수 없어요. 대신 ChartsDataProvider와 ChartsSurface를 사용해야 해요.

// ✅ Correct
<ChartsDataProvider>
  <ChartsLegend />
  <ChartsSurface>{/* SVG components */}</ChartsSurface>
</ChartsDataProvider>

// ❌ Incorrect
<ChartsContainer>
  <ChartsLegend />
</ChartsContainer>

:::

커스텀 범례에 대한 자세한 내용은 HTML components 문서를 참고하세요.

상호작용 (Interaction)

ChartsAxisHighlight와 ChartsTooltip 같은 상호작용 요소를 아래 데모처럼 추가할 수 있어요.

import { ChartsDataProvider } from '@mui/x-charts/ChartsDataProvider';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { LinePlot, MarkPlot } from '@mui/x-charts/LineChart';
import { ChartsLegend } from '@mui/x-charts/ChartsLegend';
import { ChartsTooltip } from '@mui/x-charts/ChartsTooltip';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsAxisHighlight } from '@mui/x-charts/ChartsAxisHighlight';
import Box from '@mui/material/Box';

const pData = [2400, 1398, 9800, 3908, 4800, 3800, 4300];
const xLabels = [
  'Page A',
  'Page B',
  'Page C',
  'Page D',
  'Page E',
  'Page F',
  'Page G',
];

export default function LegendTooltipComposition() {
  return (
    <Box
      sx={{
        width: '100%',
        overflow: 'auto',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
      }}
    >
      <ChartsDataProvider
        height={300}
        series={[{ type: 'line', data: pData, label: 'Sales Data', showMark: true }]}
        xAxis={[{ scaleType: 'point', data: xLabels }]}
        yAxis={[{ width: 50 }]}
        margin={{ top: 30, right: 30, bottom: 20, left: 20 }}
      >
        <ChartsLegend />
        <ChartsTooltip />
        <ChartsSurface>
          <ChartsXAxis />
          <ChartsYAxis />
          <LinePlot />
          <MarkPlot />
          <ChartsAxisHighlight x="line" />
        </ChartsSurface>
      </ChartsDataProvider>
    </Box>
  );
}

:::info 기본적으로 ChartsContainer는 마우스 이벤트를 수신해 차트 위에서 마우스가 있는 위치를 추적해요.

축 하이라이트나 툴팁을 사용하지 않는다면 disableAxisListener prop으로 이 기능을 비활성화하는 것을 고려해 보세요.

<ChartsContainer {...} disableAxisListener>

:::

포커스 표시기 (Focus indicator)

키보드 내비게이션은 기본적으로 활성화되어 있지만, 포커스 하이라이트는 차트를 컴포즈할 때 자동으로 포함되지 않는 전용 SVG 요소로 렌더링돼요. 포커스된 항목을 보이게 하려면 시리즈 타입에 맞는 포커스 컴포넌트(예: FocusedBar, FocusedLineMark, FocusedScatterMark)를 SVG 안에 추가하세요.

<ChartsContainer>
  <BarPlot />
  <FocusedBar />
</ChartsContainer>

시리즈 타입별 포커스 컴포넌트의 전체 목록은 Accessibility—Composition 문서를 참고하세요.

레이어링 (Layering)

ChartsLayerContainer, ChartsSvgLayer, ChartsWebGLLayer를 사용해 동일한 좌표계를 공유하는 여러 레이어의 요소를 만들 수 있어요. 이는 SVG와 WebGL 요소를 번갈아 배치할 때 깊이 순서를 관리하는 데 유용해요.

아래 예시에서는 세 개의 레이어를 만들어요:

  1. 차트의 그리드를 표시하는 SVG 레이어;
  2. CandlestickPlot으로 렌더링하는 WebGL 레이어;
  3. 축과 크로스헤어를 렌더링하는 SVG 레이어
import * as React from 'react';
import { ChartsDataProviderPremium } from '@mui/x-charts-premium/ChartsDataProviderPremium';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsGrid } from '@mui/x-charts/ChartsGrid';
import { ChartsTooltip } from '@mui/x-charts/ChartsTooltip';
import { ChartsAxisHighlight } from '@mui/x-charts/ChartsAxisHighlight';
import { ChartsWrapper } from '@mui/x-charts/ChartsWrapper';
import { ChartsLayerContainer } from '@mui/x-charts/ChartsLayerContainer';
import { ChartsSvgLayer } from '@mui/x-charts/ChartsSvgLayer';
import { ChartsWebGLLayer } from '@mui/x-charts-premium/ChartsWebGLLayer';
import { CandlestickPlot as CandlestickPlot } from '@mui/x-charts-premium/CandlestickChart';
import { OHLCValueType } from '@mui/x-charts-premium/models';

const ohlcData: OHLCValueType[] = [
  [100, 110, 95, 105],
  [105, 115, 100, 112],
  [112, 120, 108, 118],
  [118, 125, 115, 120],
  [120, 128, 118, 125],
  [125, 130, 120, 122],
  [122, 128, 118, 126],
  [126, 135, 124, 132],
  [132, 140, 130, 138],
  [138, 145, 135, 135],
  [135, 148, 138, 145],
  [145, 152, 142, 148],
  [148, 155, 145, 150],
  [150, 158, 148, 152],
  [152, 162, 151, 151],
  [151, 165, 151, 157],
  [157, 168, 153, 153],
  [153, 160, 151, 152],
  [152, 155, 150, 154],
  [154, 158, 153, 157],
];

const xAxisData = ohlcData.map((_, index) => `Day ${index + 1}`);

export default function Layering() {
  return (
    <ChartsDataProviderPremium
      height={600}
      series={[
        {
          type: 'ohlc',
          data: ohlcData,
          label: 'Stock Price',
        },
      ]}
      xAxis={[{ scaleType: 'band', data: xAxisData }]}
      yAxis={[{ label: 'Price' }]}
    >
      <ChartsWrapper>
        <ChartsLayerContainer>
          <ChartsSvgLayer>
            <ChartsGrid horizontal />
          </ChartsSvgLayer>
          <ChartsWebGLLayer>
            <CandlestickPlot />
          </ChartsWebGLLayer>
          <ChartsSvgLayer>
            <ChartsXAxis />
            <ChartsYAxis />
            <ChartsAxisHighlight x="line" y="line" />
          </ChartsSvgLayer>
          <ChartsTooltip />
        </ChartsLayerContainer>
      </ChartsWrapper>
    </ChartsDataProviderPremium>
  );
}

모든 레이어는 절대 위치로 배치되므로 정의된 순서대로 서로 위에 쌓여요.

예시 (Examples)

종 모양 곡선 (Bell curve)

이 예시는 스캐터와 라인 플롯을 결합해 데이터 포인트 위에 정규 분포 곡선(종 모양 곡선으로 알려짐)을 겹쳐 그리는 방법을 보여줘요. 종 모양 곡선은 데이터의 평균과 표준편차를 기반으로 계산돼요.

import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { ScatterPlot } from '@mui/x-charts/ScatterChart';
import { LinePlot } from '@mui/x-charts/LineChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsReferenceLine } from '@mui/x-charts/ChartsReferenceLine';
import { internetUsageByCountry } from '../dataset/internetUsageByCountry';

const data = Object.values(internetUsageByCountry);

function calculateStatistics(values: number[]) {
  const n = values.length;
  const mean = values.reduce((sum, val) => sum + val, 0) / n;
  const variance = values.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / n;
  const stdDev = Math.sqrt(variance);
  return { mean, stdDev };
}

function normalDistribution(x: number, mean: number, stdDev: number) {
  const exponent = -Math.pow(x - mean, 2) / (2 * Math.pow(stdDev, 2));
  return (1 / (stdDev * Math.sqrt(2 * Math.PI))) * Math.exp(exponent);
}

export default function BellCurveOverlay() {
  const { mean, stdDev } = calculateStatistics(data);

  // Generate bell curve data
  const min = Math.min(...data);
  const max = Math.max(...data);
  const range = max - min;
  const bellCurveData: number[] = [];
  const xValues: number[] = [];
  const numPoints = 100;

  for (let i = 0; i <= numPoints; i += 1) {
    const x = min - range * 0.1 + ((max - min + range * 0.2) * i) / numPoints;
    xValues.push(x);
    bellCurveData.push(normalDistribution(x, mean, stdDev));
  }

  // Stack points that are close together
  const binWidth = range / 70; // Adjust this to control stacking sensitivity
  const sortedData = [...data].sort((a, b) => a - b);
  const bins: Map<number, number[]> = new Map();

  // Group values into bins
  sortedData.forEach((value) => {
    const binIndex = Math.round(value / binWidth);
    if (!bins.has(binIndex)) {
      bins.set(binIndex, []);
    }
    bins.get(binIndex)!.push(value);
  });

  // Create scatter data with stacked y-positions
  const scatterData: Array<{ x: number; y: number; id: number }> = [];
  let globalIndex = 0;
  const baseY = 0.0005;
  const stackHeight = 0.001;

  bins.forEach((values) => {
    values.forEach((value, stackIndex) => {
      scatterData.push({
        x: value,
        y: baseY + stackIndex * stackHeight,
        id: globalIndex,
      });
      globalIndex += 1;
    });
  });

  return (
    <div style={{ width: '100%' }}>
      <ChartsContainer
        series={[
          {
            type: 'scatter',
            data: scatterData,
            label: 'Data points',
            id: 'scatter',
            markerSize: 4,
          },
          {
            type: 'line',
            data: bellCurveData,
            label: 'Normal distribution',
            id: 'bell-curve',
            color: '#f97316',
            curve: 'natural',
          },
        ]}
        xAxis={[
          {
            data: xValues,
            min: min - range * 0.1,
            max: max + range * 0.1,
            label: 'Individuals using the Internet (% of population)',
            valueFormatter: (value: string) => `${value}%`,
          },
        ]}
        yAxis={[
          {
            position: 'none',
          },
        ]}
        height={400}
      >
        <ScatterPlot />
        <LinePlot />
        <ChartsReferenceLine
          x={mean}
          label="Mean"
          lineStyle={{ strokeWidth: 2 }}
          labelStyle={{ fontWeight: 'bold' }}
          labelAlign="start"
          spacing={{ y: 40 }}
        />
        <ChartsReferenceLine
          x={mean - stdDev}
          label="-1σ"
          lineStyle={{ strokeWidth: 1.5, strokeDasharray: '5 5' }}
          labelAlign="start"
          spacing={{ y: 40 }}
        />
        <ChartsReferenceLine
          x={mean + stdDev}
          label="+1σ"
          lineStyle={{ strokeWidth: 1.5, strokeDasharray: '5 5' }}
          labelAlign="start"
          spacing={{ y: 40 }}
        />
        <ChartsXAxis />
        <ChartsYAxis />
      </ChartsContainer>
    </div>
  );
}

더 알아보기 (Learn more)