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

Charts - 사용자 지정 컴포넌트

원문 보기 위키 갱신

Charts - 사용자 지정 컴포넌트 (Custom components)

제공된 훅을 사용해 사용자 지정 차트 컴포넌트를 만듭니다.

출처: MUI X documentation

본문

MUI X Charts 패키지는 사용자 지정 Chart 컴포넌트를 만드는 데 도움이 되는 일련의 훅을 제공합니다.

치수와 상호작용 (Interact with dimensions)

다음 섹션에서는 사용자 지정 Charts를 만들 때 높이, 너비, 여백, 스케일, series 데이터 등 다양한 치수를 다루는 방법을 설명합니다.

드로잉 영역 (Drawing area)

드로잉 영역은 데이터(산점, 선, 파이 조각 등)를 그릴 수 있는 공간을 의미합니다. Charts 치수는 다음 props로 정의됩니다:

  • SVG 크기를 위한 height와 width; 제공하지 않으면 컨테이너에서 파생됨
  • SVG 테두리와 축 또는 드로잉 영역 사이의 공간을 위한 margin
  • 축을 그리기 위해 추가 공간을 더해 주는 축 치수 속성들 (xAxis[].height와 yAxis[].width)

margin은 추가 요소를 위한 공간을 남기거나 데이터 항목이 드로잉 영역 밖으로 넘치도록 할 때 사용됩니다.

Chart 하위 컴포넌트에서 useDrawingArea() 훅을 사용해 드로잉 영역의 좌표를 얻을 수 있습니다:

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

const { left, top, width, height } = useDrawingArea();
import * as React from 'react';
import { styled } from '@mui/material/styles';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { LinePlot } from '@mui/x-charts/LineChart';
import { useDrawingArea } from '@mui/x-charts/hooks';

const StyledPath = styled('path')(({ theme }) => ({
  fill: 'none',
  stroke: theme.palette.text.primary,
  shapeRendering: 'crispEdges',
  strokeWidth: 1,
  pointerEvents: 'none',
}));

const StyledText = styled('text')(({ theme }) => ({
  stroke: 'none',
  fill: theme.palette.text.primary,
  shapeRendering: 'crispEdges',
}));

function DrawingAreaBox() {
  const { left, top, width, height } = useDrawingArea();
  return (
    <React.Fragment>
      <StyledPath
        d={`M ${left} ${top} l ${width} 0 l 0 ${height} l -${width} 0 Z`}
      />
      <circle cx={left} cy={top} r={3} style={{ fill: 'red' }} />
      <circle cx={left + width} cy={top + height} r={3} style={{ fill: 'red' }} />
      <StyledText
        x={left}
        y={top}
        textAnchor="start"
        dominantBaseline="text-after-edge"
      >
        ({left},{top})
      </StyledText>
      <StyledText
        x={left + width}
        y={top + height}
        textAnchor="end"
        dominantBaseline="text-before-edge"
      >
        ({left + width},{top + height})
      </StyledText>
    </React.Fragment>
  );
}
export default function BasicScaleDemo() {
  return (
    <ChartsContainer
      height={300}
      series={[
        {
          type: 'line',
          data: [13, 13, 54, 651, 657, 987, 64, 654, 954, 654, 897, 84],
        },
      ]}
      xAxis={[{ data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], position: 'none' }]}
      yAxis={[{ position: 'none' }]}
    >
      <LinePlot />
      <DrawingAreaBox />
    </ChartsContainer>
  );
}

스케일 (Scales)

Line, Bar, Scatter 같은 일부 Charts는 series의 데이터와 SVG 좌표 사이의 매핑을 수행합니다.

예를 들어 2022년 12월 6일의 값이 $36,725인 선 차트 series는 좌표 (628, 514)로 매핑될 수 있습니다. 이 연산은 반대 방향으로도 가능합니다: x=628 좌표는 2022년 12월 6일과 연결되고 y=514는 $36,725 값과 연결됩니다.

이 매핑은 SVG와 드로잉 영역의 치수에 따라 달라집니다. 또한 스케일(linear, log, square root)과 최소/최대 값 같은 축 속성들에도 의존합니다. 이 모든 데이터는 d3-scale 객체에서 사용할 수 있습니다.

useXScale()와 useYScale()을 사용해 이 스케일에 접근할 수 있습니다. 둘 다 숫자나 문자열을 받습니다. 숫자를 사용하면 사용할 축의 인덱스를 선택하고, 문자열을 사용하면 축의 ID로 축을 선택합니다.

스케일 객체는 값이 SVG 좌표로 매핑되도록 생성됩니다. 드로잉 영역은 자동으로 처리됩니다.

값을 좌표로 (Value to coordinate)

기본 d3-scale 메서드는 값을 좌표로 매핑합니다. 예를 들어 x=0 좌표를 다음과 같이 얻을 수 있습니다:

// get the default x-axis scale
const xAxisScale = useXScale();
// get the position associated to the value 0
const xOrigin = xAxisScale(0);
import * as React from 'react';
import { styled } from '@mui/material/styles';
import { ScaleLinear } from '@mui/x-charts-vendor/d3-scale';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { LinePlot } from '@mui/x-charts/LineChart';
import { useDrawingArea, useXScale, useYScale } from '@mui/x-charts/hooks';

const x = Array.from({ length: 21 }, (_, index) => -1 + 0.2 * index);
const linear = x.map((v) => -1 + v);
const poly = x.map((v) => -1 + v ** 2 - v);

const StyledPath = styled('path')<{ color: 'primary' | 'secondary' }>(
  ({ theme, color }) => ({
    fill: 'none',
    stroke: theme.palette.text[color],
    shapeRendering: 'crispEdges',
    strokeWidth: 1,
    pointerEvents: 'none',
  }),
);

function CartesianAxis() {
  // Get the drawing area bounding box
  const { left, top, width, height } = useDrawingArea();

  // Get the two scale
  const yAxisScale = useYScale() as ScaleLinear<any, any>;
  const xAxisScale = useXScale() as ScaleLinear<any, any>;

  const yOrigin = yAxisScale(0);
  const xOrigin = xAxisScale(0);

  const xTicks = [-2, -1, 1, 2, 3];
  const yTicks = [-2, -1, 1, 2, 3, 4, 5];

  return (
    <React.Fragment>
      {yTicks.map((value) => (
        <StyledPath
          key={value}
          d={`M ${left} ${yAxisScale(value)} l ${width} 0`}
          color="secondary"
        />
      ))}
      {xTicks.map((value) => (
        <StyledPath
          key={value}
          d={`M ${xAxisScale(value)} ${top} l 0 ${height}`}
          color="secondary"
        />
      ))}
      <StyledPath d={`M ${left} ${yOrigin} l ${width} 0`} color="primary" />
      <StyledPath d={`M ${xOrigin} ${top} l 0 ${height}`} color="primary" />
    </React.Fragment>
  );
}
export default function OriginDemo() {
  return (
    <ChartsContainer
      margin={{ top: 5, left: 5, right: 5, bottom: 5 }}
      height={300}
      series={[
        {
          type: 'line',
          data: linear,
        },

        {
          type: 'line',
          data: poly,
        },
      ]}
      xAxis={[{ data: x, scaleType: 'linear', min: -1, max: 3, position: 'none' }]}
      yAxis={[{ min: -2, max: 5, position: 'none' }]}
    >
      <CartesianAxis />
      <LinePlot />
    </ChartsContainer>
  );
}

좌표를 값으로 (Coordinate to value)

d3-scale 객체를 사용하면 invert() 메서드로 좌표를 데이터 값으로 변환할 수 있습니다.

다음 예제에는 서로 다른 y축을 사용해 그린 두 개의 선이 있습니다. invert()를 사용하면 현재 마우스 좌표 y와 연결된 값을 다음과 같이 구할 수 있습니다:

<text>{leftAxisScale.invert(yCoordinate).toFixed(0)}</text>
import * as React from 'react';
import { ScaleLinear } from '@mui/x-charts-vendor/d3-scale';
import { styled } from '@mui/material/styles';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { LinePlot } from '@mui/x-charts/LineChart';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { useDrawingArea, useYScale } from '@mui/x-charts/hooks';

const StyledPath = styled('path')(({ theme }) => ({
  fill: 'none',
  stroke: theme.palette.text.primary,
  shapeRendering: 'crispEdges',
  strokeWidth: 1,
  pointerEvents: 'none',
  strokeDasharray: '5 2',
}));

const StyledText = styled('text')(({ theme }) => ({
  stroke: 'none',
  fill: theme.palette.text.primary,
  shapeRendering: 'crispEdges',
}));

function ValueHighlight(props: {
  chartRef: React.RefObject<HTMLDivElement | null>;
}) {
  const { chartRef } = props;

  // Get the drawing area bounding box
  const { left, top, width, height } = useDrawingArea();

  // Get the two scale
  const leftAxisScale = useYScale('left_axis_id') as ScaleLinear<any, any>;
  const rightAxisScale = useYScale('right_axis_id') as ScaleLinear<any, any>;

  const [mouseY, setMouseY] = React.useState<null | number>(null);

  React.useEffect(() => {
    const element = chartRef.current;
    if (element === null) {
      return () => {};
    }

    const handleMouseOut = () => {
      setMouseY(null);
    };

    const handleMouseMove = (event: MouseEvent) => {
      const x = event.offsetX;
      const y = event.offsetY;
      if (x < left || x > left + width) {
        setMouseY(null);
        return;
      }
      if (y < top - 10 || y > top + height + 10) {
        // Allows some margin if slightly on top/bottom of the drawing area
        setMouseY(null);
        return;
      }
      setMouseY(Math.max(Math.min(top + height, y), top)); // clamp to the drawing area
    };

    element.addEventListener('mouseout', handleMouseOut);
    element.addEventListener('mousemove', handleMouseMove);
    return () => {
      element.removeEventListener('mouseout', handleMouseOut);
      element.removeEventListener('mousemove', handleMouseMove);
    };
  }, [height, left, top, width, chartRef]);

  if (mouseY === null) {
    return null;
  }
  return (
    <React.Fragment>
      <StyledPath d={`M ${left} ${mouseY} l ${width} 0`} />
      <StyledText
        x={left + 5}
        y={mouseY}
        textAnchor="start"
        dominantBaseline="text-after-edge"
      >
        {leftAxisScale.invert(mouseY).toFixed(0)}
      </StyledText>

      <StyledText
        x={left + width - 5}
        y={mouseY}
        textAnchor="end"
        dominantBaseline="text-after-edge"
      >
        {rightAxisScale.invert(mouseY).toFixed(0)}
      </StyledText>
    </React.Fragment>
  );
}
export default function ScaleDemo() {
  const chartRef = React.useRef<HTMLDivElement>(null);
  return (
    <ChartsContainer
      ref={chartRef}
      height={300}
      series={[
        {
          type: 'line',
          data: [5, 15, 20, 24, 30, 38, 40, 51, 52, 61],
          yAxisId: 'left_axis_id',
        },
        {
          type: 'line',
          data: [
            50134, 48361, 46362, 44826, 42376, 40168, 38264, 36159, 34259, 32168,
          ],
          yAxisId: 'right_axis_id',
        },
      ]}
      xAxis={[
        {
          data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
          scaleType: 'point',
          position: 'none',
        },
      ]}
      yAxis={[
        { id: 'left_axis_id', position: 'left' },
        { id: 'right_axis_id', position: 'right', width: 50 },
      ]}
    >
      <LinePlot />
      <ChartsYAxis axisId="left_axis_id" />
      <ChartsYAxis axisId="right_axis_id" />
      <ValueHighlight chartRef={chartRef} />
    </ChartsContainer>
  );
}

Series

Series 정보는 모든 series 유형에 대해 useSeries() 훅으로, 특정 series 유형에 대해서는 use[Type]Series() 훅으로 접근할 수 있습니다. 이 훅들은 series의 순서와 데이터 포인트, 색상 등을 포함한 구성 정보를 반환합니다.

이 정보를 사용해 사용자 지정 차트를 만들 수 있습니다. 예를 들어 useLineSeries()를 사용해 Line Chart의 series를 얻고 각 series의 최소값과 최대값 표시기를 표시할 수 있습니다:

import * as React from 'react';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { LinePlot } from '@mui/x-charts/LineChart';
import { useLineSeries, useXAxis, useXScale, useYScale } from '@mui/x-charts/hooks';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ChartsDataProvider } from '@mui/x-charts/ChartsDataProvider';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { DefaultizedLineSeriesType } from '@mui/x-charts/models';

function ExtremaLabels() {
  const lineSeries = useLineSeries();

  if (!lineSeries) {
    return null;
  }

  return (
    <React.Fragment>
      {lineSeries.map((series) => (
        <SingleSeriesExtremaLabels series={series} />
      ))}
    </React.Fragment>
  );
}

function SingleSeriesExtremaLabels({
  series,
}: {
  series: DefaultizedLineSeriesType;
}) {
  const xAxis = useXAxis('x');

  const min = series.data.reduce(
    (acc, value, index) =>
      value != null && value < acc.value ? { index, value } : acc,
    { index: -1, value: Infinity },
  );
  const max = series.data.reduce(
    (acc, value, index) =>
      value != null && value > acc.value ? { index, value } : acc,
    { index: -1, value: -Infinity },
  );

  return (
    <React.Fragment>
      <PointLabel
        x={xAxis.data?.[min.index]}
        y={min.value}
        placement="below"
        color={series.color}
      />
      <PointLabel
        x={xAxis.data?.[max.index]}
        y={max.value}
        placement="above"
        color={series.color}
      />
    </React.Fragment>
  );
}

function PointLabel({
  x,
  y,
  placement,
  color,
}: {
  x: number;
  y: number;
  placement: 'above' | 'below';
  color: string;
}) {
  const xAxisScale = useXScale();
  const yAxisScale = useYScale();

  const left = xAxisScale(x) ?? 0;
  const top = (yAxisScale(y) ?? 0) + (placement === 'below' ? 20 : -20);

  return (
    <Box
      sx={{
        position: 'absolute',
        left,
        top,
        translate: '-50% -50%',
        border: `2px solid ${color}`,
        borderRadius: 1,
        px: 1,
      }}
    >
      <Typography variant="caption">{y}</Typography>
    </Box>
  );
}

export default function SeriesDemo() {
  return (
    <Box sx={{ position: 'relative', width: '100%' }}>
      <ChartsDataProvider
        xAxis={[{ id: 'x', data: [1, 2, 3, 5, 8, 10], height: 28 }]}
        series={[
          { id: 'a', type: 'line', data: [4, 6, 4, 9, 3, 5] },
          { id: 'b', type: 'line', data: [3, 7, 8, 2, 4, 9] },
        ]}
        yAxis={[{ min: 0, max: 10 }]}
        height={300}
      >
        <ChartsSurface>
          <LinePlot />
          <ChartsXAxis />
          <ChartsYAxis />
        </ChartsSurface>
        <ExtremaLabels />
      </ChartsDataProvider>
    </Box>
  );
}

TypeScript로 사용자 지정 slot props (Custom slot props with TypeScript)

사용자 지정 컴포넌트가 제대로 작동하기 위해 추가 props가 필요하면 TypeScript가 타입 오류를 발생시킬 수 있습니다. 이 타입 오류를 해결하려면 모듈 확장(module augmentation)을 사용해 props 인터페이스를 확장하세요.

덮어쓸 수 있는(overridable) 인터페이스의 이름은 다음과 같은 패턴을 사용합니다:

`${slotNameInPascalCase}PropsOverrides`;

예를 들어 tooltip 슬롯의 경우 인터페이스 이름은 TooltipPropsOverrides입니다.

다음 파일들은 Charts 패키지의 모든 overridable 인터페이스를 나열합니다:

// augment the props for the tooltip slot
declare module '@mui/x-charts' {
  interface TooltipPropsOverrides {
    someCustomString: string;
    someCustomNumber: number;
  }
}

<LineChart
  series={[{ data: [1, 2, 3] }]}
  slots={{
    // custom component passed to the tooltip slot
    tooltip: CustomTooltip,
  }}
  slotProps={{
    tooltip: {
      // props used by CustomTooltip
      someCustomString: 'Hello',
      someCustomNumber: 42,
    },
  }}
/>;
// augment the props for a pro-only slot (heatmap cell)
declare module '@mui/x-charts-pro' {
  interface CellPropsOverrides {
    someCustomString: string;
    someCustomNumber: number;
  }
}

<Heatmap
  xAxis={[{ data: [1, 2, 3] }]}
  yAxis={[{ data: [1, 2, 3] }]}
  series={[{ data: [[0, 0, 1]] }]}
  slots={{
    // custom component passed to the cell slot
    cell: CustomHeatmapCell,
  }}
  slotProps={{
    cell: {
      // props used by CustomHeatmapCell
      someCustomString: 'Hello',
      someCustomNumber: 42,
    },
  }}
/>;
// augment the props for a premium-only slot (radial line highlight)
declare module '@mui/x-charts-premium' {
  interface RadialLineHighlightPropsOverrides {
    someCustomString: string;
    someCustomNumber: number;
  }
}

<RadialLineChart
  series={[{ data: [1, 2, 3] }]}
  radiusAxis={[{ data: [1, 2, 3] }]}
  rotationAxis={[{ data: [0, 120, 240] }]}
  slots={{
    // custom component passed to the radialLineHighlight slot
    radialLineHighlight: CustomRadialLineHighlight,
  }}
  slotProps={{
    radialLineHighlight: {
      // props used by CustomRadialLineHighlight
      someCustomString: 'Hello',
      someCustomNumber: 42,
    },
  }}
/>;

:::info 확장은 항상 인터페이스가 원래 선언된 모듈을 대상으로 합니다. 위의 Pro와 Premium 탭은 예제 슬롯(cell, radialLineHighlight)이 해당 패키지에 선언되어 있기 때문에 @mui/x-charts-pro와 @mui/x-charts-premium을 확장합니다. 여러 tier에서 공유되는 슬롯(tooltip, legend, toolbar 등)은 @mui/x-charts에 선언되어 있습니다 — 어떤 차트를 사용하든 declare module '@mui/x-charts'로 확장하세요. :::

HTML 컴포넌트 (HTML components)

ChartsDataProvider를 사용해 어떤 컴포넌트에서든 차트 데이터에 접근할 수 있습니다. 이를 통해 데이터와 상호작용하는 HTML 컴포넌트를 만들 수 있습니다.

다음 예제에서 MyCustomLegend 컴포넌트가 series 이름과 색상을 표시하는 것에 주목하세요. 이것은 임의로 사용자 지정할 수 있는 HTML <table> 요소를 만듭니다.

import Box from '@mui/material/Box';
import { useLegend } from '@mui/x-charts/hooks';
import { ChartsDataProvider } from '@mui/x-charts/ChartsDataProvider';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { BarPlot } from '@mui/x-charts/BarChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';

function MyCustomLegend() {
  const { items } = useLegend();
  return (
    <table
      style={{
        marginLeft: 40,
        marginRight: 40,
      }}
    >
      <tbody>
        {items.map((item) => {
          return (
            <tr key={item.seriesId}>
              <td aria-hidden>
                <div
                  style={{
                    background: item.color,
                    height: 10,
                    width: 10,
                    marginRight: 10,
                    flexShrink: 0,
                    borderRadius: 5,
                  }}
                />
              </td>
              <td>{`${item.label}`}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

const veryLongText =
  "Second Series. You should always try to avoid long sentences. But oftentimes, it's not possible. So, we need to handle them gracefully. This is a very long sentence that should be fully readable.";

export default function HtmlLegend() {
  return (
    <Box sx={{ height: 400, display: 'flex', flexDirection: 'column' }}>
      <ChartsDataProvider
        series={[
          { label: 'First Series', type: 'bar', data: [100, 200] },
          { label: veryLongText, type: 'bar', data: [45, 333] },
        ]}
        xAxis={[{ data: ['A', 'B'], scaleType: 'band', id: 'x-axis', height: 28 }]}
      >
        <ChartsSurface>
          <BarPlot />
          <ChartsXAxis axisId="x-axis" />
          <ChartsYAxis />
        </ChartsSurface>
        <MyCustomLegend />
      </ChartsDataProvider>
    </Box>
  );
}

:::warning HTML 컴포넌트는 SVG 계층 구조의 일부가 아닙니다. 즉, HTML과 SVG가 섞이지 않도록 ChartsSurface 컴포넌트 바깥에 있어야 하고, 데이터에 접근하려면 ChartsDataProvider 컴포넌트 안에 있어야 합니다. :::

ChartsClipPath API

데모 (Demos)

이 React 컴포넌트의 사용법에 대한 예시와 자세한 내용은 컴포넌트 데모 페이지를 참고하세요:

가져오기 (Import)

import { ChartsClipPath } from '@mui/x-charts/ChartsClipPath';
// or
import { ChartsClipPath } from '@mui/x-charts';
// or
import { ChartsClipPath } from '@mui/x-charts-pro';
// or
import { ChartsClipPath } from '@mui/x-charts-premium';

Props

Name Type Default Required Description
id string - Yes
offset { bottom?: number, left?: number, right?: number, top?: number } - No

Note: ref는 루트 요소로 전달됩니다.

소스 코드 (Source code)

이 페이지에서 찾지 못한 정보가 있다면 컴포넌트 구현을 살펴보세요.

ChartsSurface API

데모 (Demos)

이 React 컴포넌트의 사용법에 대한 예시와 자세한 내용은 컴포넌트 데모 페이지를 참고하세요:

가져오기 (Import)

import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
// or
import { ChartsSurface } from '@mui/x-charts';
// or
import { ChartsSurface } from '@mui/x-charts-pro';
// or
import { ChartsSurface } from '@mui/x-charts-premium';

Props

Name Type Default Required Description
desc string - No
title string - No

Note: ref는 루트 요소로 전달됩니다.

제공된 다른 모든 props는 루트 요소(네이티브 요소)에 전달됩니다.

CSS

규칙 이름 (Rule name)

Global class Rule name Description
- root 루트 요소에 적용되는 스타일.

소스 코드 (Source code)

이 페이지에서 찾지 못한 정보가 있다면 컴포넌트 구현을 살펴보세요.

더 알아보기 (Learn more)