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

Charts - 막대 차트

원문 보기 위키 갱신

막대 차트는 막대의 길이와 공통 기준선을 이용해서 이산 범주와 수량을 비교해 보여주는 차트예요.

출처: MUI X documentation

본문

개요

막대 차트는 공통 기준선에서의 막대 길이로 수량을 나타내서 이산 범주들을 비교해 줘요. 범주 간의 크기를 비교하거나, 추세를 강조하거나, 비율을 한눈에 비교하기 좋아요. 범주는 점진적(예를 들어 시간 구간)일 수도 있고 독립적(예를 들어 제품, 국가, 연령대)일 수도 있어요.

아래 가로 막대 차트는 여러 유럽 국가의 투표 참여율을 비교해 줘요.

import * as React from 'react';
import { useTheme, styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import { BarChart, type BarLabelProps, type BarProps } from '@mui/x-charts/BarChart';
import { useAnimate, useAnimateBar, useDrawingArea } from '@mui/x-charts/hooks';
import { PiecewiseColorLegend } from '@mui/x-charts/ChartsLegend';
import { interpolateObject } from '@mui/x-charts-vendor/d3-interpolate';
import Box from '@mui/material/Box';
import votesTurnout from '../dataset/votes.json';

export default function ShinyBarChartHorizontal() {
  return (
    <Box sx={{ width: '100%' }}>
      <Typography sx={{ marginBottom: 2 }}>
        European countries with lowest & highest voter turnout
      </Typography>
      <BarChart
        height={300}
        dataset={votesTurnout}
        series={[
          {
            id: 'turnout',
            dataKey: 'turnout',
            stack: 'voter turnout',
            valueFormatter: (value: number | null) => `${value}%`,
            barLabel: (v) => `${v.value}%`,
          },
        ]}
        layout="horizontal"
        xAxis={[
          {
            id: 'color',
            min: 0,
            max: 100,
            colorMap: {
              type: 'piecewise',
              thresholds: [50, 85],
              colors: ['#d32f2f', '#78909c', '#1976d2'],
            },
            valueFormatter: (value: number) => `${value}%`,
          },
        ]}
        yAxis={[
          {
            scaleType: 'band',
            dataKey: 'country',
            width: 140,
          },
        ]}
        slots={{
          legend: PiecewiseColorLegend,
          barLabel: BarLabelAtBase,
          bar: BarShadedBackground,
        }}
        slotProps={{
          legend: {
            axisDirection: 'x',
            markType: 'square',
            labelPosition: 'inline-start',
            labelFormatter: ({ index }) => {
              if (index === 0) {
                return 'lowest turnout';
              }
              if (index === 1) {
                return 'average';
              }
              return 'highest turnout';
            },
          },
        }}
      />
    </Box>
  );
}

export function BarShadedBackground(props: BarProps) {
  const {
    ownerState,
    skipAnimation,
    id,
    dataIndex,
    xOrigin,
    yOrigin,
    seriesId,
    ...other
  } = props;
  const theme = useTheme();

  const animatedProps = useAnimateBar(props);
  const { width } = useDrawingArea();
  return (
    <React.Fragment>
      <rect
        {...other}
        fill={(theme.vars || theme).palette.text.primary}
        opacity={theme.palette.mode === 'dark' ? 0.05 : 0.1}
        x={other.x}
        width={width}
      />
      <rect
        {...other}
        filter={ownerState.isHighlighted ? 'brightness(120%)' : undefined}
        opacity={ownerState.isFaded ? 0.3 : 1}
        data-highlighted={ownerState.isHighlighted || undefined}
        data-faded={ownerState.isFaded || undefined}
        {...animatedProps}
      />
    </React.Fragment>
  );
}

const Text = styled('text')(({ theme }) => ({
  ...theme?.typography?.body2,
  stroke: 'none',
  fill: (theme.vars || theme).palette.common.white,
  transition: 'opacity 0.2s ease-in, fill 0.2s ease-in',
  textAnchor: 'start',
  dominantBaseline: 'central',
  pointerEvents: 'none',
  fontWeight: 600,
}));

function BarLabelAtBase(props: BarLabelProps) {
  const {
    seriesId,
    dataIndex,
    color,
    isFaded,
    isHighlighted,
    classes,
    xOrigin,
    yOrigin,
    x,
    y,
    width,
    height,
    layout,
    skipAnimation,
    ...otherProps
  } = props;

  const animatedProps = useAnimate(
    { x: xOrigin + 8, y: y + height / 2 },
    {
      initialProps: { x: xOrigin, y: y + height / 2 },
      createInterpolator: interpolateObject,
      transformProps: (p) => p,
      applyProps: (element: SVGTextElement, p) => {
        element.setAttribute('x', p.x.toString());
        element.setAttribute('y', p.y.toString());
      },
      skip: skipAnimation,
    },
  );

  return <Text {...otherProps} {...animatedProps} />;
}

기본 개념

막대 차트를 만들려면 다음이 필요해요:

  • 하나의 범주형 차원(예: 세로 막대에서는 x축, 가로 막대에서는 y축)
  • 각 막대의 길이를 정하는 하나 이상의 숫자 값

막대 차트 시리즈는 값 배열을 가진 data 속성을 반드시 포함해야 해요.

xAxis prop으로 막대의 틱(tick)을 지정할 수 있어요. 범주 축은 scaleType='band'를 사용하며, 그 data는 시리즈와 길이가 같아야 해요.

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

export default function BasicBars() {
  return (
    <BarChart
      xAxis={[{ data: ['group A', 'group B', 'group C'] }]}
      series={[{ data: [4, 3, 5] }, { data: [1, 6, 3] }, { data: [2, 5, 6] }]}
      height={300}
    />
  );
}

데이터셋 사용하기

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

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

import { BarChart } from '@mui/x-charts/BarChart';
import { dataset, valueFormatter } from '../dataset/weather';

const chartSetting = {
  yAxis: [
    {
      label: 'rainfall (mm)',
      width: 60,
    },
  ],
  height: 300,
};

export default function BarsDataset() {
  return (
    <BarChart
      dataset={dataset}
      xAxis={[{ dataKey: 'month' }]}
      series={[
        { dataKey: 'london', label: 'London', valueFormatter },
        { dataKey: 'paris', label: 'Paris', valueFormatter },
        { dataKey: 'newYork', label: 'New York', valueFormatter },
        { dataKey: 'seoul', label: 'Seoul', valueFormatter },
      ]}
      {...chartSetting}
    />
  );
}

막대 크기

categoryGapRatio와 barGapRatio 속성으로 막대의 크기를 정의할 수 있어요.

categoryGapRatio는 두 범주 사이의 간격을 정의해요. 이 비율은 간격의 크기를 범주(막대가 차지하는 공간)의 크기로 나눠서 구해요.

barGapRatio는 같은 범주 안의 두 막대 사이의 간격을 정의해요. 간격의 크기를 막대의 크기로 나눈 값이에요. 그래서 값이 1이면 막대 사이에 막대 너비와 같은 간격이 생겨요. 값이 -1이면 막대가 겹치게 돼요.

import Typography from '@mui/material/Typography';
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
import { BarChart } from '@mui/x-charts/BarChart';
import { balanceSheet, addLabels } from './netflixsBalanceSheet';

const series = addLabels([
  { dataKey: 'totAss' },
  { dataKey: 'totLia', stack: 'passive' },
  { dataKey: 'totEq', stack: 'passive' },
]);

export default function BarGap() {
  return (
    <ChartsUsageDemo
      componentName="Bar gap"
      data={{
        categoryGapRatio: {
          knob: 'number',
          defaultValue: 0.3,
          step: 0.1,
          min: 0,
          max: 1,
        },
        barGapRatio: {
          knob: 'number',
          defaultValue: 0.1,
          step: 0.1,
          min: -2,
          max: 5,
        },
      }}
      renderDemo={(props) => (
        <div style={{ width: '100%' }}>
          <Typography>Netflix balance sheet</Typography>
          <BarChart
            dataset={balanceSheet}
            series={series}
            height={300}
            xAxis={[
              {
                dataKey: 'year',
                categoryGapRatio: props.categoryGapRatio,
                barGapRatio: props.barGapRatio,
              },
            ]}
            yAxis={[{ valueFormatter: (v: number) => `$ ${v / 1000000}B` }]}
            hideLegend
          />
        </div>
      )}
      getCode={({ props }) => {
        return `import { BarChart } from '@mui/x-charts/BarChart';

<BarChart
  // ...
  xAxis={[
    {
      scaleType: 'band',
      data: ['Page 1', 'Page 2', 'Page 3'],
      categoryGapRatio: ${props.categoryGapRatio},
      barGapRatio: ${props.barGapRatio},
    },
  ]}
/>`;
      }}
    />
  );
}

누적(Stacking)

막대 시리즈는 stack이라는 문자열 속성을 받아요. 같은 stack 값을 가진 시리즈들은 서로 위에 쌓여요.

import Typography from '@mui/material/Typography';
import { BarChart, BarChartProps } from '@mui/x-charts/BarChart';
import { addLabels, balanceSheet, valueFormatter } from './netflixsBalanceSheet';

export default function StackBars() {
  return (
    <div style={{ width: '100%' }}>
      <Typography>Netflix balance sheet</Typography>
      <BarChart
        dataset={balanceSheet}
        series={addLabels([
          { dataKey: 'currAss', stack: 'assets' },
          { dataKey: 'nCurrAss', stack: 'assets' },
          { dataKey: 'curLia', stack: 'liability' },
          { dataKey: 'nCurLia', stack: 'liability' },
          { dataKey: 'capStock', stack: 'equity' },
          { dataKey: 'retEarn', stack: 'equity' },
          { dataKey: 'treas', stack: 'equity' },
        ])}
        xAxis={[{ dataKey: 'year' }]}
        {...config}
      />
    </div>
  );
}

const config: Partial<BarChartProps> = {
  height: 350,
  margin: { left: 0 },
  yAxis: [{ width: 50, valueFormatter }],
  hideLegend: true,
};

누적 전략

stackOffset와 stackOrder 속성을 사용해서 시리즈가 어떻게 쌓일지 정의할 수 있어요.

기본적으로는 정의한 순서대로 쌓이며, 양수 값은 0 위에, 음수 값은 0 아래에 쌓여요.

자세한 내용은 스태킹 문서를 참고해 주세요.

레이아웃

막대 방향

layout="horizontal" prop을 사용하면 막대 차트를 가로 레이아웃으로 렌더링할 수 있어요. 커스텀 컴포넌트를 구성 중이라면 각 막대 시리즈 객체에 layout: 'horizontal' 속성을 설정해 주세요.

import { BarChart } from '@mui/x-charts/BarChart';
import { dataset, valueFormatter } from '../dataset/weather';

const chartSetting = {
  xAxis: [
    {
      label: 'rainfall (mm)',
    },
  ],
  height: 400,
  margin: { left: 0 },
};

export default function HorizontalBars() {
  return (
    <BarChart
      dataset={dataset}
      yAxis={[{ scaleType: 'band', dataKey: 'month' }]}
      series={[{ dataKey: 'seoul', label: 'Seoul rainfall', valueFormatter }]}
      layout="horizontal"
      {...chartSetting}
    />
  );
}

틱 배치

"band" 스케일을 사용하면 축에 틱 위치를 위한 추가 커스터마이즈 속성이 있어요:

  • tickPlacement — 틱의 위치
  • tickLabelPlacement — 틱에 연결된 레이블의 위치

다음 데모에서 모든 구성 옵션을 테스트해 볼 수 있어요:

import * as React from 'react';
import Stack from '@mui/material/Stack';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import { BarChart } from '@mui/x-charts/BarChart';
import { dataset, valueFormatter } from '../dataset/weather';

type TickParamsSelectorProps = {
  tickPlacement: 'end' | 'start' | 'middle' | 'extremities';
  tickLabelPlacement: 'tick' | 'middle';
  setTickPlacement: React.Dispatch<
    React.SetStateAction<'end' | 'start' | 'middle' | 'extremities'>
  >;
  setTickLabelPlacement: React.Dispatch<React.SetStateAction<'tick' | 'middle'>>;
};

function TickParamsSelector({
  tickPlacement,
  tickLabelPlacement,
  setTickPlacement,
  setTickLabelPlacement,
}: TickParamsSelectorProps) {
  return (
    <Stack
      direction="column"
      sx={{ justifyContent: 'space-between', width: '100%' }}
    >
      <FormControl>
        <FormLabel id="tick-placement-radio-buttons-group-label">
          tickPlacement
        </FormLabel>
        <RadioGroup
          row
          aria-labelledby="tick-placement-radio-buttons-group-label"
          name="tick-placement"
          value={tickPlacement}
          onChange={(event) =>
            setTickPlacement(
              event.target.value as 'start' | 'end' | 'middle' | 'extremities',
            )
          }
        >
          <FormControlLabel value="start" control={<Radio />} label="start" />
          <FormControlLabel value="end" control={<Radio />} label="end" />
          <FormControlLabel value="middle" control={<Radio />} label="middle" />
          <FormControlLabel
            value="extremities"
            control={<Radio />}
            label="extremities"
          />
        </RadioGroup>
      </FormControl>
      <FormControl>
        <FormLabel id="label-placement-radio-buttons-group-label">
          tickLabelPlacement
        </FormLabel>
        <RadioGroup
          row
          aria-labelledby="label-placement-radio-buttons-group-label"
          name="label-placement"
          value={tickLabelPlacement}
          onChange={(event) =>
            setTickLabelPlacement(event.target.value as 'tick' | 'middle')
          }
        >
          <FormControlLabel value="tick" control={<Radio />} label="tick" />
          <FormControlLabel value="middle" control={<Radio />} label="middle" />
        </RadioGroup>
      </FormControl>
    </Stack>
  );
}

const chartSetting = {
  yAxis: [
    {
      label: 'rainfall (mm)',
      width: 60,
    },
  ],
  series: [{ dataKey: 'seoul', label: 'Seoul rainfall', valueFormatter }],
  height: 300,
  margin: { left: 0 },
};

export default function TickPlacementBars() {
  const [tickPlacement, setTickPlacement] = React.useState<
    'start' | 'end' | 'middle' | 'extremities'
  >('middle');
  const [tickLabelPlacement, setTickLabelPlacement] = React.useState<
    'middle' | 'tick'
  >('middle');

  return (
    <div style={{ width: '100%' }}>
      <TickParamsSelector
        tickPlacement={tickPlacement}
        tickLabelPlacement={tickLabelPlacement}
        setTickPlacement={setTickPlacement}
        setTickLabelPlacement={setTickLabelPlacement}
      />
      <BarChart
        dataset={dataset}
        xAxis={[{ dataKey: 'month', tickPlacement, tickLabelPlacement }]}
        {...chartSetting}
      />
    </div>
  );
}

날짜 축

정렬되고 균등한 간격으로 배치된 날짜를 나타내는 band 축이라면(보통 그렇죠) ordinalTimeTicks를 설정해서 특정 날짜 빈도를 선택할 수 있어요. 이렇게 하면 틱 관리가 달라져요.

축은 band마다 틱 하나를 그리는 대신, 제공된 빈도와 틱 개수에 따라 틱을 렌더링해요.

최소 막대 크기

minBarSize 속성으로 막대의 최소 크기를 설정할 수 있어요. 데이터가 드물거나 차트가 작을 때 막대가 항상 보이게 하고 싶다면 유용한 속성이에요.

minBarSize 속성은 시리즈 값이 null 또는 0이면 무시돼요. 또한 누적된 시리즈에서는 동작하지 않아요.

import * as React from 'react';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Slider from '@mui/material/Slider';
import { BarChart } from '@mui/x-charts/BarChart';

// Create sparse data where some bars would be very small
const sparseData: (number | null)[] = [0.02, 5, null, 7, 0.01, 0, -0.03];

export default function MinBarSize(): React.JSX.Element {
  const [minBarSize, setMinBarSize] = React.useState<number>(10);

  const handleChange = (event: Event, newValue: number | number[]) => {
    if (typeof newValue !== 'number') {
      return;
    }
    setMinBarSize(newValue);
  };

  return (
    <Stack spacing={2} sx={{ justifyContent: 'center', alignItems: 'center' }}>
      <Typography id="min-bar-size-slider" gutterBottom>
        minBarSize: {minBarSize}px
      </Typography>
      <Slider
        value={minBarSize}
        onChange={handleChange}
        aria-labelledby="min-bar-size-slider"
        min={0}
        max={50}
        sx={{ width: 300 }}
      />
      <BarChart
        xAxis={[{ data: sparseData.map((v) => `${v}`), scaleType: 'band' }]}
        series={[{ data: sparseData, minBarSize }]}
        height={300}
        width={400}
      />
    </Stack>
  );
}

로그 스케일

막대 차트는 0부터 데이터 포인트 값까지 막대를 렌더링해요. 그런데 0의 로그는 정의되지 않으므로, 로그 스케일을 가진 y축으로는 막대를 그릴 수 없어요.

이 제약은 symlog 스케일을 사용해서 우회할 수 있어요.

커스터마이즈

그리드

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

자세한 내용은 축—그리드 문서를 참고해 주세요.

import { BarChart } from '@mui/x-charts/BarChart';
import { dataset, valueFormatter } from '../dataset/weather';

const chartSetting = {
  xAxis: [{ label: 'rainfall (mm)' }],
  height: 400,
  margin: { left: 0 },
};

export default function GridDemo() {
  return (
    <BarChart
      dataset={dataset}
      yAxis={[{ scaleType: 'band', dataKey: 'month' }]}
      series={[{ dataKey: 'seoul', label: 'Seoul rainfall', valueFormatter }]}
      layout="horizontal"
      grid={{ vertical: true }}
      {...chartSetting}
    />
  );
}

색상 스케일

다른 차트와 마찬가지로 시리즈 색상을 직접 또는 컬러 팔레트로 수정할 수 있어요.

축의 colorMap으로 값을 색상에 매핑해 색상을 수정할 수도 있어요. 막대 차트는 우선순위에 따라 다음을 사용해요:

  1. 값 축의 색상
  2. band 축의 색상
  3. 시리즈 색상

colorMap 속성에 대해서는 스타일링—값 기반 색상 문서를 참고해 주세요.

import * as React from 'react';
import { BarChart } from '@mui/x-charts/BarChart';
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';

const series = [{ data: [-2, -9, 12, 11, 6, -4] }];

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

  return (
    <Stack direction="column" spacing={1} sx={{ width: '100%', maxWidth: 600 }}>
      <Stack direction="row" spacing={1}>
        <TextField
          select
          sx={{ minWidth: 150 }}
          label="x-axis colorMap"
          value={colorX}
          onChange={(event) =>
            setColorX(
              event.target.value as 'None' | 'piecewise' | 'continuous' | 'ordinal',
            )
          }
        >
          <MenuItem value="None">None</MenuItem>
          <MenuItem value="piecewise">piecewise</MenuItem>
          <MenuItem value="continuous">continuous</MenuItem>
          <MenuItem value="ordinal">ordinal</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>
      </Stack>

      <BarChart
        height={300}
        grid={{ horizontal: true }}
        series={series}
        yAxis={[
          {
            colorMap:
              (colorY === 'continuous' && {
                type: 'continuous',
                min: -10,
                max: 10,
                color: ['red', 'green'],
              }) ||
              (colorY === 'piecewise' && {
                type: 'piecewise',
                thresholds: [0],
                colors: ['red', 'green'],
              }) ||
              undefined,
          },
        ]}
        xAxis={[
          {
            data: [
              new Date(2019, 1, 1),
              new Date(2020, 1, 1),
              new Date(2021, 1, 1),
              new Date(2022, 1, 1),
              new Date(2023, 1, 1),
              new Date(2024, 1, 1),
            ],
            valueFormatter: (value: Date) => value.getFullYear().toString(),
            colorMap:
              (colorX === 'ordinal' && {
                type: 'ordinal',
                colors: [
                  '#ccebc5',
                  '#a8ddb5',
                  '#7bccc4',
                  '#4eb3d3',
                  '#2b8cbe',
                  '#08589e',
                ],
              }) ||
              (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,
          },
        ]}
        margin={{ left: 0 }}
      />
      <HighlightedCode
        code={[
          `<BarChart`,
          '  /* ... */',
          // ColorX
          ...(colorX === 'None' ? ['  xAxis={[{}]}'] : []),
          ...(colorX === 'ordinal'
            ? [
                '  xAxis={[{',
                `    colorMap: {`,
                `      type: 'ordinal',`,
                `      colors: ['#ccebc5', '#a8ddb5', '#7bccc4', '#4eb3d3', '#2b8cbe', '#08589e']`,
                `    }`,
                '  }]}',
              ]
            : []),
          ...(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],`,
                `      colors: ['red', 'green'],`,
                `    }`,
                '  }]}',
              ]
            : []),
          `/>`,
        ].join('\n')}
        language="jsx"
        copyButtonHidden
      />
    </Stack>
  );
}

테두리 반경

막대 차트에 둥근 모서리를 주려면 BarChart에 borderRadius 속성을 설정해 주세요. 양수 값이면 모두 잘 동작하며, 가로 레이아웃, 스택, 음수 값에도 올바르게 적용돼요.

커스텀 컴포넌트를 구성할 때는 BarPlot 컴포넌트에 borderRadius prop을 설정할 수 있어요.

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

export default function BorderRadius() {
  const [layout, setLayout] = React.useState<'horizontal' | 'vertical'>('vertical');
  const [radius, setRadius] = React.useState(10);
  const [reverse, setReverse] = React.useState(false);

  return (
    <Stack direction="column" spacing={1} sx={{ width: '100%', maxWidth: 600 }}>
      <Stack
        direction="row"
        spacing={4}
        sx={{ flexWrap: 'wrap', justifyContent: 'center' }}
      >
        <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
          <Typography gutterBottom>Border Radius</Typography>
          <Slider
            value={radius}
            onChange={(event, value) => setRadius(value as number)}
            valueLabelDisplay="auto"
            min={0}
            max={50}
            sx={{ mt: 2 }}
          />
        </Stack>
        <TextField
          select
          sx={{ minWidth: 150 }}
          label="layout"
          value={layout}
          onChange={(event) =>
            setLayout(event.target.value as 'horizontal' | 'vertical')
          }
        >
          <MenuItem value="horizontal">Horizontal</MenuItem>
          <MenuItem value="vertical">Vertical</MenuItem>
        </TextField>
        <FormControlLabel
          checked={reverse}
          control={
            <Checkbox onChange={(event) => setReverse(event.target.checked)} />
          }
          label="Reverse"
          labelPlacement="end"
        />
      </Stack>
      <BarChart
        series={[
          { dataKey: 'high', label: 'High', layout, stack: 'stack' },
          { dataKey: 'low', label: 'Low', layout, stack: 'stack' },
        ]}
        margin={{ left: 0 }}
        {...getChartSettings(layout, reverse)}
        borderRadius={radius}
      />
      <HighlightedCode
        code={`<BarChart
  // ...
  borderRadius={${radius}}
/>`}
        language="jsx"
        copyButtonHidden
      />
    </Stack>
  );
}

const dataset = [
  [3, -7, '1st'],
  [0, -5, '2nd'],
  [10, 0, '3rd'],
  [9, 6, '4th'],
].map(([high, low, order]) => ({
  high,
  low,
  order,
}));

function getChartSettings(
  layout: 'vertical' | 'horizontal',
  reverse: boolean,
): Partial<BarChartProps> {
  return {
    dataset,
    height: 300,
    xAxis: layout === 'horizontal' ? [{ reverse }] : [{ dataKey: 'order' }],
    yAxis:
      layout === 'horizontal'
        ? [{ scaleType: 'band', dataKey: 'order' }]
        : [{ reverse }],
    slotProps: {
      legend: {
        direction: 'horizontal',
        position: { vertical: 'bottom', horizontal: 'center' },
      },
    },
  };
}

CSS

CSS 선택자를 사용해서 막대 차트 요소를 커스터마이즈할 수 있어요.

각 시리즈는 data-series 속성을 가진 g 요소를 렌더링해요. 이 속성을 사용해서 시리즈별로 요소를 지정할 수 있어요.

import * as React from 'react';
import { BarChart, barClasses } from '@mui/x-charts/BarChart';

const settings = {
  xAxis: [{ data: ['group A', 'group B', 'group C'] }],
  series: [
    { id: '1', data: [4, 3, 5], barLabel: 'value' },
    { id: '2', data: [1, 6, 3], barLabel: 'value' },
    { id: '3', data: [2, 5, 6], barLabel: 'value' },
  ],
  height: 300,
  margin: { left: 0 },
} as const;

export default function BarGradient() {
  return (
    <BarChart
      {...settings}
      sx={{
        [`& .${barClasses.series}[data-series="2"] .${barClasses.element}`]: {
          fill: 'url(#bar-gradient)',
        },
        [`& .${barClasses.seriesLabels}[data-series="2"] .${barClasses.label}`]: {
          fontWeight: 'bold',
        },
      }}
    >
      <defs>
        <Gradient id="bar-gradient" />
      </defs>
    </BarChart>
  );
}

function Gradient(props: React.SVGProps<SVGLinearGradientElement>) {
  return (
    <linearGradient gradientTransform="rotate(90)" {...props}>
      <stop offset="5%" stopColor="gold" />
      <stop offset="95%" stopColor="red" />
    </linearGradient>
  );
}

그라디언트

기본적으로 그라디언트의 단위는 objectBoundingBox로 설정돼요. 막대에 적용하면 그라디언트가 막대의 값과 관계없이 막대 전체 크기를 채우도록 늘어나요.

반면 gradientUnits를 userSpaceOnUse로 설정하면 그라디언트가 차트 전체 크기를 채우도록 늘어나요. userSpaceOnUse에서는 그라디언트 좌표가 SVG를 기준으로 하므로, x1="0"과 x2="100%"인 그라디언트는 SVG 전체 너비에 걸쳐 늘어나요. 이렇게 하면 그라디언트가 막대 크기로 잘리므로, 막대의 값에 따라 그라디언트가 드러나게 돼요.

아래 예제에는 두 개의 그라디언트가 있어요:

  1. 시리즈 color 속성이 gradientUnits="objectBoundingBox"인 그라디언트를 참조하는데, 이건 툴팁, 범례, 시리즈 색상을 참조하는 다른 요소에 적용돼요.
  2. 막대의 fill 속성이 CSS로 오버라이드되어 gradientUnits="userSpaceOnUse"인 그라디언트를 참조해요.

첫 번째 그라디언트는 툴팁과 범례처럼 전체 그라디언트를 보여주는 요소에 사용돼요. 두 번째는 값에 해당하는 그라디언트 부분을 보여주는 막대 자체에 표시돼요.

import * as React from 'react';
import { BarChart, BarChartProps, barClasses } from '@mui/x-charts/BarChart';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import { countryData } from '../dataset/countryData';
import householdSavings from '../dataset/oecdHouseholdSavings2024.json';

/* Source: https://www.oecd.org/en/data/indicators/household-savings.html */
const savings = Object.entries(householdSavings)
  .map(([country, value]) => ({
    country,
    value,
  }))
  .sort((a, b) => a.value - b.value);

const percentageFormatter = new Intl.NumberFormat('en-US', {
  style: 'percent',
  maximumFractionDigits: 1,
});

const settings = {
  height: 600,
  xAxis: [{ label: 'Household Savings (%)' }],
  layout: 'horizontal',
  hideLegend: true,
} satisfies Partial<BarChartProps>;

export default function BarOECDHouseholdSavings() {
  const [gradientUnits, setGradientUnits] = React.useState<
    'objectBoundingBox' | 'userSpaceOnUse'
  >('userSpaceOnUse');

  return (
    <Stack sx={{ width: '100%' }}>
      <Typography variant="h6" sx={{ textAlign: 'center' }}>
        Household Savings in OECD Countries (2016)
      </Typography>
      <FormControl fullWidth>
        <FormLabel id="gradient-units-label">Gradient Units</FormLabel>
        <RadioGroup
          row
          aria-labelledby="gradient-units-label"
          name="gradient-units"
          value={gradientUnits}
          onChange={(event) =>
            setGradientUnits(
              event.target.value as 'objectBoundingBox' | 'userSpaceOnUse',
            )
          }
        >
          <FormControlLabel
            value="objectBoundingBox"
            control={<Radio />}
            label="objectBoundingBox (default)"
          />
          <FormControlLabel
            value="userSpaceOnUse"
            control={<Radio />}
            label="userSpaceOnUse"
          />
        </RadioGroup>
      </FormControl>
      <BarChart
        {...settings}
        yAxis={[
          {
            data: savings.map((v) => v.country),
            valueFormatter: (value: keyof typeof countryData) =>
              countryData[value].country,
            width: 100,
          },
        ]}
        series={[
          {
            label: 'Household Savings',
            data: savings.map((v) => v.value),
            color: 'url(#savings-gradient)',
            valueFormatter: (value) => percentageFormatter.format(value! / 100),
          },
        ]}
        sx={
          gradientUnits === 'userSpaceOnUse'
            ? {
                [`.${barClasses.element}`]: {
                  fill: 'url(#savings-gradient-user-space)',
                },
              }
            : undefined
        }
      >
        <Gradient id="savings-gradient" x1="0" x2="100%" />
        <Gradient
          id="savings-gradient-user-space"
          gradientUnits="userSpaceOnUse"
          x1="150"
          x2="100%"
        />
      </BarChart>
      <Typography variant="caption">Source: Our World in Data</Typography>
    </Stack>
  );
}

function Gradient(props: React.SVGProps<SVGLinearGradientElement>) {
  return (
    <linearGradient x1="0" y1="0%" x2="100%" y2="0%" {...props}>
      <stop offset="0" stopColor="#ff2f1b" />
      <stop offset="0.5" stopColor="#fce202" />
      <stop offset="1" stopColor="#02b32b" />
    </linearGradient>
  );
}

레이블

막대에 레이블을 표시할 수 있어요. 각 막대의 값을 차트에 직접 보여주고 싶을 때 유용해요.

막대 시리즈의 barLabel 속성에 'value'를 제공하면 그 막대의 값이 표시돼요. 또는 barLabel 속성은 막대 항목과 막대에 대한 컨텍스트를 인자로 받는 함수도 받아요.

아래 예제에서 첫 번째 시리즈의 값은 기본 포매터로 표시되고, 두 번째 시리즈의 값은 미국 달러로 포맷돼요. 세 번째 시리즈의 레이블은 숨겨져 있어요.

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

const dollarFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  maximumFractionDigits: 0,
});

export default function BarLabel() {
  return (
    <BarChart
      xAxis={[{ data: ['group A', 'group B', 'group C'] }]}
      series={[
        { data: [4, 3, 5], barLabel: 'value' },
        {
          data: [1, 6, 3],
          barLabel: (item) => dollarFormatter.format(item.value!),
        },
        { data: [2, 5, 6] },
      ]}
      height={300}
      margin={{ left: 0 }}
      yAxis={[{ width: 30 }]}
    />
  );
}

레이블 배치

막대 레이블의 위치를 커스터마이즈하려면 시리즈의 barLabelPlacement 속성을 다음 값 중 하나로 설정해 주세요:

  • center: 레이블이 막대의 중앙에 배치돼요.
  • outside: 레이블이 원점 기준으로 막대의 끝 이후에 배치돼요. 세로 양수 막대의 경우 레이블이 위쪽 가장자리 위에 있어요. 가로 음수 막대의 경우 레이블이 가장 왼쪽 한계의 왼쪽에 있어요.
import { BarChart } from '@mui/x-charts/BarChart';

export default function BarLabelPlacement() {
  return (
    <BarChart
      xAxis={[{ data: ['group A', 'group B', 'group C'] }]}
      series={[
        { data: [1, 1, -4], barLabel: 'value', barLabelPlacement: 'outside' },
        { data: [2, 0, -1], barLabel: 'value', barLabelPlacement: 'center' },
        { data: [3, -1, 4], barLabel: 'value' },
      ]}
      height={300}
      yAxis={[{ width: 30, min: -5 }]}
    />
  );
}

:::info outside 배치를 사용할 때 레이블이 차트 영역에 들어가지 않으면 잘려요. 이를 피하려면 축의 min/max를 각각 줄이거나 늘려서 레이블을 위한 공간을 충분히 만들어 주세요. :::

커스텀 레이블

조건 로직에 따라 레이블을 표시하거나, 변경하거나, 숨기려면 barLabel prop에 함수를 제공해 주세요. 함수가 null을 반환하면 레이블이 표시되지 않아요.

아래 예제는 10보다 큰 값에는 'High' 텍스트를 표시하고, 생성된 막대 높이가 60px 미만인 경우 값을 숨겨요.

import { BarChart, BarItem, BarLabelContext } from '@mui/x-charts/BarChart';

function barLabel(item: BarItem, context: BarLabelContext) {
  if ((item.value ?? 0) > 10) {
    return 'High';
  }
  return context.bar.height < 60 ? null : item.value?.toString();
}

export default function CustomLabels() {
  return (
    <BarChart
      series={[
        {
          data: [4, 2, 5, 4, 1],
          stack: 'A',
          label: 'Series A1',
          barLabel,
        },
        {
          data: [2, 8, 1, 3, 1],
          stack: 'A',
          label: 'Series A2',
          barLabel,
        },
        {
          data: [14, 6, 5, 8, 9],
          label: 'Series B1',
          barLabel,
        },
      ]}
      height={350}
      margin={{ left: 0 }}
    />
  );
}

barLabel 슬롯에 컴포넌트를 제공해서 레이블을 더 커스터마이즈할 수도 있어요. 아래 예제는 레이블을 해당 막대 위에 배치해요.

import { useAnimate } from '@mui/x-charts/hooks';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { BarLabelProps, BarPlot } from '@mui/x-charts/BarChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { styled } from '@mui/material/styles';
import { interpolateObject } from '@mui/x-charts-vendor/d3-interpolate';

export default function LabelsAboveBars() {
  return (
    <ChartsContainer
      xAxis={[{ scaleType: 'band', data: ['A', 'B', 'C'] }]}
      series={[{ type: 'bar', id: 'base', data: [5, 17, 11], barLabel: 'value' }]}
      height={400}
      yAxis={[{ width: 30 }]}
      margin={{ left: 0, right: 10 }}
    >
      <BarPlot slots={{ barLabel: BarLabel }} />
      <ChartsXAxis />
      <ChartsYAxis />
    </ChartsContainer>
  );
}

const Text = styled('text')(({ theme }) => ({
  ...theme?.typography?.body2,
  stroke: 'none',
  fill: (theme.vars || theme)?.palette?.text?.primary,
  transition: 'opacity 0.2s ease-in, fill 0.2s ease-in',
  textAnchor: 'middle',
  dominantBaseline: 'central',
  pointerEvents: 'none',
}));

function BarLabel(props: BarLabelProps) {
  const {
    seriesId,
    dataIndex,
    color,
    isFaded,
    isHighlighted,
    classes,
    xOrigin,
    yOrigin,
    x,
    y,
    width,
    height,
    layout,
    skipAnimation,
    ...otherProps
  } = props;

  const animatedProps = useAnimate(
    { x: x + width / 2, y: y - 8 },
    {
      initialProps: { x: x + width / 2, y: yOrigin },
      createInterpolator: interpolateObject,
      transformProps: (p) => p,
      applyProps: (element: SVGTextElement, p) => {
        element.setAttribute('x', p.x.toString());
        element.setAttribute('y', p.y.toString());
      },
      skip: skipAnimation,
    },
  );

  return (
    <Text {...otherProps} fill={color} textAnchor="middle" {...animatedProps} />
  );
}

스택 합계 레이블

barLabel 속성은 단일 막대에만 접근할 수 있어서 스택의 합계를 표시할 수 없어요. 합계를 보여주려면 차트 컨테이너의 자식으로 커스텀 컴포넌트를 렌더링하세요.

아래 예제는 useBarSeries 훅으로 시리즈를 합산하고, useXScale과 useYScale 스케일로 각 합계를 배치해요.

import * as React from 'react';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { BarPlot } from '@mui/x-charts/BarChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import {
  getValueToPositionMapper,
  useBarSeries,
  useXScale,
  useYScale,
} from '@mui/x-charts/hooks';
import { styled } from '@mui/material/styles';

export default function StackTotalLabels() {
  return (
    <ChartsContainer
      xAxis={[{ scaleType: 'band', data: ['Q1', 'Q2', 'Q3'] }]}
      series={[
        {
          type: 'bar',
          id: 'a',
          stack: 'total',
          data: [5, 17, 11],
          barLabel: 'value',
        },
        { type: 'bar', id: 'b', stack: 'total', data: [4, 8, 6], barLabel: 'value' },
      ]}
      height={400}
      yAxis={[{ width: 30 }]}
      margin={{ left: 0, right: 10, top: 30 }}
    >
      <BarPlot />
      <StackTotals />
      <ChartsXAxis />
      <ChartsYAxis />
    </ChartsContainer>
  );
}

function StackTotals() {
  const xScale = useXScale();
  const yScale = useYScale();
  const barSeries = useBarSeries();

  const xMapper = getValueToPositionMapper(xScale);
  const yMapper = getValueToPositionMapper(yScale);

  return (
    <React.Fragment>
      {xScale.domain().map((category, dataIndex) => {
        const total = barSeries.reduce(
          (acc, series) =>
            acc + (series.stack === 'total' ? (series.data[dataIndex] ?? 0) : 0),
          0,
        );

        return (
          <TotalLabel
            key={String(category)}
            x={xMapper(category)}
            y={yMapper(total) - 8}
          >
            {total}
          </TotalLabel>
        );
      })}
    </React.Fragment>
  );
}

const TotalLabel = styled('text')(({ theme }) => ({
  ...theme?.typography?.body2,
  fontWeight: 600,
  stroke: 'none',
  fill: (theme.vars || theme)?.palette?.text?.primary,
  textAnchor: 'middle',
  dominantBaseline: 'auto',
  pointerEvents: 'none',
}));

클릭 이벤트

막대 차트는 두 가지 클릭 핸들러를 제공해요:

  • onItemClick — 특정 막대를 클릭할 때
  • 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 { BarChart } from '@mui/x-charts/BarChart';

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

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

export default function BarClick() {
  const [itemData, setItemData] = React.useState<BarItemIdentifier>();
  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 }}>
        <BarChart
          {...barChartsParams}
          onItemClick={(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 onItemClick과 onAxisClick의 event에는 약간의 차이가 있어요:

  • onItemClick의 이벤트는 막대 컴포넌트가 내보내는 React 합성 마우스 이벤트예요.
  • onAxisClick의 이벤트는 SVG 컴포넌트가 내보내는 네이티브 마우스 이벤트예요.

:::

커스텀 컴포넌트를 구성한다면 아래 코드 스니펫처럼 클릭 이벤트를 통합할 수 있어요. 시리즈를 섞으면 onAxisClick이 막대와 라인 시리즈를 모두 처리할 수 있다는 점에 주의하세요.

<ChartsContainer onAxisClick={onAxisClick}>
  {/* ... */}
  <BarPlot onItemClick={onItemClick} />
</ChartsContainer>

애니메이션

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

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

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

// For a composed chart
<ChartsContainer>
  <BarPlot skipAnimation />
</ChartsContainer>
import * as React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Slider from '@mui/material/Slider';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import { BarChart } from '@mui/x-charts/BarChart';
import { HighlightScope } from '@mui/x-charts/context';

export default function BarAnimation() {
  const [seriesNb, setSeriesNb] = React.useState(2);
  const [itemNb, setItemNb] = React.useState(5);
  const [skipAnimation, setSkipAnimation] = React.useState(false);

  const handleItemNbChange = (event: Event, newValue: number | number[]) => {
    if (typeof newValue !== 'number') {
      return;
    }
    setItemNb(newValue);
  };
  const handleSeriesNbChange = (event: Event, newValue: number | number[]) => {
    if (typeof newValue !== 'number') {
      return;
    }
    setSeriesNb(newValue);
  };

  return (
    <Box sx={{ width: '100%' }}>
      <BarChart
        height={300}
        series={series
          .slice(0, seriesNb)
          .map((s) => ({ ...s, data: s.data.slice(0, itemNb) }))}
        skipAnimation={skipAnimation}
        margin={{ left: 0 }}
      />
      <FormControlLabel
        checked={skipAnimation}
        control={
          <Checkbox onChange={(event) => setSkipAnimation(event.target.checked)} />
        }
        label="skipAnimation"
        labelPlacement="end"
      />
      <Typography id="input-item-number" gutterBottom>
        Number of items
      </Typography>
      <Slider
        value={itemNb}
        onChange={handleItemNbChange}
        valueLabelDisplay="auto"
        min={1}
        max={20}
        aria-labelledby="input-item-number"
      />
      <Typography id="input-series-number" gutterBottom>
        Number of series
      </Typography>
      <Slider
        value={seriesNb}
        onChange={handleSeriesNbChange}
        valueLabelDisplay="auto"
        min={1}
        max={10}
        aria-labelledby="input-series-number"
      />
    </Box>
  );
}

const highlightScope: HighlightScope<'bar'> = {
  highlight: 'series',
  fade: 'global',
};

const series = [
  {
    label: 'series 1',
    data: [
      2423, 2210, 764, 1879, 1478, 1373, 1891, 2171, 620, 1269, 724, 1707, 1188,
      1879, 626, 1635, 2177, 516, 1793, 1598,
    ],
  },
  {
    label: 'series 2',
    data: [
      2362, 2254, 1962, 1336, 586, 1069, 2194, 1629, 2173, 2031, 1757, 862, 2446,
      910, 2430, 2300, 805, 1835, 1684, 2197,
    ],
  },
  {
    label: 'series 3',
    data: [
      1145, 1214, 975, 2266, 1768, 2341, 747, 1282, 1780, 1766, 2115, 1720, 1057,
      2000, 1716, 2253, 619, 1626, 1209, 1786,
    ],
  },
  {
    label: 'series 4',
    data: [
      2361, 979, 2430, 1768, 1913, 2342, 1868, 1319, 1038, 2139, 1691, 935, 2262,
      1580, 692, 1559, 1344, 1442, 1593, 1889,
    ],
  },
  {
    label: 'series 5',
    data: [
      968, 1371, 1381, 1060, 1327, 934, 1779, 1361, 878, 1055, 1737, 2380, 875, 2408,
      1066, 1802, 1442, 1567, 1552, 1742,
    ],
  },
  {
    label: 'series 6',
    data: [
      2316, 1845, 2057, 1479, 1859, 1015, 1569, 1448, 1354, 1007, 799, 1748, 1454,
      1968, 1129, 1196, 2158, 540, 1482, 880,
    ],
  },
  {
    label: 'series 7',
    data: [
      2140, 2082, 708, 2032, 554, 1365, 2121, 1639, 2430, 2440, 814, 1328, 883, 1811,
      2322, 1743, 700, 2131, 1473, 957,
    ],
  },
  {
    label: 'series 8',
    data: [
      1074, 744, 2487, 823, 2252, 2317, 2139, 1818, 2256, 1769, 1123, 1461, 672,
      1335, 960, 1871, 2305, 1231, 2005, 908,
    ],
  },
  {
    label: 'series 9',
    data: [
      1792, 886, 2472, 1546, 2164, 2323, 2435, 1268, 2368, 2158, 2200, 1316, 552,
      1874, 1771, 1038, 1838, 2029, 1793, 1117,
    ],
  },
  {
    label: 'series 10',
    data: [
      1433, 1161, 1107, 1517, 1410, 1058, 676, 1280, 1936, 1774, 698, 1721, 1421,
      785, 1752, 800, 990, 1809, 1985, 665,
    ],
  },
].map((s) => ({ ...s, highlightScope }));

성능

SVG 배치 렌더링

기본적으로 각 막대는 SVG rect 요소로 그려져요. 막대가 많으면 렌더링이 느려질 수 있어요.

막대를 더 효율적으로 렌더링하려면 renderer prop을 "svg-batch"로 설정할 수 있어요. 여기에는 몇 가지 트레이드오프가 있어요:

  • CSS로 개별 막대에 스타일을 적용할 수 없어요.
  • 투명한 하이라이트 스타일은 완전히 지원되지 않아요. 성능을 위해 하이라이트가 맨 위에 있는 막대로 그려지므로, 투명도 때문에 원래 막대가 비쳐 보일 수 있어요.
  • 막대 하이라이트 및 페이드 애니메이션을 사용할 수 없어요.
  • onItemClick 핸들러는 React.MouseEvent 대신 네이티브 MouseEvent를 받아요. 타입 호환성을 깨지 않기 위해 타입은 변경되지 않았어요. 올바른 타입을 위해 import type {} from '@mui/x-charts/moduleAugmentation/barChartBatchRendererOnItemClick'을 추가해 주세요.
  • 배치 렌더러는 범위 막대 차트에서는 사용할 수 없어요.

아래 예제는 500개 데이터 포인트를 가진 데이터셋을 렌더링할 때 renderer prop을 사용해서 성능을 개선해요.

import * as React from 'react';
import Stack from '@mui/material/Stack';
import { BarChartPro } from '@mui/x-charts-pro/BarChartPro';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import data from '../dataset/sp500-intraday.json';

const tickLabelDateFormatter = new Intl.DateTimeFormat(undefined, {
  month: 'short',
  day: 'numeric',
});

export default function BarBatchRenderer() {
  const [renderer, setRenderer] = React.useState<'svg-single' | 'svg-batch'>(
    'svg-batch',
  );

  return (
    <Stack sx={{ width: '100%' }}>
      <FormControl fullWidth>
        <FormLabel id="bar-chart-renderer-label">Rendering Strategy</FormLabel>
        <RadioGroup
          row
          aria-labelledby="bar-chart-renderer-label"
          value={renderer}
          onChange={(event) =>
            setRenderer(event.target.value as 'svg-single' | 'svg-batch')
          }
        >
          <FormControlLabel
            value="svg-single"
            control={<Radio />}
            label="Individual Bars (default)"
          />
          <FormControlLabel
            value="svg-batch"
            control={<Radio />}
            label="Batch Bar Rendering"
          />
        </RadioGroup>
      </FormControl>
      <BarChartPro
        xAxis={[
          {
            data: data.map((d) => new Date(d.date)),
            valueFormatter: (v: Date) => tickLabelDateFormatter.format(v),
            zoom: true,
            ordinalTimeTicks: [
              'years',
              'quarterly',
              'months',
              'biweekly',
              'weeks',
              'days',
            ],
          },
        ]}
        series={[
          {
            data: data.map((d) => d.close),
            label: 'Close',
            highlightScope: { highlight: 'item', fade: 'global' },
          },
          {
            data: data.map((d) => d.open),
            label: 'Open',
            highlightScope: { highlight: 'item', fade: 'global' },
          },
        ]}
        height={300}
        renderer={renderer}
      />
    </Stack>
  );
}

WebGL 렌더러

더 큰 데이터셋을 위해서는 BarChartPremium이 단일 <canvas> 요소에서 모든 막대를 그리는 WebGL 렌더러를 지원해요. 이를 활성화하려면 renderer prop을 "webgl"로 설정하세요.

WebGL 렌더러는 배치 렌더러와 같은 트레이드오프가 있으며, 몇 가지가 더 추가돼요:

  • 막대마다 DOM 요소가 렌더링되지 않으므로, 이를 사용하는 커스텀 슬롯(예: 커스텀 bar 슬롯)은 적용되지 않아요.
  • WebGL 캔버스는 막대 모양만 그려요. 축, 그리드, 하이라이트, 포커스 윤곽선, 막대 레이블은 계속 SVG에 의존해요.
  • WebGL 2를 지원하는 브라우저가 필요해요.
import * as React from 'react';
import Stack from '@mui/material/Stack';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import { BarChartPremium } from '@mui/x-charts-premium/BarChartPremium';

type Renderer = 'svg-single' | 'svg-batch' | 'webgl';

const POINTS = 10000;

function generateData(seed: number) {
  const data = new Array<number>(POINTS);
  let value = 50;
  for (let i = 0; i < POINTS; i += 1) {
    // Deterministic pseudo-random walk. value-in-sin breaks linear predictability.
    value += Math.sin(value * i * seed * 0.13) * 4;
    data[i] = Math.max(0, Math.round(value));
  }
  return data;
}

const xData = Array.from({ length: POINTS }, (_, i) => i);
const seriesA = generateData(1);
const seriesB = generateData(7);

export default function WebGLBars() {
  const [renderer, setRenderer] = React.useState<Renderer>('webgl');

  return (
    <Stack sx={{ width: '100%' }}>
      <FormControl fullWidth>
        <FormLabel id="bar-chart-webgl-renderer-label">Rendering Strategy</FormLabel>
        <RadioGroup
          row
          aria-labelledby="bar-chart-webgl-renderer-label"
          value={renderer}
          onChange={(event) => setRenderer(event.target.value as Renderer)}
        >
          <FormControlLabel
            value="svg-single"
            control={<Radio />}
            label="Individual Bars (default)"
          />
          <FormControlLabel
            value="svg-batch"
            control={<Radio />}
            label="Batch Bar Rendering"
          />
          <FormControlLabel value="webgl" control={<Radio />} label="WebGL" />
        </RadioGroup>
      </FormControl>
      <BarChartPremium
        xAxis={[{ data: xData, scaleType: 'band', zoom: { minSpan: 0.05 } }]}
        series={[
          { data: seriesA, label: 'Series A', stack: 'stack' },
          { data: seriesB, label: 'Series B', stack: 'stack' },
        ]}
        height={300}
        renderer={renderer}
      />
    </Stack>
  );
}

샘플링

BarChartPro에 sampling prop을 설정하면 축소(zoom out) 상태에서 뷰가 해상할 수 있는 만큼만 막대를 그리게 돼요. 자세한 내용과 라이브 데모는 Charts—성능 문서를 참고하세요.

컴포지션

컴포지션을 위해 ChartDataProvider를 사용해서 series, xAxis, yAxis prop을 제공해 주세요.

컴포지션을 위해 사용할 수 있는 공유 차트 컴포넌트에 더해, BarPlot 컴포넌트로 막대와 그 레이블을 렌더링할 수 있어요.

막대 차트는 다음과 같이 구성돼요:

<ChartsDataProvider>
  <ChartsWrapper>
    <ChartsLegend />
    <ChartsSurface>
      <ChartsGrid />
      <g clipPath={`url(#${clipPathId})`}>
        <BarPlot />
        <ChartsOverlay />
        <ChartsAxisHighlight />
        <FocusedBar />
        <FocusedScatterMark />
      </g>
      <ChartsAxis />
      <ChartsClipPath id={clipPathId} />
    </ChartsSurface>
    <ChartsTooltip />
  </ChartsWrapper>
</ChartsDataProvider>
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { BarPlot, FocusedBar } from '@mui/x-charts/BarChart';
import { ScatterPlot, FocusedScatterMark } from '@mui/x-charts/ScatterChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsGrid } from '@mui/x-charts/ChartsGrid';
import { ChartsDataProvider } from '@mui/x-charts/ChartsDataProvider';
import { ChartsSurface } from '@mui/x-charts/ChartsSurface';
import { ChartsTooltip } from '@mui/x-charts/ChartsTooltip';
import { legendClasses, ChartsLegend } from '@mui/x-charts/ChartsLegend';
import { GDPdata } from '../dataset/gdpGrowth';

const chartSetting = {
  xAxis: [
    {
      id: 'bar',
      label: 'GDP growth rate',
      dataKey: '2024',
      colorMap: {
        type: 'piecewise' as const,
        thresholds: [0],
        colors: ['#ff4d4f', '#1976d2'],
      },
    },
    {
      id: 'scatter',
      label: '2010-19 Average',
      dataKey: '2010_19',
      color: '#FFFF00',
    },
  ],
  height: 800,
};

const valueFormatter = (value: number | null) =>
  value ? `${value.toFixed(2)}%` : '';

const scatterValueFormatter = (value: { x: number } | null) =>
  value ? `${value.x.toFixed(2)}%` : '';

function Gradient() {
  return (
    <linearGradient id="diagonalGradient" x1="0%" y1="50%" x2="100%" y2="50%">
      <stop offset="0%" stopColor="#ff4d4f" />
      <stop offset="50%" stopColor="#ff4d4f" />
      <stop offset="50%" stopColor="#1976d2" />
      <stop offset="100%" stopColor="#1976d2" />
    </linearGradient>
  );
}

export default function BarScatterCompostion() {
  return (
    <Box
      sx={{
        width: '100%',
        overflow: 'auto',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
      }}
    >
      <Typography variant="h6">
        GDP growth rate comparison (2024 vs 2010-19 Avg)
      </Typography>
      <ChartsDataProvider
        dataset={GDPdata}
        series={[
          {
            id: 'bar',
            type: 'bar',
            layout: 'horizontal',
            dataKey: '2024',
            label: '2024 ',
            valueFormatter,
          },
          {
            id: 'scatter',
            type: 'scatter',
            datasetKeys: { id: 'country', x: '2010_19', y: 'country' },
            label: '2010-19 Average',
            valueFormatter: scatterValueFormatter,
            markerSize: 4,
            xAxisId: 'scatter',
          },
        ]}
        yAxis={[{ scaleType: 'band', dataKey: 'country', width: 100 }]}
        {...chartSetting}
      >
        <ChartsLegend
          sx={{
            [`[data-series="bar"] .${legendClasses.mark} rect`]: {
              fill: 'url(#diagonalGradient)',
            },
          }}
        />
        <ChartsTooltip />
        <ChartsSurface>
          <Gradient />
          <ChartsGrid vertical />
          <BarPlot />
          <ScatterPlot />
          <ChartsXAxis axisId="bar" />
          <FocusedBar />
          <FocusedScatterMark />
          <ChartsYAxis />
        </ChartsSurface>
      </ChartsDataProvider>
    </Box>
  );
}

더 알아보기 (Learn more)