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

Charts – 라인 차트

원문 보기 위키 갱신

Charts – 라인 차트 (Lines)

라인 차트로 시간에 따른 추세를 보여주고, 시리즈를 비교하며, 연속된 데이터의 변화를 강조할 수 있어요.

출처: MUI X documentation

본문

개요 (Overview)

라인 차트는 시간이나 측정 스케일 같은 연속 축 위에서 값이 어떻게 변하는지 보여주고 싶을 때 잘 어울려요. 추세, 패턴, 변동을 강조하기 때문에 관계를 탐색하거나, 주기를 발견하거나, 시간에 따른 성과를 추적하는 데 유용해요. 각 라인은 보통 하나의 시리즈를 나타내므로, 여러 변수나 그룹을 한눈에 비교할 수 있어요.

import * as React from 'react';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import { alpha, useTheme } from '@mui/material/styles';
import { ChartsDataProviderPro } from '@mui/x-charts-pro/ChartsDataProviderPro';
import { ChartsSurface } from '@mui/x-charts-pro/ChartsSurface';
import { LinePlot } from '@mui/x-charts-pro/LineChart';
import { ChartsXAxis } from '@mui/x-charts-pro/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts-pro/ChartsYAxis';
import { useDrawingArea, useXScale } from '@mui/x-charts-pro/hooks';
import { ChartsTooltip } from '@mui/x-charts-pro/ChartsTooltip';
import { ChartsGrid } from '@mui/x-charts-pro/ChartsGrid';
import { ChartsZoomSlider } from '@mui/x-charts-pro/ChartsZoomSlider';
import { ChartsClipPath } from '@mui/x-charts-pro/ChartsClipPath';
import { ChartsAxisHighlight } from '@mui/x-charts/ChartsAxisHighlight';
import { ChartsLegend } from '@mui/x-charts-pro/ChartsLegend';
import { usaUnemploymentAndGdp } from '../dataset/usaUnemploymentAndGdp';

type RecessionPeriod = {
  start: Date;
  end: Date;
  label: string;
};

const recessions = [
  {
    start: new Date('2001-03-01'),
    end: new Date('2001-11-01'),
    label: 'Early 2000s',
  },
  {
    start: new Date('2007-12-01'),
    end: new Date('2009-06-01'),
    label: 'Great Recession',
  },
  { start: new Date('2020-02-01'), end: new Date('2020-04-01'), label: 'COVID-19' },
];

function RecessionBands({ periods }: { periods: RecessionPeriod[] }) {
  const { top, left, width, height } = useDrawingArea();
  const xScale = useXScale();
  const theme = useTheme();
  const labelFill = alpha(theme.palette.text.primary, 0.7);

  return (
    <g>
      {periods.map((p, index) => {
        const xStart = xScale(p.start.getTime());
        const xEnd = xScale(p.end.getTime());

        if (xStart === undefined || xEnd === undefined) {
          return null;
        }

        // Stick to the left of the drawing area boundaries
        let textX: number;
        if (xStart >= left && xStart <= left + width) {
          textX = xStart;
        } else if (xEnd >= left && xEnd <= left + width) {
          textX = left;
        } else {
          return null;
        }

        return (
          <React.Fragment key={index}>
            <rect
              x={textX}
              y={top}
              width={Math.min(xEnd, left + width) - textX}
              height={height}
              fill="grey"
              opacity={0.2}
            />
            <text
              x={textX}
              y={top - 5}
              textAnchor="start"
              dominantBaseline="auto"
              fill={labelFill}
              fontSize="0.8rem"
              fontWeight={500}
              pointerEvents="none"
            >
              {p.label}
            </text>
          </React.Fragment>
        );
      })}
    </g>
  );
}

export default function LineOverview() {
  const clipPathId = React.useId();
  return (
    <Box sx={{ width: '100%' }}>
      <Typography sx={{ textAlign: 'center' }}>
        US unemployment rate comparison with GDP per capita
      </Typography>
      <ChartsDataProviderPro
        height={300}
        dataset={usaUnemploymentAndGdp}
        series={[
          {
            type: 'line',
            id: 'unemployment',
            dataKey: 'unemploymentRate',
            label: 'Unemployment rate',
            color: '#af3838',
            yAxisId: 'unemployment-axis',
            valueFormatter: (value) => (value == null ? '' : `${value.toFixed(1)}%`),
          },
          {
            type: 'line',
            dataKey: 'gdpPerCapita',
            label: 'GDP per capita',
            color: '#4caf50',
            yAxisId: 'gdp-axis',
            connectNulls: true,
            valueFormatter: (value) =>
              value == null ? '' : `${(value / 1000).toFixed(1)}k`,
          },
        ]}
        xAxis={[
          {
            scaleType: 'time',
            dataKey: 'date',
            tickNumber: 4,
            valueFormatter: (date, context) => {
              if (context.location !== 'tick') {
                return date.toLocaleDateString('en-US', {
                  year: 'numeric',
                  month: 'short',
                });
              }
              return date.getMonth() === 0
                ? date.toLocaleDateString('en-US', {
                    year: 'numeric',
                  })
                : date.toLocaleDateString('en-US', {
                    month: 'short',
                  });
            },
            zoom: {
              slider: { enabled: true },
            },
          },
        ]}
        yAxis={[
          {
            id: 'unemployment-axis',
            scaleType: 'linear',
            valueFormatter: (value) => `${value}%`,
            width: 55,
            position: 'left',
          },
          {
            id: 'gdp-axis',
            scaleType: 'linear',
            width: 50,
            position: 'right',
            valueFormatter: (value) => `${(value / 1000).toLocaleString()}k`,
          },
        ]}
      >
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 1 }}>
          <ChartsLegend />
        </Box>
        <ChartsSurface>
          <ChartsClipPath id={clipPathId} />
          <RecessionBands periods={recessions} />
          <ChartsGrid horizontal />
          <g clipPath={`url(#${clipPathId})`}>
            <LinePlot />
          </g>
          <ChartsXAxis />
          <ChartsYAxis axisId="unemployment-axis" label="Unemployment Rate" />
          <ChartsYAxis axisId="gdp-axis" label="GDP per capita in US$" />
          <ChartsAxisHighlight x="line" />
          <ChartsZoomSlider />
        </ChartsSurface>
        <ChartsTooltip />
      </ChartsDataProviderPro>
      <Typography
        variant="caption"
        component="p"
        sx={{ color: 'text.secondary', textAlign: 'left', pt: 1 }}
      >
        Source: FRED
      </Typography>
    </Box>
  );
}

기초 (Basics)

데이터 형식 (Data format)

라인 차트 시리즈는 숫자 배열인 data 속성을 포함해야 해요. 이 배열이 y값을 담고 있어요.

x값을 설정하려면 xAxis 설정에 data를 전달해요. 축은 어떤 scaleType이든 사용할 수 있고, 그 data는 시리즈와 길이가 같아야 해요.

xAxis prop을 완전히 생략하면 LineChart가 scaleType='point'인 기본 x축을 제공해요. 그 data는 가장 긴 시리즈와 길이가 맞는 [0, 1, 2, …]이므로, 각 y값은 시리즈 data 배열의 인덱스와 짝을 이뤄요.

import { LineChart } from '@mui/x-charts/LineChart';

export default function BasicLineChart() {
  return (
    <LineChart
      xAxis={[{ data: [1, 2, 3, 5, 8, 10] }]}
      series={[
        {
          data: [2, 5.5, 2, 8.5, 1.5, 5],
        },
      ]}
      height={300}
    />
  );
}

데이터셋 사용하기 (Using a dataset)

데이터가 객체 배열로 저장되어 있다면 dataset 헬퍼 prop을 사용할 수 있어요. dataset={[{x: 1, y: 32}, {x: 2, y: 41}, ...]} 같은 객체 배열을 받아들여요.

시리즈와 축을 정의할 때 dataKey 속성을 사용해 이 데이터를 재사용할 수 있어요. 예를 들어 xAxis={[{ dataKey: 'x' }]} 또는 series={[{ dataKey: 'y' }]}처럼요.

아래 데모는 에너지원별 세계 전력 생산량의 변화를 그려요.

import { LineChart } from '@mui/x-charts/LineChart';
import {
  worldElectricityProduction,
  keyToLabel,
  colors,
} from '../dataset/worldElectricityProduction';

const stackStrategy = {
  stack: 'total',
  area: true,
  stackOffset: 'none', // To stack 0 on top of others
} as const;

const customize = {
  height: 350,
  hideLegend: true,
};

export default function LineDataset() {
  return (
    <LineChart
      xAxis={[
        { dataKey: 'year', valueFormatter: (value: number) => value.toString() },
      ]}
      yAxis={[{ width: 50 }]}
      series={Object.keys(keyToLabel).map((key) => ({
        dataKey: key,
        label: keyToLabel[key],
        color: colors[key],
        ...stackStrategy,
      }))}
      dataset={worldElectricityProduction}
      {...customize}
    />
  );
}

영역 (Area)

시리즈 area 속성을 true로 설정하면 라인 아래 영역을 채워요.

import { LineChart } from '@mui/x-charts/LineChart';

export default function BasicArea() {
  return (
    <LineChart
      xAxis={[{ data: [1, 2, 3, 5, 8, 10] }]}
      series={[
        {
          data: [2, 5.5, 2, 8.5, 1.5, 5],
          area: true,
        },
      ]}
      height={300}
    />
  );
}

마크 (Marks)

모든 값에 마크를 표시하려면 showMark: true를 추가해요.

시리즈의 첫 번째(또는 마지막) 값에만 마크를 표시하려면 'start' 또는 'end' 값을 받을 수도 있어요.

마크를 수정하려면 shape 속성을 사용해요. 'circle', 'square', 'diamond', 'cross', 'star', 'triangle', 'wye' 7가지 모양을 받아들여요.

:::info 'start' | 'end' 옵션은 일반 마크 대신 하이라이트 마크를 렌더링해요. 그래서 포인터가 값을 강조하는 동안, start/end 마크는 강조된 마크로 교체돼요. :::

import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import { LineChart } from '@mui/x-charts/LineChart';
import { dataset } from '../dataset/weather';

type Shape = 'circle' | 'square' | 'diamond' | 'cross' | 'star' | 'triangle' | 'wye';

const marksMapping = {
  true: true,
  false: false,
  start: 'start',
  end: 'end',
  '({index})=>index%2===0': ({ index }: { index: number }) => index % 2 === 0,
} as const;

const marksOptions: (keyof typeof marksMapping)[] = [
  'true',
  'false',
  'start',
  'end',
  '({index})=>index%2===0',
];

const shapes: Shape[] = [
  'circle',
  'square',
  'diamond',
  'cross',
  'star',
  'triangle',
  'wye',
];

export default function LineMarkShape() {
  const [marks, setMarks] = React.useState<keyof typeof marksMapping>('true');
  const [shape, setShape] = React.useState<Shape>('circle');

  return (
    <Stack
      direction={{ xs: 'column', md: 'row' }}
      spacing={1}
      sx={{ width: '100%', padding: 2 }}
    >
      <Stack direction={{ xs: 'row', md: 'column' }} spacing={1}>
        <TextField
          select
          label="marks"
          value={marks}
          onChange={(event) =>
            setMarks(event.target.value as keyof typeof marksMapping)
          }
          sx={{ minWidth: 150 }}
        >
          {marksOptions.map((option) => (
            <MenuItem key={option} value={option}>
              {option}
            </MenuItem>
          ))}
        </TextField>
        <TextField
          select
          label="shape"
          value={shape}
          onChange={(event) => setShape(event.target.value as Shape)}
          sx={{ minWidth: 150 }}
        >
          {shapes.map((option) => (
            <MenuItem key={option} value={option}>
              {option}
            </MenuItem>
          ))}
        </TextField>
      </Stack>
      <Box sx={{ flexGrow: 1 }}>
        <LineChart
          height={250}
          dataset={dataset}
          series={[
            {
              dataKey: 'london',
              label: 'London precipitation (mm)',
              curve: 'natural',
              showMark: marksMapping[marks],
              shape,
            },
          ]}
          xAxis={[{ scaleType: 'point', dataKey: 'month' }]}
          grid={{ vertical: true, horizontal: true }}
        />
      </Box>
    </Stack>
  );
}

로그 스케일 (Log scale)

로그 스케일의 y축은 0을 지나는 라인을 그릴 수 없고, 0의 로그는 정의되지 않으므로 영역 차트도 그릴 수 없어요.

해결 방법은 Axis—Symlog scale을 참고해요.

스태킹 (Stacking)

stack 문자열 속성을 사용해 라인 시리즈들을 스택으로 묶을 수 있어요. 같은 stack 값을 공유하는 시리즈들은 서로 위에 쌓여요.

stackOffset와 stackOrder 속성을 사용해 시리즈가 쌓이는 방식을 정의할 수 있어요. 기본적으로는 정의한 순서대로 쌓이며, 양수 값은 0 위로, 음수 값은 0 아래로 쌓여요.

자세한 내용은 Stacking을 참고해요.

import { LineChart } from '@mui/x-charts/LineChart';
import { dataset } from '../dataset/gdpPerCapitaEvolution';

export default function StackedAreas() {
  return (
    <div style={{ width: '100%' }}>
      <LineChart
        dataset={dataset}
        xAxis={[
          {
            id: 'Years',
            dataKey: 'date',
            scaleType: 'time',
            valueFormatter: (date) => date.getFullYear().toString(),
          },
        ]}
        yAxis={[{ width: 70 }]}
        series={[
          {
            id: 'France',
            label: 'French GDP per capita',
            dataKey: 'fr',
            stack: 'total',
            area: true,
          },
          {
            id: 'Germany',
            label: 'German GDP per capita',
            dataKey: 'dl',
            stack: 'total',
            area: true,
          },
          {
            id: 'United Kingdom',
            label: 'UK GDP per capita',
            dataKey: 'gb',
            stack: 'total',
            area: true,
          },
        ]}
        height={300}
      />
    </div>
  );
}

축 도메인 (Axis domain)

기본적으로 라인 차트의 x축 도메인 한계는 'strict'로 설정되어, 축 범위가 데이터 범위와 정확히 일치해요. 다른 차트 유형은 축 한계를 사람이 읽기 좋은 값으로 반올림해요(예: 2에서 195까지의 데이터가 0에서 200까지의 값으로 표시). 이 동작은 축 속성 domainLimit으로 수정할 수 있어요.

import * as React from 'react';
import Stack from '@mui/material/Stack';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import { LineChart } from '@mui/x-charts/LineChart';
import { dataset } from '../dataset/gdpPerCapitaEvolution';

export default function LineDefaultDomainLimit() {
  const [niceDomainLimit, setNiceDomainLimit] = React.useState(false);

  return (
    <Stack sx={{ alignItems: 'center' }}>
      <FormControlLabel
        checked={niceDomainLimit}
        control={
          <Checkbox onChange={(event) => setNiceDomainLimit(event.target.checked)} />
        }
        label="Nice domain limit"
        labelPlacement="end"
      />
      <div style={{ width: '100%', maxWidth: 450 }}>
        <LineChart
          dataset={dataset.slice(2, dataset.length)}
          xAxis={[
            {
              id: 'Years',
              dataKey: 'date',
              scaleType: 'time',
              valueFormatter: (date) => date.getFullYear().toString(),
              domainLimit: niceDomainLimit ? 'nice' : undefined,
            },
          ]}
          yAxis={[{ width: 70 }]}
          series={[
            {
              id: 'France',
              label: 'French GDP per capita',
              dataKey: 'fr',
              stack: 'total',
              area: true,
            },
            {
              id: 'Germany',
              label: 'German GDP per capita',
              dataKey: 'dl',
              stack: 'total',
              area: true,
            },
            {
              id: 'United Kingdom',
              label: 'UK GDP per capita',
              dataKey: 'gb',
              stack: 'total',
              area: true,
            },
          ]}
          height={300}
        />
      </div>
    </Stack>
  );
}

부분 데이터 (Partial data)

누락된 지점 건너뛰기 (Skip missing points)

라인 시리즈는 축보다 적은 데이터 포인트를 가질 수 있어요. 부분 데이터가 있거나 시리즈가 서로 다른 지점에서 시작할 때는 null 값을 사용해요.

기본적으로 툴팁은 호버된 위치에 값이 없는 시리즈를 생략해요. 누락된 값에 대한 툴팁을 표시하려면 valueFormatter를 사용해 값이 null 또는 undefined일 때 문자열을 반환하게 해요.

import { LineChart } from '@mui/x-charts/LineChart';

export default function DifferentLength() {
  return (
    <LineChart
      xAxis={[{ data: [1, 2, 3, 5, 8, 10, 12, 15, 16] }]}
      series={[
        {
          data: [2, 5.5, 2, 8.5, 1.5, 5],
          valueFormatter: (value) => (value == null ? 'NaN' : value.toString()),
        },
        {
          data: [null, null, null, null, 5.5, 2, 8.5, 1.5, 5],
        },
        {
          data: [7, 8, 5, 4, null, null, 2, 5.5, 1],
          valueFormatter: (value) => (value == null ? '?' : value.toString()),
        },
      ]}
      height={200}
      margin={{ bottom: 10 }}
    />
  );
}

:::info 시리즈 data 배열이 축 data보다 짧으면, 시리즈 길이 밖의 값은 null이 아니라 undefined예요.

아래 코드는 x가 2에서 4 사이일 때 라인을 그려요.

  • x<2이면 값이 null이라 라인이 그려지지 않아요.
  • x>4이면 값이 undefined라 라인이 그려지지 않아요.
<LineChart
  series={[{ data: [null, null, 10, 11, 12] }]}
  xAxis={[{ data: [0, 1, 2, 3, 4, 5, 6] }]}
/>

:::

누락된 지점 연결하기 (Connect missing points)

라인 시리즈의 connectNulls 속성을 설정하면 값이 null인 지점을 가로질러 곡선을 이어요. 이것은 사이에 null 값 간격이 있는 두 세그먼트를 연결해요. 곡선은 첫 번째 non-null 지점 이전이나 마지막 지점 이후로는 외삽되지 않아요.

import * as React from 'react';
import Stack from '@mui/material/Stack';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import { LineChart } from '@mui/x-charts/LineChart';

export default function ConnectNulls() {
  const [connectNulls, setConnectNulls] = React.useState(true);

  return (
    <Stack sx={{ width: '100%' }}>
      <FormControlLabel
        checked={connectNulls}
        control={
          <Checkbox onChange={(event) => setConnectNulls(event.target.checked)} />
        }
        label="connectNulls"
        labelPlacement="end"
      />
      <LineChart
        xAxis={[{ data: [1, 2, 3, 5, 8, 10, 12, 15, 16, 18, 20] }]}
        series={[
          {
            data: [2, 5, 6.5, 3, 8, 10, 9.5, 2.5, 6, 10, 8],
          },
          {
            data: [null, null, 5.5, 2, null, null, 8.5, 1.5, 5],
            connectNulls,
            area: true,
          },
        ]}
        height={200}
        margin={{ bottom: 10 }}
        skipAnimation
      />
    </Stack>
  );
}

클릭 이벤트 (Click event)

라인 차트는 여러 클릭 핸들러를 제공해요:

  • 특정 영역이 클릭되면 onAreaClick
  • 특정 라인이 클릭되면 onLineClick
  • 특정 마크가 클릭되면 onMarkClick
  • 차트 배경이 클릭되면 onAxisClick

각 핸들러는 같은 시그니처를 받아요:

const clickHandler = (
  event, // The mouse event.
  params, // An object that identifies the clicked elements.
) => {};
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 UndoOutlinedIcon from '@mui/icons-material/UndoOutlined';

import { LineChart } from '@mui/x-charts/LineChart';

import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
import { ChartsAxisData, LineItemIdentifier } from '@mui/x-charts/models';

const lineChartsParams = {
  series: [
    {
      id: 'series-1',
      data: [3, 4, 1, 6, 5],
      label: 'A',
      area: true,
      stack: 'total',
      highlightScope: {
        highlight: 'item',
      },
    },
    {
      id: 'series-2',
      data: [4, 3, 1, 5, 8],
      label: 'B',
      area: true,
      stack: 'total',
      highlightScope: {
        highlight: 'item',
      },
    },
    {
      id: 'series-3',
      data: [4, 2, 5, 4, 1],
      label: 'C',
      area: true,
      stack: 'total',
      highlightScope: {
        highlight: 'item',
      },
    },
  ],
  xAxis: [{ data: [0, 3, 6, 9, 12], scaleType: 'linear', id: 'axis1' }],
  height: 400,
} as const;

export default function LineClick() {
  const [itemData, setItemData] = React.useState<LineItemIdentifier>();
  const [axisData, setAxisData] = React.useState<ChartsAxisData | null>();

  return (
    <Stack
      direction={{ xs: 'column', md: 'row' }}
      spacing={{ xs: 0, md: 4 }}
      sx={{ width: '100%' }}
    >
      <Box sx={{ flexGrow: 1 }}>
        <LineChart
          {...lineChartsParams}
          onAreaClick={(event, d) => setItemData(d)}
          onMarkClick={(event, d) => setItemData(d)}
          onLineClick={(event, d) => setItemData(d)}
          onAxisClick={(event, d) => setAxisData(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={() => {
              setItemData(undefined);
              setAxisData(null);
            }}
          >
            <UndoOutlinedIcon fontSize="small" />
          </IconButton>
        </Box>
        <HighlightedCode
          code={`// Data from item click
${itemData ? JSON.stringify(itemData, null, 2) : '// The data will appear here'}

// Data from axis click
${axisData ? JSON.stringify(axisData, null, 2) : '// The data will appear here'}
`}
          language="json"
          copyButtonHidden
        />
      </Stack>
    </Stack>
  );
}

:::info event는 onAxisClick과 나머지에서 약간 달라요:

  • onAxisClick의 경우, SVG 요소의 네이티브 마우스 이벤트예요.
  • 나머지의 경우, 영역·라인·마크 컴포넌트의 React 합성 마우스 이벤트예요.

:::

Composition

커스텀 컴포넌트를 구성하고 있다면 아래와 같이 이 클릭 이벤트를 받을 수 있어요. 막대와 라인 시리즈를 섞으면 onAxisClick이 둘 다에 대해 실행된다는 점을 주의해요.

<ChartsContainer onAxisClick={onAxisClick}>
  {/* ... */}
  <LinePlot onItemClick={onLineClick} />
  <AreaPlot onItemClick={onAreaClick} />
</ChartsContainer>

포인터 상호작용 (Pointer interaction) 🧪

:::warning 이 기능은 프리뷰(preview) 상태예요. 프로덕션에서 사용할 수 있지만, API·시각적 요소·동작이 향후 마이너 또는 패치 릴리스에서 변경될 수 있어요. :::

기본적으로 라인과 영역 시리즈는 포인터가 SVG 요소(라인 스트로크 또는 영역 채움) 바로 위에 호버할 때 강조돼요. 이 때문에 얇은 라인과 상호작용하기 어려울 수 있어요.

experimentalFeatures.enablePositionBasedPointerInteraction를 활성화하면 커서에 가장 가까운 시리즈를 결정하는 포인터 위치 기반 감지로 전환돼요. 영역 시리즈의 경우 포인터가 채워진 영역 안에 있는지 감지해요. 라인 시리즈(영역 없음)의 경우 포인터의 세로 위치에 가장 가까운 곡선을 가진 시리즈를 찾아요.

이것은 렌더링된 라인과 동일한 곡선 보간(예: monotoneX, catmullRom)을 사용하므로, 히트 감지가 시각적 모양과 일치해요.

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

const data = {
  xAxis: [{ data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }],
  series: [
    {
      data: [5, 8, 3, 7, 2, 9, 4, 6, 1, 5, 3],
      label: 'Series C',
      area: true,
      highlightScope: { highlight: 'series', fade: 'global' },
    },
    {
      data: [2, 5.5, 2, 8.5, 1.5, 5, 1, 4, 3, 8, 2],
      label: 'Series A',
      highlightScope: { highlight: 'series', fade: 'global' },
    },
    {
      data: [8, 2, 5, 1, 7, 3, 9, 2, 6, 3, 7],
      label: 'Series B',
      highlightScope: { highlight: 'series', fade: 'global' },
    },
  ],
} as const;

export default function LinePointerInteraction() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <LineChart
        {...data}
        experimentalFeatures={{ enablePositionBasedPointerInteraction: true }}
      />
    </Box>
  );
}

하이라이트 (Highlight)

라인 하이라이트는 라인과 마크 위에 마크를 표시해요. showMark: false로 설정했어도 마찬가지예요.

이 동작은 disableHighlight 시리즈 속성이나 라인 차트의 disableLineItemHighlight prop으로 끌 수 있어요.

스타일링 (Styling)

그리드 (Grid)

grid prop으로 차트 배경에 그리드를 추가할 수 있어요.

자세한 내용은 Axis—Grid를 참고해요.

import { LineChart } from '@mui/x-charts/LineChart';
import { XAxis } from '@mui/x-charts/models';
import {
  dateAxisFormatter,
  percentageFormatter,
  usUnemploymentRate,
} from '../dataset/usUnemploymentRate';

const xAxis: XAxis<'time'>[] = [
  {
    dataKey: 'date',
    scaleType: 'time',
    valueFormatter: dateAxisFormatter,
  },
];
const yAxis = [
  {
    valueFormatter: percentageFormatter,
  },
];
const series = [
  {
    dataKey: 'rate',
    valueFormatter: percentageFormatter,
  },
];
export default function GridDemo() {
  return (
    <LineChart
      dataset={usUnemploymentRate}
      xAxis={xAxis}
      yAxis={yAxis}
      series={series}
      height={300}
      grid={{ vertical: true, horizontal: true }}
    />
  );
}

컬러 스케일 (Color scale)

다른 차트처럼 시리즈 색상을 직접 또는 컬러 팔레트로 수정할 수 있어요.

또한 축의 colorMap을 사용해 색상을 수정할 수도 있어요. colorMap은 값을 색상에 매핑해요. 라인 차트는 다음의 우선순위 순서로 사용해요:

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

colorMap 속성은 Styling—Value-based colors를 참고해요.

import * as React from 'react';
import { LineChart } from '@mui/x-charts/LineChart';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';

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

  return (
    <Stack direction="column" spacing={1} sx={{ width: '100%', maxWidth: 600 }}>
      <Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap' }}>
        <TextField
          select
          sx={{ minWidth: 150 }}
          label="x-axis colorMap"
          value={colorX}
          onChange={(event) =>
            setColorX(event.target.value as 'None' | 'piecewise' | 'continuous')
          }
        >
          <MenuItem value="None">None</MenuItem>
          <MenuItem value="piecewise">piecewise</MenuItem>
          <MenuItem value="continuous">continuous</MenuItem>
        </TextField>
        <TextField
          select
          sx={{ minWidth: 150 }}
          label="y-axis colorMap"
          value={colorY}
          onChange={(event) =>
            setColorY(event.target.value as 'None' | 'piecewise' | 'continuous')
          }
        >
          <MenuItem value="None">None</MenuItem>
          <MenuItem value="piecewise">piecewise</MenuItem>
          <MenuItem value="continuous">continuous</MenuItem>
        </TextField>
        <FormControlLabel
          checked={colorArea}
          control={
            <Checkbox onChange={(event) => setColorArea(event.target.checked)} />
          }
          label="Show chart area"
          labelPlacement="end"
        />
      </Stack>
      <LineChart
        height={300}
        grid={{ horizontal: true }}
        series={[
          {
            data: [-2, -9, 12, 11, 6, -4],
            area: colorArea,
            showMark: true,
          },
        ]}
        yAxis={[
          {
            colorMap:
              (colorY === 'continuous' && {
                type: 'continuous',
                min: -10,
                max: 10,
                color: ['red', 'green'],
              }) ||
              (colorY === 'piecewise' && {
                type: 'piecewise',
                thresholds: [0, 10],
                colors: ['red', 'green', 'blue'],
              }) ||
              undefined,
          },
        ]}
        xAxis={[
          {
            scaleType: 'time',
            data: [
              new Date(2019, 0, 1),
              new Date(2020, 0, 1),
              new Date(2021, 0, 1),
              new Date(2022, 0, 1),
              new Date(2023, 0, 1),
              new Date(2024, 0, 1),
            ],
            valueFormatter: (value) => value.getFullYear().toString(),
            colorMap:
              (colorX === 'continuous' && {
                type: 'continuous',
                min: new Date(2019, 1, 1),
                max: new Date(2024, 1, 1),
                color: ['green', 'orange'],
              }) ||
              (colorX === 'piecewise' && {
                type: 'piecewise',
                thresholds: [new Date(2021, 1, 1), new Date(2023, 1, 1)],
                colors: ['blue', 'red', 'blue'],
              }) ||
              undefined,
          },
        ]}
      />
      <HighlightedCode
        code={[
          `<LineChart`,
          '  /* ... */',
          `  series={[{data: [-2, -9, 12, 11, 6, -4], area: ${colorArea}}]}`,
          // ColorX
          ...(colorX === 'None' ? ['  xAxis={[{}]}'] : []),
          ...(colorX === 'continuous'
            ? [
                '  xAxis={[{',
                `    colorMap: {`,
                `      type: 'continuous',`,
                `      min: new Date(2019, 1, 1),`,
                `      max: new Date(2024, 1, 1),`,
                `      color: ['green', 'orange']`,
                `    }`,
                '  }]}',
              ]
            : []),
          ...(colorX === 'piecewise'
            ? [
                '  xAxis={[{',
                `    colorMap: {`,
                `      type: 'piecewise',`,
                `      thresholds: [new Date(2021, 1, 1), new Date(2023, 1, 1)],`,
                `      colors: ['blue', 'red', 'blue'],`,
                `    }`,
                '  }]}',
              ]
            : []),

          // ColorY
          ...(colorY === 'None' ? ['  yAxis={[{}]}'] : []),
          ...(colorY === 'continuous'
            ? [
                '  yAxis={[{',
                `    colorMap: {`,
                `      type: 'continuous',`,
                `      min: -10,`,
                `      max: 10,`,
                `      color: ['red', 'green'],`,
                `    }`,
                '  }]}',
              ]
            : []),
          ...(colorY === 'piecewise'
            ? [
                '  yAxis={[{',
                `    colorMap: {`,
                `      type: 'piecewise',`,
                `      thresholds: [0, 10],`,
                `      colors: ['red', 'green', 'blue'],`,
                `    }`,
                '  }]}',
              ]
            : []),
          `/>`,
        ].join('\n')}
        language="jsx"
        copyButtonHidden
      />
    </Stack>
  );
}

:::warning 서수(ordinal) 컬러 설정은 아직 라인 차트에서 지원되지 않아요. :::

보간 (Interpolation)

curve 속성을 사용해 점 사이에서 라인이 그려지는 방식을 선택해요. 'linear', 'catmullRom', 'monotoneX', 'monotoneY', 'natural', 'step', 'stepBefore', 'stepAfter', 'bumpX', 'bumpY' 문자열 값을 받아들여요.

아래 데모의 select를 사용해 각 값이 같은 데이터에서 어떻게 렌더링되는지 비교해 보세요.

시리즈마다 curve를 설정할 수 있으므로, 서로 다른 시리즈에 서로 다른 보간을 사용할 수 있어요.

import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import { LineChart } from '@mui/x-charts/LineChart';

import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
import { CurveType } from '@mui/x-charts/models';

const curveTypes: CurveType[] = [
  'linear',
  'catmullRom',
  'monotoneX',
  'monotoneY',
  'natural',
  'step',
  'stepBefore',
  'stepAfter',
  'bumpX',
  'bumpY',
];

function getExample(curveType: CurveType) {
  return `<LineChart
  series={[
    { curve: "${curveType}", data: [1, 5, 2, 6, 3, 9.3] },
    { curve: "${curveType}", data: [6, 3, 7, 9.5, 4, 2] },
  ]}
  {/* ... */}
/>`;
}

export default function InterpolationDemo() {
  const [curveType, setCurveType] = React.useState(curveTypes[0]);

  return (
    <Box sx={{ p: 2, width: 1, maxWidth: 600 }}>
      <TextField
        select
        label="interpolation method"
        value={curveType}
        sx={{ minWidth: 200, mb: 2 }}
        onChange={(event) => setCurveType(event.target.value as CurveType)}
      >
        {curveTypes.map((curve) => (
          <MenuItem key={curve} value={curve}>
            {curve}
          </MenuItem>
        ))}
      </TextField>
      <LineChart
        xAxis={[{ data: [1, 3, 5, 6, 7, 9], min: 0, max: 10 }]}
        series={[
          { curve: curveType, data: [1, 5, 2, 6, 3, 9.3] },
          { curve: curveType, data: [6, 3, 7, 9.5, 4, 2] },
        ]}
        height={300}
        skipAnimation
      />
      <HighlightedCode code={getExample(curveType)} language="tsx" />
    </Box>
  );
}

이어지는 계단 (Expanding steps)

계단 보간의 경우(curve가 'step', 'stepBefore', 'stepAfter'로 설정된 경우), 라인과 영역 차트를 조합하기 쉽도록 라인이 band 너비 전체로 확장돼요.

이 동작을 끄려면 strictStepCurve 시리즈 속성을 사용해요.

import * as React from 'react';
import Stack from '@mui/material/Stack';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import { LinePlot, MarkPlot } from '@mui/x-charts/LineChart';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { BarPlot } from '@mui/x-charts/BarChart';
import { ChartsAxisHighlight } from '@mui/x-charts/ChartsAxisHighlight';

const weekDay = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const stepCurves = ['step', 'stepBefore', 'stepAfter'];
type StepCurve = 'step' | 'stepBefore' | 'stepAfter';

export default function ExpandingStep() {
  const [strictStepCurve, setStrictStepCurve] = React.useState(false);
  const [connectNulls, setConnectNulls] = React.useState(false);
  const [curve, setCurve] = React.useState<StepCurve>('step');

  return (
    <Stack sx={{ width: '100%' }}>
      <Stack direction="row" sx={{ justifyContent: 'space-between' }}>
        <Stack>
          <FormControlLabel
            checked={connectNulls}
            control={
              <Checkbox
                onChange={(event) => setConnectNulls(event.target.checked)}
              />
            }
            label="connectNulls"
            labelPlacement="end"
          />
          <FormControlLabel
            checked={strictStepCurve}
            control={
              <Checkbox
                onChange={(event) => setStrictStepCurve(event.target.checked)}
              />
            }
            label="strictStepCurve"
            labelPlacement="end"
          />
        </Stack>
        <TextField
          select
          label="curve"
          value={curve}
          sx={{ minWidth: 100, mb: 2 }}
          onChange={(event) => setCurve(event.target.value as StepCurve)}
        >
          {stepCurves.map((curveType) => (
            <MenuItem key={curveType} value={curveType}>
              {curveType}
            </MenuItem>
          ))}
        </TextField>
      </Stack>
      <ChartsContainer
        xAxis={[{ scaleType: 'band', data: weekDay }]}
        series={[
          {
            type: 'line',
            curve,
            connectNulls,
            strictStepCurve,
            data: [5, 10, 16, 9, null, 6],
            showMark: true,
            color: 'blue',
          },
          {
            type: 'line',
            curve,
            connectNulls,
            strictStepCurve,
            data: [null, 15, 9, 6, 8, 3, 10],
            showMark: true,
            color: 'red',
          },
          {
            data: [1, 2, 3, 4, 3, 2, 1],
            type: 'bar',
          },
        ]}
        height={250}
        margin={{ bottom: 10 }}
        skipAnimation
      >
        <ChartsAxisHighlight x="band" />
        <BarPlot />
        <LinePlot />
        <MarkPlot />
        <ChartsXAxis />
        <ChartsYAxis />
      </ChartsContainer>
    </Stack>
  );
}

기준선 (Baseline)

영역 차트는 기본적으로 y축 값 0을 기준선으로 사용해요. 이는 참조로 잘 작동하지만, 상황에 따라 다른 기준선이 필요할 수 있어요.

baseline을 "min" 또는 "max"로 설정하면 라인의 위 또는 아래 영역을 채워요. baseline을 숫자로 설정해 기준선을 특정 값에 고정할 수도 있어요.

:::warning 스택 영역과 함께 baseline을 사용하지 마세요. 결과가 예상과 일치하지 않을 거예요. :::

import { LineChart } from '@mui/x-charts/LineChart';

export default function AreaBaseline() {
  return (
    <LineChart
      xAxis={[{ data: [1, 2, 3, 5, 8, 10] }]}
      series={[
        {
          data: [2, -5.5, 2, -7.5, 1.5, 6],
          area: true,
          baseline: 'min',
        },
      ]}
      height={300}
    />
  );
}

최적화 (Optimization)

큰 데이터셋에서는 마크 표시를 피해요.

showMark에 'start' 또는 'end'를 전달해 화면에 렌더링되는 요소 수를 제한하면서도 접근성을 위한 마크를 유지해요.

또는 showMarks에 콜백을 제공해 마크의 일부만 표시할 수 있어요.

이 데모는 인덱스가 짝수인 값에만 마크 하나를 표시해요. 강조된 점은 인덱스가 짝수든 홀수든 항상 마크를 보여줘요.

import { LineChart } from '@mui/x-charts/LineChart';

export default function MarkOptimization() {
  return (
    <LineChart
      xAxis={[{ data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }]}
      series={[
        {
          data: [2, 3, 5.5, 8.5, 1.5, 5, 1, 4, 3, 8],
          showMark: ({ index }) => index % 2 === 0,
        },
      ]}
      height={300}
    />
  );
}

큰 데이터셋의 경우, LineChartPro의 sampling prop을 설정해 축소했을 때 라인을 줄일 수 있어요. 알고리즘은 'm4', 'minmax', 'lttb' 중 선택할 수 있어요. 자세한 내용과 라이브 데모는 Charts—Performance를 참고해요.

CSS

CSS 선택자로 라인 차트 요소를 커스터마이즈할 수 있어요. 라인 플롯은 LineElement, AreaElement, MarkElement 세 가지 요소를 사용해요. lineClasses.line, lineClasses.area, lineClasses.mark CSS 클래스로 대상으로 삼을 수 있어요. 특정 시리즈를 대상으로 하려면 data-series 속성을 사용해요.

아래 데모에서는 각 라인이 커스텀 대시 스타일을 사용하고 마크는 숨겨져 있어요. 독일 GDP 영역은 커스텀 그라데이션을 사용해요. 그라데이션은 차트의 자식으로 정의돼요(fill에서 참조되는 myGradient).

<LineChart
  sx={{
    '& .MuiLineElement-root': {
      strokeDasharray: '10 5',
      strokeWidth: 4,
    },
    [`& .${lineClasses.line}`]: {
      strokeDasharray: '10 5',
      strokeWidth: 4,
    },
    [`& .${lineClasses.area}[data-series="Germany"]`]: {
      fill: "url('#myGradient')",
    },
  }}
/>
import { lineClasses, LineChart } from '@mui/x-charts/LineChart';
import { dataset } from '../dataset/gdpPerCapitaEvolution';

export default function CSSCustomization() {
  return (
    <LineChart
      dataset={dataset}
      sx={{
        [`& .${lineClasses.line}`]: {
          strokeDasharray: '10 5',
          strokeWidth: 4,
        },
        [`& .${lineClasses.area}[data-series="Germany"]`]: {
          fill: "url('#myGradient')",
          filter: 'none', // Remove the default filtering
        },
      }}
      xAxis={[
        {
          id: 'Years',
          dataKey: 'date',
          scaleType: 'time',
          valueFormatter: (date) => date.getFullYear().toString(),
        },
      ]}
      yAxis={[
        {
          width: 60,
        },
      ]}
      series={[
        {
          id: 'France',
          label: 'France',
          dataKey: 'fr',
          stack: 'total',
          area: true,
        },
        {
          id: 'Germany',
          label: 'Germany',
          dataKey: 'dl',
          stack: 'total',
          area: true,
        },
        {
          id: 'United Kingdom',
          label: 'United Kingdom',
          dataKey: 'gb',
          stack: 'total',
          area: true,
        },
      ]}
      height={300}
    >
      <defs>
        <linearGradient id="myGradient" gradientTransform="rotate(90)">
          <stop offset="5%" stopColor="gold" />
          <stop offset="95%" stopColor="red" />
        </linearGradient>
      </defs>
    </LineChart>
  );
}

다음 예시는 [data-series] 속성 선택자를 사용해 각 시리즈의 차트 라인, 범례 마크, 툴팁 마크에 점선 스트로크를 적용하는 방법을 보여줘요.

import Box from '@mui/material/Box';
import { LineChart, lineClasses } from '@mui/x-charts/LineChart';
import { labelMarkClasses } from '@mui/x-charts/ChartsLabel';

const margin = { right: 24 };
const uData = [4000, 3000, 2000, 2780, 1890, 2390, 3490];
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 StyledLineChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <LineChart
        series={[
          {
            data: pData,
            label: 'pv',
            id: 'pvId',
            showMark: true,
            labelMarkType: 'line',
          },
          {
            data: uData,
            label: 'uv',
            id: 'uvId',
            showMark: true,
            labelMarkType: 'line',
          },
        ]}
        xAxis={[{ id: 'x-axis', scaleType: 'point', data: xLabels, height: 28 }]}
        yAxis={[{ width: 50 }]}
        tooltipAxis={[{ axisId: 'x-axis', dataIndex: 6 }]}
        slotProps={{ tooltip: { position: 'left' } }}
        sx={{
          // Style the chart line, legend mark, and tooltip mark for pvId
          [`& .${lineClasses.line}[data-series="pvId"], [data-series="pvId"] .${labelMarkClasses.fill}`]:
            {
              strokeDasharray: '5 5',
              strokeWidth: 1,
              strokeLinecap: 'square',
            },
          // Style the chart line, legend mark, and tooltip mark for uvId
          [`& .${lineClasses.line}[data-series="uvId"], [data-series="uvId"] .${labelMarkClasses.fill}`]:
            {
              strokeDasharray: '3 4 5 2',
              strokeWidth: 1,
              strokeLinecap: 'square',
            },
        }}
        margin={margin}
      />
    </Box>
  );
}

마크 크기 (Mark size)

라인 시리즈와 mark 슬롯 모두 크기 속성을 받아들이지 않으므로, 마크 크기는 lineClasses.mark 클래스에 CSS로 설정해야 해요.

기본 'circle' 모양은 SVG circle 요소를 렌더링하므로 기본값이 5인 r(반지름) 속성을 사용해요. 다른 모양은 r이 영향을 주지 않는 SVG path 요소를 렌더링해요. 그런 모양에는 scale 속성을 사용해요. scale은 마크를 자신의 중심을 기준으로 재조정해요.

import * as React from 'react';
import Box from '@mui/material/Box';
import MenuItem from '@mui/material/MenuItem';
import Slider from '@mui/material/Slider';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
import { LineChart, lineClasses } from '@mui/x-charts/LineChart';

type Shape = 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye';

const shapes: Shape[] = [
  'circle',
  'cross',
  'diamond',
  'square',
  'star',
  'triangle',
  'wye',
];

export default function MarkSize() {
  const [shape, setShape] = React.useState<Shape>('circle');
  const [radius, setRadius] = React.useState(6);
  const [scale, setScale] = React.useState(1.2);

  const isCircle = shape === 'circle';
  const markStyle = isCircle ? { r: radius } : { scale: `${scale}` };

  const code = `<LineChart
  series={[{ data: [...], showMark: true, shape: '${shape}' }]}
  sx={{
    [\`& .\${lineClasses.mark}\`]: {
      ${isCircle ? `r: ${radius}` : `scale: '${scale}'`},
    },
  }}
/>`;

  return (
    <Box sx={{ p: 2, width: '100%', maxWidth: 600 }}>
      <Stack direction="row" spacing={3} sx={{ alignItems: 'center', mb: 1 }}>
        <TextField
          select
          label="shape"
          value={shape}
          sx={{ minWidth: 140 }}
          onChange={(event) => setShape(event.target.value as Shape)}
        >
          {shapes.map((option) => (
            <MenuItem key={option} value={option}>
              {option}
            </MenuItem>
          ))}
        </TextField>
        <Stack sx={{ flex: 1 }}>
          <Typography id="mark-size" gutterBottom>
            {isCircle ? 'radius' : 'scale'}
          </Typography>
          {isCircle ? (
            <Slider
              aria-labelledby="mark-size"
              value={radius}
              onChange={(event, value) => setRadius(value as number)}
              valueLabelDisplay="auto"
              min={1}
              max={12}
              step={1}
            />
          ) : (
            <Slider
              aria-labelledby="mark-size"
              value={scale}
              onChange={(event, value) => setScale(value as number)}
              valueLabelDisplay="auto"
              min={0.5}
              max={3}
              step={0.1}
            />
          )}
        </Stack>
      </Stack>
      <LineChart
        xAxis={[{ data: [1, 2, 3, 5, 8, 10] }]}
        series={[{ data: [2, 5.5, 2, 8.5, 1.5, 5], showMark: true, shape }]}
        height={250}
        sx={{ [`& .${lineClasses.mark}`]: markStyle }}
      />
      <HighlightedCode code={code} language="tsx" />
    </Box>
  );
}

애니메이션 (Animation)

차트 컨테이너는 prefers-reduced-motion을 존중하지만, skipAnimation prop을 true로 설정해 수동으로 애니메이션을 끌 수도 있어요.

skipAnimation을 true로 설정하면 차트가 애니메이션 없이 렌더링돼요.

:::warning 시리즈를 상호작용적으로 추가하거나 제거한다면 각 시리즈에 id를 부여해 주세요. 그렇지 않으면 차트가 시리즈를 업데이트·제거·추가 중 어떤 것인지 알 수 없어 애니메이션이 예상대로 동작하지 않을 수 있어요. :::

// For a single component chart
<LineChart skipAnimation />

// For a composed chart
<ChartsContainer>
  <LinePlot skipAnimation />
  <AreaPlot skipAnimation />
</ChartsContainer>
import * as React from 'react';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import { LineChart } from '@mui/x-charts/LineChart';
import { mangoFusionPalette } from '@mui/x-charts/colorPalettes';

const defaultSeries = [
  { id: '1', data: [4, 5, 1, 2, 3, 3, 2], area: true, stack: '1' },
  { id: '2', data: [7, 4, 6, 7, 2, 3, 5], area: true, stack: '1' },
  { id: '3', data: [6, 4, 1, 2, 6, 3, 3], area: true, stack: '1' },
  { id: '4', data: [4, 7, 6, 1, 2, 7, 7], area: true, stack: '1' },
  { id: '5', data: [2, 2, 1, 7, 1, 5, 3], area: true, stack: '1' },
  { id: '6', data: [6, 6, 1, 6, 7, 1, 1], area: true, stack: '1' },
  { id: '7', data: [7, 6, 1, 6, 4, 4, 6], area: true, stack: '1' },
  { id: '8', data: [4, 3, 1, 6, 6, 3, 5], area: true, stack: '1' },
  { id: '9', data: [7, 6, 2, 7, 4, 2, 7], area: true, stack: '1' },
].map((item, index) => ({
  ...item,
  color: mangoFusionPalette('light')[index],
}));

export default function LineAnimation() {
  const [series, setSeries] = React.useState(defaultSeries);
  const [nbSeries, setNbSeries] = React.useState(3);
  const [skipAnimation, setSkipAnimation] = React.useState(false);

  return (
    <div
      style={{
        width: '100%',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <div>
        <LineChart
          xAxis={[{ data: [1, 2, 3, 4, 5, 6, 7] }]}
          series={[
            ...series.slice(0, Math.min(nbSeries, 8)),
            ...series.slice(8, 10),
          ]}
          skipAnimation={skipAnimation}
          height={400}
        />
      </div>
      <Stack spacing={1} direction="row" sx={{ flexWrap: 'wrap' }}>
        <Button
          variant="outlined"
          onClick={() =>
            setSeries((prev) =>
              prev.map((item) => ({
                ...item,
                // eslint-disable-next-line no-restricted-properties -- interactive randomize button
                data: item.data.map((v) => Math.max(0.5, v - 4 + 8 * Math.random())),
              })),
            )
          }
        >
          randomize
        </Button>
        <Button
          variant="outlined"
          onClick={() => setNbSeries((prev) => prev - 1)}
          disabled={nbSeries === 0}
        >
          remove
        </Button>
        <Button
          variant="outlined"
          onClick={() => setNbSeries((prev) => prev + 1)}
          disabled={nbSeries === 8}
        >
          add
        </Button>
        <FormControlLabel
          checked={skipAnimation}
          control={
            <Checkbox onChange={(event) => setSkipAnimation(event.target.checked)} />
          }
          label="skipAnimation"
          labelPlacement="end"
        />
      </Stack>
    </div>
  );
}

Composition

Composition에는 series, xAxis, yAxis props를 제공하기 위해 ChartsDataProvider를 사용해요.

composition에서 사용 가능한 공용 차트 컴포넌트 외에도, LinePlot, AreaPlot, MarkPlot, LineHighlightPlot, FocusedLineMark를 사용해 라인, 영역, 마크, 포커스 링을 그릴 수 있어요.

라인 차트는 이렇게 구성돼요:

<ChartsDataProvider>
  <ChartsWrapper>
    <ChartsLegend />
    <ChartsSurface>
      <ChartsGrid />
      <g clipPath={`url(#${clipPathId})`}>
        {/* Elements clipped inside the drawing area. */}
        <AreaPlot />
        <LinePlot />
        <ChartsOverlay />
        <ChartsAxisHighlight />
      </g>
      <FocusedLineMark />
      <ChartsAxis />
      <g data-drawing-container>
        {/* Elements able to overflow the drawing area. */}
        <MarkPlot />
      </g>
      <LineHighlightPlot />
      <ChartsClipPath id={clipPathId} />
    </ChartsSurface>
    <ChartsTooltip />
  </ChartsWrapper>
</ChartsDataProvider>

:::info data-drawing-container 속성은 자식 요소가 넘쳐 흐를 때조차 그리는 영역의 일부로 표시해요.

자세한 내용은 Composition—clipping을 참고해요. :::

더 알아보기 (Learn more)