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

Charts - 선(Lines) 데모

원문 보기 위키 갱신

기본 플롯, 라이브 데이터, 참조선, 커스텀 스타일링에 선 차트를 사용하는 데모들이에요.

출처: MUI X documentation

본문

SimpleLineChart

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

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 SimpleLineChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <LineChart
        series={[
          { data: pData, label: 'pv' },
          { data: uData, label: 'uv' },
        ]}
        xAxis={[{ scaleType: 'point', data: xLabels, height: 28 }]}
        yAxis={[{ width: 50 }]}
        margin={margin}
      />
    </Box>
  );
}

TinyLineChart

import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { LinePlot, MarkPlot, lineClasses } from '@mui/x-charts/LineChart';

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 TinyLineChart() {
  return (
    <ChartsContainer
      width={500}
      height={300}
      series={[{ type: 'line', data: pData, showMark: true }]}
      xAxis={[{ scaleType: 'point', data: xLabels, position: 'none' }]}
      yAxis={[{ position: 'none' }]}
      sx={{
        [`& .${lineClasses.line}`]: {
          stroke: '#8884d8',
          strokeWidth: 2,
        },
        [`& .${lineClasses.mark}`]: {
          stroke: '#8884d8',
          r: 4, // Modify the circle radius
          fill: '#fff',
          strokeWidth: 2,
        },
      }}
      disableAxisListener
    >
      <LinePlot />
      <MarkPlot />
    </ChartsContainer>
  );
}

DashedLineChart

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

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 DashedLineChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <LineChart
        series={[
          { data: pData, label: 'pv', id: 'pvId', showMark: true },
          { data: uData, label: 'uv', id: 'uvId', showMark: true },
        ]}
        xAxis={[{ scaleType: 'point', data: xLabels, height: 28 }]}
        yAxis={[{ width: 50 }]}
        sx={{
          [`.${lineClasses.line}, .${lineClasses.mark}`]: {
            strokeWidth: 1,
          },
          [`.${lineClasses.line}[data-series="pvId"]`]: {
            strokeDasharray: '5 5',
          },
          [`.${lineClasses.line}[data-series="uvId"]`]: {
            strokeDasharray: '3 4 5 2',
          },
          [`.${lineClasses.mark}:not([data-highlighted="true"])`]: {
            fill: '#fff',
          },
          [`& [data-highlighted="true"]`]: {
            stroke: 'none',
          },
        }}
        margin={margin}
      />
    </Box>
  );
}

BiaxialLineChart

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

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 BiaxialLineChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <LineChart
        series={[
          { data: pData, label: 'pv', yAxisId: 'leftAxisId' },
          { data: uData, label: 'uv', yAxisId: 'rightAxisId' },
        ]}
        xAxis={[{ scaleType: 'point', data: xLabels, height: 28 }]}
        yAxis={[
          { id: 'leftAxisId', width: 50 },
          { id: 'rightAxisId', position: 'right' },
        ]}
      />
    </Box>
  );
}

LineChartWithReferenceLines

import Box from '@mui/material/Box';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { ChartsReferenceLine } from '@mui/x-charts/ChartsReferenceLine';
import { LinePlot } from '@mui/x-charts/LineChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';

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 LineChartWithReferenceLines() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <ChartsContainer
        series={[
          { data: pData, label: 'pv', type: 'line' },
          { data: uData, label: 'uv', type: 'line' },
        ]}
        xAxis={[{ scaleType: 'point', data: xLabels, height: 28 }]}
        yAxis={[{ width: 50 }]}
        margin={margin}
      >
        <LinePlot />
        <ChartsReferenceLine
          x="Page C"
          label="Max PV PAGE"
          lineStyle={{ stroke: 'red' }}
        />
        <ChartsReferenceLine y={9800} label="Max" lineStyle={{ stroke: 'red' }} />
        <ChartsXAxis />
        <ChartsYAxis />
      </ChartsContainer>
    </Box>
  );
}

LineChartConnectNulls

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

const margin = { right: 24 };
const data = [4000, 3000, 2000, null, 1890, 2390, 3490];
const xData = ['Page A', 'Page B', 'Page C', 'Page D', 'Page E', 'Page F', 'Page G'];
export default function LineChartConnectNulls() {
  return (
    <Stack sx={{ width: '100%', height: 400 }}>
      <LineChart
        xAxis={[{ data: xData, scaleType: 'point', height: 28 }]}
        series={[{ data, showMark: true }]}
        margin={margin}
      />
      <LineChart
        xAxis={[{ data: xData, scaleType: 'point', height: 28 }]}
        series={[{ data, connectNulls: true, showMark: true }]}
        margin={margin}
      />
    </Stack>
  );
}

CustomLabelLineChart

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

const margin = { right: 24 };
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',
];

function CustomMark(props: MarkElementProps) {
  const { x, y, color } = props;

  return (
    <g>
      <circle cx={x} cy={y} r={4} fill={color || 'currentColor'} />
      <text
        x={x}
        y={Number(y) - 12}
        style={{
          textAnchor: 'middle',
          dominantBaseline: 'auto',
          fill: color || 'currentColor',
          fontWeight: 'bold',
          fontSize: 12,
        }}
      >
        {pData[props.dataIndex].toString()}
      </text>
    </g>
  );
}

export default function CustomLabelChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <LineChart
        series={[{ data: pData, label: 'pv', showMark: true }]}
        xAxis={[{ scaleType: 'point', data: xLabels }]}
        yAxis={[{ width: 50 }]}
        margin={margin}
        slots={{
          mark: CustomMark,
        }}
      />
    </Box>
  );
}

라이브 데이터가 있는 선 차트

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

const dateFormatter = Intl.DateTimeFormat(undefined, {
  month: '2-digit',
  day: '2-digit',
});
const oneDay = 24 * 60 * 60 * 1000; // in milliseconds

const length = 50;
const initialFirstData = Array.from<number>({ length }).map(
  (_, __, array) => (array.at(-1) ?? 0) + randBetween(-100, 500),
);
const initialSecondData = Array.from<number>({ length }).map(
  (_, __, array) => (array.at(-1) ?? 0) + randBetween(-500, 100),
);

export default function LiveLineChartNoSnap() {
  const [running, setRunning] = React.useState(false);
  const [date, setDate] = React.useState(new Date(2000, 0, 0));
  const [firstData, setFirstData] = React.useState(initialFirstData);
  const [secondData, setSecondData] = React.useState(initialSecondData);

  React.useEffect(() => {
    if (!running) {
      return undefined;
    }
    const intervalId = setInterval(() => {
      setDate((prev) => new Date(prev.getTime() + oneDay));
      setFirstData((prev) => [
        ...prev.slice(1),
        prev.at(-1)! + randBetween(-500, 500),
      ]);
      setSecondData((prev) => [
        ...prev.slice(1),
        prev.at(-1)! + randBetween(-500, 500),
      ]);
    }, 100);

    return () => {
      clearInterval(intervalId);
    };
  }, [running]);

  return (
    <Box sx={{ width: '100%' }}>
      <LineChart
        height={300}
        skipAnimation
        series={[{ data: secondData }, { data: firstData }]}
        xAxis={[
          {
            scaleType: 'point',
            data: Array.from({ length }).map(
              (_, i) => new Date(date.getTime() + i * oneDay),
            ),
            valueFormatter: (value: Date) => dateFormatter.format(value),
          },
        ]}
        yAxis={[{ width: 50 }]}
        margin={{ right: 24 }}
      />
      <Button size="small" variant="contained" onClick={() => setRunning((p) => !p)}>
        {running ? 'stop' : 'start'}
      </Button>
      <Button
        size="small"
        variant="outlined"
        sx={{ marginLeft: 1.5 }}
        onClick={() => {
          setFirstData(initialFirstData);
          setSecondData(initialSecondData);
        }}
      >
        reset
      </Button>
    </Box>
  );
}

function randBetween(min: number, max: number) {
  // eslint-disable-next-line no-restricted-properties -- live animation demo
  return Math.floor(Math.random() * (max - min + 1) + min);
}

예측이 있는 선(Line with forecast)

데이터의 일부가 서로 다른 의미를 가진다는 것을 보여주려면 각 부분을 다르게 스타일링할 수 있어요.

아래 데모에서 점선은 추정 또는 예측된 값을 나타내요. slots.line prop을 기본 선을 두 번 렌더링하는 커스텀 컴포넌트로 설정하세요.

  • 첫 번째 경로는 알려진 값(차트 왼쪽에서 한계까지)을 보여주도록 잘라요(clip).
  • 두 번째 경로는 대시 스타일로 예측(한계에서 차트 오른쪽까지)을 보여주도록 잘라요.

불확실성 영역이 예측의 불확실성을 나타내요.

import * as React from 'react';
import Box from '@mui/material/Box';
import {
  AnimatedLine,
  AnimatedLineProps,
  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 { ChartsTooltip } from '@mui/x-charts/ChartsTooltip';
import { ChartsClipPath } from '@mui/x-charts/ChartsClipPath';
import {
  useChartId,
  useDrawingArea,
  useLineSeries,
  useXAxis,
  useXScale,
  useYScale,
} from '@mui/x-charts/hooks';
import * as d3Shape from '@mui/x-charts-vendor/d3-shape';
import { SxProps } from '@mui/system';
import { useTheme, Theme } from '@mui/material/styles';

interface CustomAnimatedLineProps extends AnimatedLineProps {
  limit?: number;
  sxBefore?: SxProps<Theme>;
  sxAfter?: SxProps<Theme>;
}

function CustomAnimatedLine(props: CustomAnimatedLineProps) {
  const { limit, sxBefore, sxAfter, ...other } = props;
  const { top, bottom, height, left, width } = useDrawingArea();
  const scale = useXScale();
  const chartId = useChartId();

  if (limit === undefined) {
    return <AnimatedLine {...other} />;
  }

  const limitPosition = scale(limit); // Convert value to x coordinate.

  if (limitPosition === undefined) {
    return <AnimatedLine {...other} />;
  }

  const clipIdleft = `${chartId}-${props.ownerState.seriesId}-line-limit-${limit}-1`;
  const clipIdRight = `${chartId}-${props.ownerState.seriesId}-line-limit-${limit}-2`;
  return (
    <React.Fragment>
      {/* Clip to show the line before the limit */}
      <clipPath id={clipIdleft}>
        <rect
          x={left}
          y={0}
          width={limitPosition - left}
          height={top + height + bottom}
        />
      </clipPath>
      {/* Clip to show the line after the limit */}
      <clipPath id={clipIdRight}>
        <rect
          x={limitPosition}
          y={0}
          width={left + width - limitPosition}
          height={top + height + bottom}
        />
      </clipPath>
      <g clipPath={`url(#${clipIdleft})`} className="line-before">
        <AnimatedLine {...other} />
      </g>
      <g clipPath={`url(#${clipIdRight})`} className="line-after">
        <AnimatedLine {...other} />
      </g>
    </React.Fragment>
  );
}

function ForecastArea({
  limit,
  forecast,
}: {
  limit: number;
  forecast: { y0: number; y1: number }[];
}) {
  const lineSeries = useLineSeries();
  const xAxis = useXAxis();
  const xScale = useXScale();
  const yScale = useYScale();

  const xAxisData: number[] = xAxis.data?.slice(limit) ?? [];

  if (!yScale) {
    return null;
  }

  return (
    <React.Fragment>
      {lineSeries.map((series) => {
        const data = xAxisData.map((v, i) => ({
          x: v,
          y0: forecast[i].y0,
          y1: forecast[i].y1,
        }));

        const path = d3Shape
          .area<(typeof data)[number]>()
          .x((d) => xScale(d.x)!)
          .y0((d) => yScale(d.y0)!)
          .y1((d) => yScale(d.y1)!)(data)!;

        return <path key={`forecast-area-${series.id}`} d={path} fill="#0000ff44" />;
      })}
    </React.Fragment>
  );
}

function ShadedBackground({ limit }: { limit: number }) {
  const { top, bottom, height, left, width } = useDrawingArea();
  const scale = useXScale();
  const limitPosition = scale(limit)!;
  const theme = useTheme();
  const fill =
    theme.palette.mode === 'dark'
      ? theme.palette.grey[900]
      : theme.palette.grey[400];

  return (
    <rect
      x={limitPosition}
      y={0}
      width={left + width - limitPosition}
      height={top + height + bottom}
      fill={fill}
      opacity={0.4}
    />
  );
}

export default function LineWithUncertaintyArea() {
  const id = React.useId();
  const clipPathId = `${id}-clip-path`;

  return (
    <Box sx={{ width: '100%', height: 200 }}>
      <ChartsContainer
        series={[
          {
            type: 'line',
            data: [1, 2, 3, 4, 1, 2, 3, 4, 5],
            valueFormatter: (v, i) => `${v}${i.dataIndex > 5 ? ' (estimated)' : ''}`,
            showMark: true,
          },
        ]}
        xAxis={[{ data: [0, 1, 2, 3, 4, 5, 6, 7, 8] }]}
        sx={{ '& .line-after path': { strokeDasharray: '10 5' } }}
      >
        <ChartsXAxis />
        <ChartsYAxis />

        <g clipPath={`url(#${clipPathId})`}>
          <ShadedBackground limit={5} />
          <LinePlot
            slots={{ line: CustomAnimatedLine }}
            slotProps={{ line: { limit: 5 } as any }}
          />
          <ForecastArea
            limit={5}
            forecast={[
              { y0: 2, y1: 2 },
              { y0: 2.3, y1: 4 },
              { y0: 3, y1: 5 },
              { y0: 4.4, y1: 5.8 },
            ]}
          />
        </g>
        <g data-drawing-container>
          <MarkPlot />
        </g>
        <ChartsTooltip />
        <ChartsClipPath id={clipPathId} />
      </ChartsContainer>
    </Box>
  );
}

CustomLineMarks

"circle"이 아닌 모양을 사용하면 마크 요소에 대해 <circle /> 대신 <path />가 렌더링돼요. 이 변경은 렌더링 성능을 저하시킬 수 있어요(예: 1,000개의 마크를 렌더링하는 데 약 50ms).

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

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 CustomLineMarks() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <LineChart
        series={[
          {
            data: pData,
            label: 'pv',
            shape: 'cross',
            showMark: ({ index }) => index % 2 === 0,
          },
          {
            data: uData,
            label: 'uv',
            shape: 'diamond',
            showMark: ({ index }) => index % 2 === 0,
          },
        ]}
        xAxis={[{ scaleType: 'point', data: xLabels, height: 28 }]}
        yAxis={[{ width: 50 }]}
        margin={margin}
      />
    </Box>
  );
}

더 넓은 상호작용 영역

선이 위에 있을 때 포인터가 그 위에 호버하면 하이라이트되지만, 상호작용 영역은 좁아요. 내장 솔루션이 나올 때까지 슬롯으로 더 넓은 히트 영역을 정의할 수 있어요.

두 개의 경로를 사용하세요: 선용으로 얇고 보이는 것, 포인터 이벤트용으로 더 넓고 보이지 않는 것.

선이 교차할 때 하이라이트되는 시리즈는 슬롯에서 마지막으로 정의된 것으로, 반드시 포인터에 가장 가까운 것은 아니에요.

import * as React from 'react';
import Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import { AnimatedLineProps, LineChart } from '@mui/x-charts/LineChart';
import { HighlightScope } from '@mui/x-charts/context';

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',
];

const highlightScope: HighlightScope<'line'> = {
  highlight: 'item',
  fade: 'global',
};

const settings = {
  height: 300,
  series: [
    { data: pData, label: 'pv', highlightScope },
    { data: uData, label: 'uv', highlightScope },
  ],
  xAxis: [{ scaleType: 'point', data: xLabels }],
  yAxis: [{ width: 50 }],
  margin,
} as const;

function CustomLine(props: AnimatedLineProps) {
  const { d, ownerState, className, ...other } = props;

  return (
    <React.Fragment>
      <path
        d={d}
        stroke={
          ownerState.gradientId ? `url(#${ownerState.gradientId})` : ownerState.color
        }
        strokeWidth={ownerState.isHighlighted ? 4 : 2}
        strokeLinejoin="round"
        fill="none"
        filter={ownerState.isHighlighted ? 'brightness(120%)' : undefined}
        opacity={ownerState.isFaded ? 0.3 : 1}
        className={className}
      />
      <path
        d={d}
        stroke="transparent"
        strokeWidth={25}
        fill="none"
        className="interaction-area"
        {...other}
      />
    </React.Fragment>
  );
}

export default function LargerHighlightLineNoSnap() {
  const [showInteractionArea, setShowInteractionArea] = React.useState(true);

  return (
    <Box
      sx={{
        width: '100%',
        '& .interaction-area': showInteractionArea
          ? {
              stroke: 'lightgray',
              strokeOpacity: 0.3,
            }
          : {},
      }}
    >
      <FormControlLabel
        checked={showInteractionArea}
        control={
          <Checkbox
            onChange={(event) => setShowInteractionArea(event.target.checked)}
          />
        }
        label="Show highlight area"
        labelPlacement="end"
      />
      <LineChart {...settings} slots={{ line: CustomLine }} />
    </Box>
  );
}