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

Charts - 브러시

원문 보기 위키 갱신

Charts - 브러시 (Brush)

사용자가 차트에서 클릭·드래그로 영역을 선택할 수 있게 해줘요. 브러시 상호작용으로 정의된 범위의 추세나 클러스터를 강조하거나, 데이터 포인트를 선택해 추가 조사·편집·주석을 달거나, 선택 영역에 기반한 콜백을 트리거하는 데 활용할 수 있어요.

출처: MUI X documentation

본문

브러시 상호작용은 사용자가 클릭·드래그로 차트 영역을 선택하게 해줘요. 선택의 시작 위치와 현재 위치를 캡처하며, 이를 다음과 같이 사용할 수 있어요:

  • 정의된 범위 내의 추세나 클러스터 강조하기

  • 추가 조사, 편집, 또는 주석을 위해 데이터 포인트 선택하기

  • 선택 영역에 기반해 콜백 또는 커스텀 이벤트 트리거하기

브러시는 다음 차트 유형에서 사용할 수 있어요:

  • LineChart
  • BarChart
  • ScatterChart

시각적 피드백은 ChartsBrushOverlay 컴포넌트를 통해 제공돼요.

브러시 기능 구현하기

Cartesian 차트에서 brushConfig={{ enabled: true }}를 설정하면 브러시를 활성화할 수 있어요.

기본적으로 브러시에는 시각적 피드백이 없어요. 선택 영역을 표시하려면 ChartsBrushOverlay 컴포넌트를 차트의 자식으로 추가할 수 있어요.

커스텀 상호작용을 만들려면 아래 Custom overlay 섹션에 나온 것처럼 useBrush() 훅을 사용할 수 있어요.

import { BarChart } from '@mui/x-charts/BarChart';
import { ChartsBrushOverlay } from '@mui/x-charts/ChartsBrushOverlay';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';

export default function BrushBasic() {
  return (
    <Box sx={{ width: '100%' }}>
      <Typography variant="body2" sx={{ mb: 2 }}>
        Click and drag on the chart to see the brush selection overlay.
      </Typography>
      <BarChart
        height={300}
        series={[
          {
            data: [4, 8, 6, 12, 9, 15, 11, 14, 13, 18, 16, 20],
            label: 'Sales',
          },
        ]}
        brushConfig={{ enabled: true }}
        xAxis={[{ data: xAxisData }]}
      >
        <ChartsBrushOverlay />
      </BarChart>
    </Box>
  );
}

const xAxisData = [
  'Jan',
  'Feb',
  'Mar',
  'Apr',
  'May',
  'Jun',
  'Jul',
  'Aug',
  'Sep',
  'Oct',
  'Nov',
  'Dec',
];

커스터마이징 예시

커스텀 오버레이

useBrush() 훅을 사용하는 자신만의 컴포넌트를 만들어 커스텀 브러시 오버레이를 만들 수 있어요. 아래 예시는 시작 위치와 끝 위치의 값, 그리고 그 사이의 차이와 퍼센트 변화를 표시해요.

import { LineChart } from '@mui/x-charts/LineChart';
import {
  useBrush,
  useDrawingArea,
  useLineSeries,
  useXScale,
} from '@mui/x-charts/hooks';
import { useTheme } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';

function CustomBrushOverlay() {
  const theme = useTheme();
  const drawingArea = useDrawingArea();
  const brush = useBrush();
  const xScale = useXScale<'point'>();
  const series = useLineSeries('marketValue');

  if (!brush || !series) {
    return null;
  }

  const { left, top, width, height } = drawingArea;

  // 좌표를 드로잉 영역 안으로 제한
  const clampX = (x: number) => Math.max(left, Math.min(left + width, x));
  const clampedStartX = clampX(brush.start.x!);
  const clampedCurrentX = clampX(brush.current.x!);

  const minX = Math.min(clampedStartX, clampedCurrentX);
  const maxX = Math.max(clampedStartX, clampedCurrentX);
  const rectWidth = maxX - minX;

  const color = theme.palette.primary.main;

  if (rectWidth < 1) {
    return null;
  }

  const getIndex = (x: number) =>
    Math.floor(
      (x - Math.min(...xScale.range()) + xScale.step() / 2) / xScale.step(),
    );
  // x 위치에 기반해 대략적인 데이터 인덱스를 계산
  const startIndex = getIndex(clampedStartX);
  const currentIndex = getIndex(clampedCurrentX);

  const startValue = series.data[startIndex]!;
  const currentValue = series.data[currentIndex]!;
  const difference = currentValue - startValue;
  const percentChange = ((difference / startValue) * 100).toFixed(2);

  // 날짜 라벨 가져오기
  const startDate = (xScale.domain()[startIndex] as string) || '';
  const currentDate = (xScale.domain()[currentIndex] as string) || '';

  return (
    <g>
      {/* 시작 선 */}
      <line
        x1={clampedStartX}
        y1={top}
        x2={clampedStartX}
        y2={top + height}
        stroke={color}
        strokeWidth={2}
        strokeDasharray="5,5"
        pointerEvents="none"
      />

      {/* 현재 선 */}
      <line
        x1={clampedCurrentX}
        y1={top}
        x2={clampedCurrentX}
        y2={top + height}
        stroke={color}
        strokeWidth={2}
        strokeDasharray="5,5"
        pointerEvents="none"
      />

      {/* 선택 사각형 */}
      <rect
        x={minX}
        y={top}
        width={rectWidth}
        height={height}
        fill={color}
        fillOpacity={0.1}
        pointerEvents="none"
      />

      {/* 시작 라벨 */}
      <g transform={`translate(${clampedStartX}, ${top + 15})`}>
        <rect x={-30} y={0} width={60} height={40} fill={color} rx={4} />
        {/* 날짜 라벨 */}
        <text x={0} y={16} textAnchor="middle" fill="white" fontSize={10}>
          {startDate}
        </text>
        {/* 값 라벨 */}
        <text
          x={0}
          y={32}
          textAnchor="middle"
          fill="white"
          fontSize={11}
          fontWeight="bold"
        >
          {startValue.toFixed(2)}
        </text>
      </g>

      {/* 끝 라벨 */}
      <g transform={`translate(${clampedCurrentX}, ${top + 15})`}>
        <rect x={-30} y={0} width={60} height={40} fill={color} rx={4} />
        {/* 날짜 라벨 */}
        <text x={0} y={16} textAnchor="middle" fill="white" fontSize={10}>
          {currentDate}
        </text>
        {/* 값 라벨 */}
        <text
          x={0}
          y={32}
          textAnchor="middle"
          fill="white"
          fontSize={11}
          fontWeight="bold"
        >
          {currentValue.toFixed(2)}
        </text>
      </g>

      {/* 가운데 차이 라벨 */}
      <g transform={`translate(${(minX + maxX) / 2}, ${top + height - 30})`}>
        <rect
          x={-50}
          y={0}
          width={100}
          height={26}
          fill={
            difference >= 0 ? theme.palette.success.main : theme.palette.error.main
          }
          rx={4}
        />
        <text
          x={0}
          y={17}
          textAnchor="middle"
          fill="white"
          fontSize={12}
          fontWeight="bold"
        >
          {difference >= 0 ? '+' : ''}
          {difference.toFixed(2)} ({percentChange}%)
        </text>
      </g>
    </g>
  );
}

const marketData = [
  100, 96.56, 97.04, 98.95, 102.66, 106.18, 107.76, 109.78, 113.57, 111.54, 107.69,
  104.58, 106.62, 103.81, 104.46, 105.14, 108.94, 112.81, 112.62, 117.52, 122.17,
  122.11, 121.44, 122.5, 125.42, 127.46, 129.21, 124.71, 125.0, 125.28, 125.15,
  125.06, 120.48, 115.83, 116.47, 119.58, 118.99, 123.46, 126.83, 130.84, 131.12,
  131.31, 129.14, 133.35, 130.15, 129.02, 132.57, 136.1, 139.33, 139.66,
];
const dates = Array.from({ length: 50 }, (_, i) => {
  const date = new Date(2024, 0, i + 1);
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
});

export default function BrushCustomOverlay() {
  return (
    <Box sx={{ width: '100%' }}>
      <Typography variant="body2" sx={{ mb: 2 }}>
        Custom brush overlay showing the values at start and end positions, and the
        difference between them.
      </Typography>
      <LineChart
        height={300}
        series={[
          {
            data: marketData,
            label: 'Market Value',
            id: 'marketValue',
          },
        ]}
        brushConfig={{ enabled: true }}
        xAxis={[
          {
            data: dates,
            scaleType: 'point',
          },
        ]}
      >
        <CustomBrushOverlay />
      </LineChart>
    </Box>
  );
}

데이터 선택

브러시를 사용해 선택 영역 안의 데이터 포인트를 선택하고 표시할 수 있어요. 아래 예시는 드래그로 포인트를 선택할 수 있는 산점도(scatter) 차트로, 선택된 포인트는 차트 아래에 표시돼요.

import * as React from 'react';
import { ChartsDataProvider } from '@mui/x-charts/ChartsDataProvider';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ScatterPlot } from '@mui/x-charts/ScatterChart';
import { ChartsAxis } from '@mui/x-charts/ChartsAxis';
import {
  useBrush,
  useScatterSeries,
  useXScale,
  useYScale,
} from '@mui/x-charts/hooks';
import { ChartsBrushOverlay } from '@mui/x-charts/ChartsBrushOverlay';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';

const scatterData = [
  { x: 5, y: 12, id: 1 },
  { x: 12, y: 18, id: 2 },
  { x: 18, y: 9, id: 3 },
  { x: 25, y: 22, id: 4 },
  { x: 32, y: 15, id: 5 },
  { x: 40, y: 28, id: 6 },
  { x: 48, y: 20, id: 7 },
  { x: 55, y: 35, id: 8 },
  { x: 62, y: 25, id: 9 },
  { x: 70, y: 40, id: 10 },
  { x: 78, y: 32, id: 11 },
  { x: 85, y: 45, id: 12 },
  { x: 15, y: 30, id: 13 },
  { x: 35, y: 38, id: 14 },
  { x: 50, y: 42, id: 15 },
  { x: 65, y: 36, id: 16 },
  { x: 22, y: 25, id: 17 },
  { x: 44, y: 33, id: 18 },
  { x: 58, y: 29, id: 19 },
  { x: 72, y: 37, id: 20 },
];

const empty: { x: number; y: number; id: number }[] = [];

function ChartContent() {
  return (
    <React.Fragment>
      <ScatterPlot />
      <ChartsAxis />
      <ChartsBrushOverlay />
    </React.Fragment>
  );
}

function SelectedPointsList() {
  const brush = useBrush();
  const series = useScatterSeries('data');
  const xScale = useXScale<'linear'>();
  const yScale = useYScale<'linear'>();

  const selectedData = React.useMemo(() => {
    if (!brush || !series || !xScale || !yScale) {
      return empty;
    }

    const { start, current } = brush;

    // 최소/최대 x, y 위치 가져오기
    const minX = Math.min(start.x!, current.x!);
    const maxX = Math.max(start.x!, current.x!);
    const minY = Math.min(start.y!, current.y!);
    const maxY = Math.max(start.y!, current.y!);

    // 픽셀 좌표를 다시 데이터 값으로 변환
    const minDataX = xScale.invert(minX);
    const maxDataX = xScale.invert(maxX);
    const minDataY = yScale.invert(maxY);
    const maxDataY = yScale.invert(minY);

    // 브러시 선택 범위 안의 데이터 포인트 필터링
    const d = series.data
      .map((point, index) => ({
        x: point.x as number,
        y: point.y as number,
        id: (point.id as number) ?? index + 1,
      }))
      .filter((point) => {
        return (
          point.x >= (minDataX as number) &&
          point.x <= (maxDataX as number) &&
          point.y >= (minDataY as number) &&
          point.y <= (maxDataY as number)
        );
      });

    return d;
  }, [brush, series, xScale, yScale]);

  if (selectedData.length === 0) {
    return (
      <Box sx={{ mt: 3 }}>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          No points selected. Drag on the chart to select data points.
        </Typography>
      </Box>
    );
  }

  return (
    <Box sx={{ mt: 3 }}>
      <Typography variant="subtitle2" gutterBottom>
        Selected Points ({selectedData.length}):
      </Typography>
      <Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap', gap: 1 }}>
        {selectedData.map((point) => (
          <Chip
            key={point.id}
            label={`#${point.id}: (${point.x}, ${point.y})`}
            color="primary"
            variant="outlined"
            size="small"
          />
        ))}
      </Stack>
    </Box>
  );
}

export default function BrushScatterList() {
  return (
    <Box sx={{ width: '100%' }}>
      <Typography variant="body2" sx={{ mb: 2 }}>
        Drag to select points on the scatter chart. Selected points will be displayed
        below.
      </Typography>
      <ChartsDataProvider
        series={[
          {
            type: 'scatter',
            data: scatterData,
            id: 'data',
            label: 'Data Points',
          },
        ]}
        xAxis={[{ id: 'x-axis', min: 0, max: 100 }]}
        yAxis={[{ id: 'y-axis', min: 0, max: 50 }]}
        height={400}
        brushConfig={{ enabled: true }}
      >
        <ChartsSurface>
          <ChartContent />
        </ChartsSurface>
        <SelectedPointsList />
      </ChartsDataProvider>
    </Box>
  );
}

useBrush() 훅 사용하기

useBrush() 훅은 현재 브러시 상태에 대한 접근을 제공해요. 다음 항목을 가진 객체를 반환해요:

  • start: 브러시 선택의 시작 지점 ({ x: number, y: number } | null)
  • current: 브러시 선택의 현재 지점 ({ x: number, y: number } | null)
import { useBrush } from '@mui/x-charts/hooks';

function MyCustomOverlay() {
  const brush = useBrush();

  // 진행 중인 브러시가 없음
  if (!brush) {
    return null;
  }

  const { start, current } = brush;

  // start.x, start.y - 브러시가 시작된 좌표
  // current.x, current.y - 브러시의 현재 좌표

  return <g>{/* Your custom overlay */}</g>;
}

설정(Configuration)

brushConfig prop은 다음 boolean 옵션을 가진 객체를 받아요:

  • enabled (기본값: false): 브러시 상호작용이 활성화되는지 여부
  • preventTooltip (기본값: true): 브러시 상호작용 중에 툴팁 표시를 막을지 여부
  • preventHighlight (기본값: true): 브러시 상호작용 중에 하이라이트를 막을지 여부
<LineChart
  brushConfig={{
    enabled: true,
    preventTooltip: true,
    preventHighlight: true,
  }}
  // ... other props
/>

더 알아보기 (Learn more)