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

차트 - 축(Axis)

원문 보기 위키 갱신

차트의 축을 정의하고, 형식을 지정하고, 원하는 대로 꾸미는 방법을 알아봅니다.

출처: MUI X documentation

본문

사용자 지정 축 만들기

xAxis와 yAxis props를 사용해서 주문형(커스텀) 축을 정의해요. 이 props들은 객체의 배열을 기대해요.

아래 데모에서는 같은 데이터 포인트로 두 개의 선을 그리고 있어요. 하나는 선형(linear) y축을, 다른 하나는 로그(log) 축을 사용하죠. 각 축 정의는 id 속성으로 식별돼요. 그리고 각 시리즈는 xAxisId와 yAxisId 속성으로 사용할 축을 지정해요.

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

const sample = [1, 10, 30, 50, 70, 90, 100];

export default function ScaleExample() {
  return (
    <Box sx={{ width: '100%', maxWidth: 500 }}>
      <LineChart
        xAxis={[{ data: sample }]}
        yAxis={[
          { id: 'linearAxis', scaleType: 'linear', position: 'left' },
          { id: 'logAxis', scaleType: 'log', position: 'right' },
        ]}
        series={[
          { yAxisId: 'linearAxis', data: sample, label: 'linear', showMark: true },
          { yAxisId: 'logAxis', data: sample, label: 'log', showMark: true },
        ]}
        height={400}
      />
    </Box>
  );
}

:::info ID management, as shown in the example above, is not necessary for most common use cases.

If you don't provide xAxisId or yAxisId then the series uses the axis defined first. This is why you won't see definitions of id, xAxisId, or yAxisId in most demos in the Charts docs—they rely on the default values. :::

Axis type and data

The axis type is specified by its property scaleType. The axis definition object has a data property which expects an array of values corresponding to the scaleType, as shown in the table below:

scaleType Description Number Date String
'band' Splits the axis in equal bands. ✅ ✅ ✅
'point' Splits the axis in equally spaced points. ✅ ✅ ✅
'linear' 'log' 'symlog' 'sqrt' Maps numerical values to the available space. ✅ ❌ ❌
'time' 'utc' Maps JavaScript Date() objects to the available space. ❌ ✅ ❌
:::info
위 예시에서 보여준 것처럼 ID를 관리하는 건 대부분의 일반적인 사용 사례에서는 필요하지 않아요.

xAxisId나 yAxisId를 제공하지 않으면 시리즈는 가장 먼저 정의된 축을 사용해요. 그래서 Charts 문서의 대부분 데모에서는 id, xAxisId, yAxisId 정의를 볼 수 없어요. 기본값에 의존하기 때문이죠. :::

축 유형과 데이터

축 유형은 scaleType 속성으로 지정돼요. 축 정의 객체에는 data 속성이 있는데, 아래 표에서 볼 수 있듯이 scaleType에 해당하는 값의 배열을 기대해요.

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

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

const dataset = [
  {
    london: 59,
    paris: 57,
    newYork: 86,
    seoul: 21,
    month: 'January',
  },
  {
    london: 50,
    paris: 52,
    newYork: 78,
    seoul: 28,
    month: 'February',
  },
  {
    london: 47,
    paris: 53,
    newYork: 106,
    seoul: 41,
    month: 'March',
  },
  {
    london: 54,
    paris: 56,
    newYork: 92,
    seoul: 73,
    month: 'April',
  },
  {
    london: 57,
    paris: 69,
    newYork: 92,
    seoul: 99,
    month: 'May',
  },
  {
    london: 60,
    paris: 63,
    newYork: 103,
    seoul: 144,
    month: 'June',
  },
  {
    london: 59,
    paris: 60,
    newYork: 105,
    seoul: 319,
    month: 'July',
  },
  {
    london: 65,
    paris: 60,
    newYork: 106,
    seoul: 249,
    month: 'August',
  },
  {
    london: 51,
    paris: 51,
    newYork: 95,
    seoul: 131,
    month: 'September',
  },
  {
    london: 60,
    paris: 65,
    newYork: 97,
    seoul: 55,
    month: 'October',
  },
  {
    london: 67,
    paris: 64,
    newYork: 76,
    seoul: 48,
    month: 'November',
  },
  {
    london: 61,
    paris: 70,
    newYork: 103,
    seoul: 25,
    month: 'December',
  },
];

const valueFormatter = (value: number | null) => `${value}mm`;

export default function FormatterDemo() {
  return (
    <BarChart
      dataset={dataset}
      xAxis={[
        {
          scaleType: 'band',
          dataKey: 'month',
          valueFormatter: (month, context) =>
            context.location === 'tick'
              ? `${month.slice(0, 3)} \n2023`
              : `${month} 2023`,
          height: 40,
        },
      ]}
      series={[{ dataKey: 'seoul', label: 'Seoul rainfall', valueFormatter }]}
      {...otherSetting}
    />
  );
}

Ticks without labels

Some use cases may call for displaying ticks with no labels. For example, it's common to use ticks to indicate a logarithmic scale but omit the labels from the axis when they'd be too numerous or complex to display.

The default tick formatter achieves this by rendering an empty string for ticks that should not show labels. If you want to customize the formatting, but want to keep the default behavior for ticks without labels, you can check that the context.defaultTickLabel property is different from the empty string:

import * as React from 'react';
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import { AxisValueFormatterContext, ScatterValueType } from '@mui/x-charts/models';
import { earthquakeData } from '../dataset/earthquakeData';

const settings = {
  height: 400,
  grid: { horizontal: true },
};
const data = Object.entries(earthquakeData).reduce<ScatterValueType[]>(
  (acc, [magnitude, events]) => {
    acc.push({ x: Number.parseFloat(magnitude), y: events });

    return acc;
  },
  [],
);

const formatter = new Intl.NumberFormat('en-US', {
  notation: 'compact',
  maximumFractionDigits: 1,
});

function valueFormatterIgnoreEmpty(value: any, context: AxisValueFormatterContext) {
  if (context.location === 'tick' && context.defaultTickLabel === '') {
    return '';
  }

  return formatter.format(value);
}

function valueFormatterShowAll(value: any) {
  return formatter.format(value);
}

export default function TicksWithoutLabels() {
  const [tickFormatter, setTickFormatter] = React.useState(
    () => valueFormatterIgnoreEmpty,
  );

  return (
    <Stack
      direction={{ md: 'row' }}
      sx={{ width: '100%', alignItems: 'center', rowGap: 2 }}
    >
      <Stack sx={{ width: '100%' }}>
        <Typography variant="h6" sx={{ textAlign: 'center' }}>
          Worldwide Earthquake Count and Magnitude, 2020-2024
        </Typography>
        <ScatterChart
          {...settings}
          xAxis={[{ height: 48, label: 'Magnitude' }]}
          yAxis={[
            {
              scaleType: 'log',
              valueFormatter: tickFormatter,
              label: 'Number of events (Log scale)',
              width: 50,
            },
          ]}
          series={[{ data }]}
        />
        <Typography variant="caption">Source: US Geological Survey</Typography>
      </Stack>
      <FormControl sx={{ flexShrink: 0 }}>
        <FormLabel id="tick-format-label">Tick Format</FormLabel>
        <RadioGroup
          aria-labelledby="tick-format-label"
          name="tick-format"
          value={tickFormatter === valueFormatterIgnoreEmpty ? 'empty' : 'all'}
          onChange={(event) =>
            setTickFormatter(() =>
              event.target.value === 'empty'
                ? valueFormatterIgnoreEmpty
                : valueFormatterShowAll,
            )
          }
        >
          <FormControlLabel
            value="empty"
            control={<Radio />}
            label="Ignore empty ticks"
          />
          <FormControlLabel
            value="all"
            control={<Radio />}
            label="Show all values"
          />
        </RadioGroup>
      </FormControl>
    </Stack>
  );
}

일부 시리즈 유형은 특정 축 속성도 요구해요.

  • 선(line) 차트에서는 각 y값이 특정 x값에 매핑되도록 xAxis에 data 배열이 있어야 해요. 그래야 차트가 제대로 렌더링돼요.
  • 막대(bar) 차트에서는 카테고리를 나타내는 축(세로 막대의 x축 또는 가로 막대의 y축)이 scaleType: 'band'를 사용해야 해요.

축 포맷터

축 데이터는 틱(tick), 툴팁, 그 밖의 위치에 표시될 수 있어요. valueFormatter 속성을 사용해서 데이터가 표시되는 방식을 바꿀 수 있어요. 이 포맷터의 두 번째 인자는 고급 사용 사례를 위한 렌더링 컨텍스트를 제공해요.

아래 데모에서는 valueFormatter를 사용해서 월 이름을 줄이고 틱에 새 줄을 도입했어요. 값이 렌더링되는 위치를 판단하기 위해 context.location을 사용하죠.

import { ScaleLogarithmic } from '@mui/x-charts-vendor/d3-scale';
import { LineChart } from '@mui/x-charts/LineChart';
import { ChartsReferenceLine } from '@mui/x-charts/ChartsReferenceLine';

const otherSetting = {
  height: 300,
  grid: { horizontal: true, vertical: true },
};

// https://en.wikipedia.org/wiki/Low-pass_filter
const f0 = 440;
const frequencyResponse = (f: number) => 5 / Math.sqrt(1 + (f / f0) ** 2);

const dataset = [
  0.1, 0.5, 0.8, 1, 5, 8, 10, 50, 80, 100, 500, 800, 1_000, 5_000, 8_000, 10_000,
  50_000, 80_000, 100_000, 500_000, 800_000, 1_000_000,
].map((f) => ({ frequency: f, voltage: frequencyResponse(f) }));

export default function FormatterD3() {
  return (
    <LineChart
      dataset={dataset}
      xAxis={[
        {
          scaleType: 'log',
          label: 'f (Hz)',
          dataKey: 'frequency',
          tickNumber: 20,
          valueFormatter: (f, context) => {
            if (context.location === 'tick') {
              const d3Text = (
                context.scale as ScaleLogarithmic<number, number, never>
              ).tickFormat(
                context.tickNumber!,
                'e',
              )(f);

              return d3Text;
            }
            return `${f.toLocaleString()}Hz`;
          },
        },
      ]}
      yAxis={[
        {
          scaleType: 'log',
          label: 'Vo/Vi',
          width: 60,
          valueFormatter: (f, context) => {
            if (context.location === 'tick') {
              const d3Text = (
                context.scale as ScaleLogarithmic<number, number, never>
              ).tickFormat(
                30,
                'f',
              )(f);

              return d3Text;
            }
            return f.toLocaleString();
          },
        },
      ]}
      series={[{ dataKey: 'voltage' }]}
      {...otherSetting}
    >
      <ChartsReferenceLine x={f0} />
    </LineChart>
  );
}

Axis subdomain

By default, the axis domain is computed so that all data is visible. To show a specific range of values, you can provide the min and/or max properties to the axis definition:

xAxis={[
  {
    min: 10,
    max: 50,
  },
]}

라벨이 없는 틱

라벨 없이 틱만 표시해야 하는 사용 사례도 있어요. 예를 들어 로그 스케일을 나타낼 때 틱은 사용하지만, 너무 많거나 복잡해서 라벨은 축에서 생략하는 경우가 흔하죠.

기본 틱 포맷터는 라벨을 표시하지 않아야 하는 틱에 빈 문자열을 렌더링하는 방식으로 이 동작을 구현해요. 형식을 커스터마이즈하면서도 라벨이 없는 틱의 기본 동작은 유지하고 싶다면, context.defaultTickLabel 속성이 빈 문자열과 다른지 확인하면 돼요.

import * as React from 'react';
import Slider from '@mui/material/Slider';
import Box from '@mui/material/Box';
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import { Chance } from 'chance';

const chance = new Chance(42);

const data = Array.from({ length: 200 }, () => ({
  x: chance.floating({ min: -25, max: 25 }),
  y: chance.floating({ min: -25, max: 25 }),
})).map((d, index) => ({ ...d, id: index }));

const minDistance = 10;

export default function MinMaxExample() {
  const [value, setValue] = React.useState<number[]>([-25, 25]);

  const handleChange = (
    event: Event,
    newValue: number | number[],
    activeThumb: number,
  ) => {
    if (!Array.isArray(newValue)) {
      return;
    }

    if (newValue[1] - newValue[0] < minDistance) {
      if (activeThumb === 0) {
        const clamped = Math.min(newValue[0], 100 - minDistance);
        setValue([clamped, clamped + minDistance]);
      } else {
        const clamped = Math.max(newValue[1], minDistance);
        setValue([clamped - minDistance, clamped]);
      }
    } else {
      setValue(newValue as number[]);
    }
  };

  return (
    <Box sx={{ width: '100%', maxWidth: 500 }}>
      <ScatterChart
        xAxis={[
          {
            label: 'x',
            min: value[0],
            max: value[1],
          },
        ]}
        series={[{ data }]}
        height={300}
      />
      <Slider
        value={value}
        onChange={handleChange}
        valueLabelDisplay="auto"
        min={-40}
        max={40}
      />
    </Box>
  );
}

Relative axis subdomain

You can adjust the axis range relative to its data by using the domainLimit option. This expects one of three possible values:

  • "nice" (default): Rounds the domain to human-friendly values
  • "strict": Sets the domain to the min/max value to display
  • (minValue, maxValue) => { min, max }: Receives the calculated extrema as parameters, and should return the axis domain

The demo below illustrates these differences in behavior, showing data ranging from -15 to 92 with different domain limits:

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

const settings = {
  height: 220,
  series: [{ data: [60, -15, 66, 68, 87, 82, 83, 85, 92, 75, 76, 50, 91] }],
  margin: { top: 20, bottom: 10 },
} as const;

// Extend a value to match a multiple of the step.
function extend(value: number, step: number) {
  if (value > 0) {
    // If >0 go to the next step
    return step * Math.ceil(value / step);
  }
  // If <0 go to the previous step
  return step * Math.floor(value / step);
}

export default function CustomDomainYAxis() {
  const [domainLimit, setDomainLimit] = React.useState<
    'nice' | 'strict' | 'function'
  >('nice');

  return (
    <Box sx={{ width: '100%' }}>
      <TextField
        select
        value={domainLimit}
        onChange={(event) =>
          setDomainLimit(event.target.value as 'nice' | 'strict' | 'function')
        }
        label="domain limit"
        sx={{ minWidth: 150, mb: 2 }}
      >
        <MenuItem value="nice">nice</MenuItem>
        <MenuItem value="strict">strict</MenuItem>
        <MenuItem value="function">function</MenuItem>
      </TextField>
      <BarChart
        yAxis={[
          {
            domainLimit:
              domainLimit === 'function'
                ? (min, max) => ({
                    min: extend(min.valueOf(), 10),
                    max: extend(max.valueOf(), 10),
                  })
                : domainLimit,
          },
        ]}
        {...settings}
      />
    </Box>
  );
}

D3 포맷터 사용하기

이 컨텍스트에서는 축 스케일, 틱 개수(해당하는 경우), 그리고 기본 포맷된 값에 접근할 수 있어요. D3의 tickFormat(tickNumber, specifier) 메서드를 사용해서 아래처럼 스케일 속성에 맞게 틱 형식을 조정할 수 있어요.

import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';

import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { LinePlot, MarkPlot } from '@mui/x-charts/LineChart';
import { BarPlot } from '@mui/x-charts/BarChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsGrid } from '@mui/x-charts/ChartsGrid';
import { ChartsTooltip } from '@mui/x-charts/ChartsTooltip';

const dataset = [
  { min: -12, max: -4, precip: 79, month: 'Jan' },
  { min: -11, max: -3, precip: 66, month: 'Feb' },
  { min: -6, max: 2, precip: 76, month: 'Mar' },
  { min: 1, max: 9, precip: 106, month: 'Apr' },
  { min: 8, max: 17, precip: 105, month: 'Mai' },
  { min: 15, max: 24, precip: 114, month: 'Jun' },
  { min: 18, max: 26, precip: 106, month: 'Jul' },
  { min: 17, max: 26, precip: 105, month: 'Aug' },
  { min: 13, max: 21, precip: 100, month: 'Sept' },
  { min: 6, max: 13, precip: 116, month: 'Oct' },
  { min: 0, max: 6, precip: 93, month: 'Nov' },
  { min: -8, max: -1, precip: 93, month: 'Dec' },
];

const series = [
  { type: 'line', dataKey: 'min', color: '#577399', showMark: true },
  { type: 'line', dataKey: 'max', color: '#fe5f55', showMark: true },
  { type: 'bar', dataKey: 'precip', color: '#bfdbf7', yAxisId: 'rightAxis' },
] as const;

export default function ReverseExample() {
  const [reverseX, setReverseX] = React.useState(false);
  const [reverseLeft, setReverseLeft] = React.useState(false);
  const [reverseRight, setReverseRight] = React.useState(false);

  return (
    <Stack sx={{ width: '100%' }}>
      <Stack direction="row">
        <FormControlLabel
          checked={reverseX}
          control={
            <Checkbox onChange={(event) => setReverseX(event.target.checked)} />
          }
          label="reverse x-axis"
          labelPlacement="end"
        />
        <FormControlLabel
          checked={reverseLeft}
          control={
            <Checkbox onChange={(event) => setReverseLeft(event.target.checked)} />
          }
          label="reverse left axis"
          labelPlacement="end"
        />
        <FormControlLabel
          checked={reverseRight}
          control={
            <Checkbox onChange={(event) => setReverseRight(event.target.checked)} />
          }
          label="reverse right axis"
          labelPlacement="end"
        />
      </Stack>
      <Box sx={{ width: '100%' }}>
        <ChartsContainer
          series={series}
          xAxis={[
            {
              scaleType: 'band',
              dataKey: 'month',
              label: 'Month',
              reverse: reverseX,
            },
          ]}
          yAxis={[
            { id: 'leftAxis', reverse: reverseLeft, width: 50 },
            { id: 'rightAxis', reverse: reverseRight, position: 'right', width: 50 },
          ]}
          dataset={dataset}
          height={400}
        >
          <ChartsGrid horizontal />
          <BarPlot />
          <LinePlot />
          <MarkPlot />

          <ChartsXAxis />
          <ChartsYAxis axisId="leftAxis" label="temperature (°C)" />
          <ChartsYAxis axisId="rightAxis" label="precipitation (mm)" />
          <ChartsTooltip />
        </ChartsContainer>
      </Box>
    </Stack>
  );
}

Position

You can customize axis positioning with the position property of the axis configuration. This property expects the following values:

  • 'top' or 'bottom' for the x-axis
  • 'left' or 'right' for the y-axis
  • 'none' to hide the axis
import Box from '@mui/material/Box';
import { ScatterChart } from '@mui/x-charts/ScatterChart';
import { Chance } from 'chance';

const chance = new Chance(42);

const data = Array.from({ length: 200 }, () => ({
  x: chance.floating({ min: -25, max: 25 }),
  y: chance.floating({ min: -25, max: 25 }),
})).map((d, index) => ({ ...d, id: index }));

const params = {
  series: [{ data }],
  height: 300,
  margin: { top: 12, right: 12, bottom: 20, left: 12 },
};
export default function ModifyAxisPosition() {
  return (
    <Box sx={{ width: '100%', maxWidth: 500 }}>
      <ScatterChart
        {...params}
        xAxis={[{ position: 'top' }]}
        yAxis={[{ position: 'right' }]}
      />
    </Box>
  );
}

축 하위 도메인(Subdomain)

기본적으로 축 도메인은 모든 데이터가 보이도록 계산돼요. 특정 값 범위만 표시하려면 축 정의에 min 및/또는 max 속성을 제공하면 돼요.

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

export default function HidingAxis() {
  return (
    <BarChart
      series={[{ data: [1, 2, 3, 2, 1] }]}
      xAxis={[{ data: ['A', 'B', 'C', 'D', 'E'] }]}
      yAxis={[{ position: 'none' }]}
      height={300}
      width={300}
    />
  );
}

Multiple axes on one side

You can display multiple axes on one side. If two or more axes share the same position, they're displayed in the order they're defined from closest to farthest away from the chart.

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

const sample = [1, 10, 30, 50, 70, 90, 100];

export default function MultipleAxes() {
  return (
    <Box sx={{ width: '100%', maxWidth: 500 }}>
      <LineChart
        xAxis={[{ data: sample }]}
        yAxis={[
          { id: 'linearAxis', scaleType: 'linear', position: 'left', width: 40 },
          { id: 'logAxis', scaleType: 'log', position: 'left' },
        ]}
        series={[
          { yAxisId: 'linearAxis', data: sample, label: 'linear', showMark: true },
          { yAxisId: 'logAxis', data: sample, label: 'log', showMark: true },
        ]}
        height={400}
      />
    </Box>
  );
}

Coordinates

You can obtain the coordinates of the axis by calling the useXAxisCoordinates() or useYAxisCoordinates() hooks.

Below is an example of how to use the these hooks to get the coordinates of several axes and render rectangles delineating their area.

import * as React from 'react';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { LinePlot } from '@mui/x-charts/LineChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import {
  useXAxis,
  useXAxisCoordinates,
  useYAxis,
  useYAxisCoordinates,
  type AxisCoordinates,
} from '@mui/x-charts/hooks';
import { AxisId } from '@mui/x-charts/internals';
import { useTheme } from '@mui/material/styles';

const lineData = [2, 5, 3, 8, 4];
const xAxisData = [1, 2, 3, 4, 5];

const colors = [
  '#e63946', // red
  '#f4a261', // orange
  '#e9c46a', // yellow
  '#2a9d8f', // teal
  '#264653', // dark blue
  '#8338ec', // purple
  '#3a86ff', // blue
  '#06d6a0', // green
];

export default function AxisCoordinatesDemo() {
  return (
    <ChartsContainer
      series={[
        {
          type: 'line',
          data: lineData,
          yAxisId: 'y-left-1',
          xAxisId: 'x-bottom-1',
        },
      ]}
      xAxis={[
        { id: 'x-bottom-1', data: xAxisData, height: 60 },
        { id: 'x-bottom-2', data: xAxisData, height: 30, position: 'bottom' },
        { id: 'x-top-1', data: xAxisData, height: 60, position: 'top' },
        { id: 'x-top-2', data: xAxisData, height: 30, position: 'top' },
      ]}
      yAxis={[
        { id: 'y-left-1', width: 60 },
        { id: 'y-left-2', width: 30, position: 'left' },
        { id: 'y-right-1', width: 60, position: 'right' },
        { id: 'y-right-2', width: 30, position: 'right' },
      ]}
      axesGap={8}
      width={500}
      height={500}
    >
      <LinePlot />
      <XAxisPositionIndicator axisId="x-bottom-1" color={colors[0]} />
      <XAxisPositionIndicator axisId="x-bottom-2" color={colors[1]} />
      <XAxisPositionIndicator axisId="x-top-1" color={colors[2]} />
      <XAxisPositionIndicator axisId="x-top-2" color={colors[3]} />
      <YAxisPositionIndicator axisId="y-left-1" color={colors[4]} />
      <YAxisPositionIndicator axisId="y-left-2" color={colors[5]} />
      <YAxisPositionIndicator axisId="y-right-1" color={colors[6]} />
      <YAxisPositionIndicator axisId="y-right-2" color={colors[7]} />
      {/* Render the actual axes */}
      <ChartsXAxis axisId="x-bottom" />
      <ChartsXAxis axisId="x-top" />
      <ChartsYAxis axisId="y-left" />
      <ChartsYAxis axisId="y-right" />
    </ChartsContainer>
  );
}

function XAxisPositionIndicator({
  axisId,
  color,
}: {
  axisId: AxisId;
  color: string;
}) {
  const xPosition = useXAxisCoordinates(axisId);
  const xAxis = useXAxis(axisId);

  if (!xPosition) {
    return null;
  }

  return (
    <AxisPositionIndicator
      axisId={axisId}
      position={xAxis.position ?? 'bottom'}
      direction="x"
      coordinates={xPosition}
      color={color}
    />
  );
}

function YAxisPositionIndicator({
  axisId,
  color,
}: {
  axisId: AxisId;
  color: string;
}) {
  const yPosition = useYAxisCoordinates(axisId);
  const yAxis = useYAxis(axisId);

  if (!yPosition) {
    return null;
  }

  return (
    <AxisPositionIndicator
      axisId={axisId}
      position={yAxis.position ?? 'left'}
      direction="y"
      coordinates={yPosition}
      color={color}
    />
  );
}

function AxisPositionIndicator({
  axisId,
  position,
  direction,
  coordinates,
  color,
}: {
  axisId: AxisId;
  position: 'top' | 'bottom' | 'left' | 'right' | 'none';
  direction: 'x' | 'y';
  coordinates: AxisCoordinates;
  color: string;
}) {
  const theme = useTheme();

  if (position === 'none') {
    return null;
  }

  const centerX = coordinates.left + (coordinates.right - coordinates.left) / 2;
  const centerY = coordinates.top + (coordinates.bottom - coordinates.top) / 2;

  return (
    <React.Fragment>
      <rect
        x={coordinates.left}
        y={coordinates.top}
        width={coordinates.right - coordinates.left}
        height={coordinates.bottom - coordinates.top}
        fill={color}
        fillOpacity={0.2}
        stroke={color}
        strokeWidth={2}
      />
      <text
        x={centerX}
        y={centerY}
        width={coordinates.right - coordinates.left}
        height={coordinates.bottom - coordinates.top}
        dominantBaseline="central"
        textAnchor="middle"
        transform={
          direction === 'y'
            ? `rotate(${position === 'right' ? 90 : -90} ${centerX} ${centerY})`
            : undefined
        }
        fill={theme.palette.text.primary}
      >
        {axisId}
      </text>
    </React.Fragment>
  );
}

Grouped axes

To group band or point axes together, provide a groups property in the axis definition. This property expects an array of objects with a getValue() function. This feature is available for both x- and y-axes.

The getValue() function receives the axis data value and should return a group name. Each group name is used as-is, overriding any valueFormatter for the axis. Groups are displayed in the order they're defined in the groups array.

The demos below show the feature with:

  • The x-axis grouped by month, quarter, and year.
  • The y-axis is grouped by category and subcategory.
import { BarChart } from '@mui/x-charts/BarChart';

export default function GroupedAxes() {
  return (
    <BarChart
      xAxis={[
        {
          data,
          scaleType: 'band',
          tickSize: 8,
          height: 36,
          groups: [
            { getValue: getMonth },
            { getValue: getQuarter },
            { getValue: getYear },
          ],
          valueFormatter,
        },
      ]}
      {...chartConfig}
    />
  );
}

const getMonth = (date: Date) =>
  date.toLocaleDateString('en-US', { month: 'short' });
const getQuarter = (date: Date) => `Q${Math.floor(date.getMonth() / 3) + 1}`;

const getYear = (date: Date) =>
  date.toLocaleDateString('en-US', { year: 'numeric' });

const valueFormatter = (v: Date) =>
  v.toLocaleDateString('en-US', {
    month: 'short',
    year: 'numeric',
  });

const data = [
  new Date(2014, 11, 1),
  new Date(2015, 0, 1),
  new Date(2015, 1, 1),
  new Date(2015, 2, 1),
  new Date(2015, 3, 1),
  new Date(2015, 4, 1),
  new Date(2015, 5, 1),
  new Date(2015, 6, 1),
  new Date(2015, 7, 1),
  new Date(2015, 8, 1),
  new Date(2015, 9, 1),
  new Date(2015, 10, 1),
  new Date(2015, 11, 1),
  new Date(2016, 0, 1),
];
const a = [
  3190, 4000, 3000, 2000, 2780, 1890, 2390, 3490, 2400, 1398, 9800, 3908, 4800, 2040,
];
const b = [
  1200, 2400, 1398, 9800, 3908, 4800, 3800, 4300, 2181, 2500, 2100, 3000, 2000, 2040,
];

const getPercents = (array: number[]) =>
  array.map((v, index) => (100 * v) / (a[index] + b[index]));

const chartConfig = {
  height: 200,
  margin: { left: 0 },
  series: [
    {
      data: getPercents(a),
      label: 'Income',
      valueFormatter: (value: number | null) => `${(value ?? 0).toFixed(0)}%`,
    },
    {
      data: getPercents(b),
      label: 'Expenses',
      valueFormatter: (value: number | null) => `${(value ?? 0).toFixed(0)}%`,
    },
  ],
  yAxis: [
    {
      valueFormatter: (value: number | null) => `${(value ?? 0).toFixed(0)}%`,
    },
  ],
} as const;

상대 축 하위 도메인

domainLimit 옵션을 사용해서 데이터를 기준으로 축 범위를 상대적으로 조정할 수 있어요. 이 옵션은 다음 세 가지 값 중 하나를 기대해요.

  • "nice"(기본값): 도메인을 사람이 보기 좋은 값으로 반올림해요.
  • "strict": 표시할 min/max 값 그대로 도메인을 설정해요.
  • (minValue, maxValue) => { min, max }: 계산된 두 극값을 매개변수로 받아서 축 도메인을 반환해요.

아래 데모는 -15부터 92까지의 데이터를 서로 다른 도메인 한계로 보여주면서 이러한 동작 차이를 설명해요.

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

export default function GroupedYAxes() {
  return (
    <BarChart
      layout="horizontal"
      yAxis={[
        {
          data: categoryData,
          scaleType: 'band',
          width: 120,
          groups: [
            // Extract main category
            { getValue: (category) => category[1] },
            // Extract subcategory
            {
              getValue: (category) => category[0],
              tickSize: 120,
              tickLabelStyle: {
                angle: -90,
                textAnchor: 'middle',
              },
            },
          ],
          valueFormatter: (value) => value.join(' - '),
        },
      ]}
      {...chartConfig}
    />
  );
}

const categoryData = [
  ['Technology', 'Software'],
  ['Technology', 'Hardware'],
  ['Technology', 'AI/ML'],
  ['Finance', 'Banking'],
  ['Finance', 'Insurance'],
  ['Finance', 'Investment'],
  ['Healthcare', 'Pharmaceuticals'],
  ['Healthcare', 'Medical Devices'],
  ['Healthcare', 'Telemedicine'],
];

const salesData = [150, 120, 200, 180, 90, 160, 140, 110, 85];
const profitData = [45, 35, 80, 65, 25, 55, 50, 40, 30];

const chartConfig = {
  height: 400,
  xAxis: [{ valueFormatter: (value: number) => `${value}K` }],
  series: [
    {
      data: salesData,
      label: 'Sales',
      valueFormatter: (value: number | null) => `${value}K`,
    },
    {
      data: profitData,
      label: 'Profit',
      valueFormatter: (value: number | null) => `${value}K`,
    },
  ],
};

Auto-sizing axes

You can set the axis height (for x-axes) or width (for y-axes) to 'auto' to automatically calculate the axis dimension based on the tick label measurements. This is useful when your tick labels have varying lengths or when you use rotated labels.

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

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

export default function AxisAutoSize() {
  const [useAutoSize, setUseAutoSize] = React.useState(true);

  return (
    <Box sx={{ width: '100%' }}>
      <Stack direction="row" spacing={1} sx={{ mb: 2 }}>
        <FormControlLabel
          checked={useAutoSize}
          control={
            <Checkbox onChange={(event) => setUseAutoSize(event.target.checked)} />
          }
          label="Use auto-sizing"
          labelPlacement="end"
        />
      </Stack>

      <BarChart
        xAxis={[
          {
            scaleType: 'band',
            dataKey: 'product',
            label: 'Products',
            height: useAutoSize ? 'auto' : undefined,
          },
        ]}
        yAxis={[
          {
            valueFormatter: (value: number) => currencyFormatter.format(value),
            label: 'Revenue',
            width: useAutoSize ? 'auto' : undefined,
          },
        ]}
        height={350}
        dataset={dataset}
        series={[
          { dataKey: 'q1', label: 'Q1' },
          { dataKey: 'q2', label: 'Q2' },
          { dataKey: 'q3', label: 'Q3' },
          { dataKey: 'q4', label: 'Q4' },
        ]}
      />
    </Box>
  );
}

const dataset = [
  { product: 'Electronics', q1: 125000, q2: 142000, q3: 158000, q4: 189000 },
  { product: 'Clothing', q1: 89000, q2: 95000, q3: 112000, q4: 145000 },
  { product: 'Home & Garden', q1: 67000, q2: 78000, q3: 85000, q4: 92000 },
  { product: 'Sports', q1: 45000, q2: 52000, q3: 68000, q4: 71000 },
  { product: 'Books', q1: 23000, q2: 28000, q3: 31000, q4: 42000 },
];

축 방향

기본적으로 축은 왼쪽에서 오른쪽으로, 아래에서 위로 진행돼요. reverse 속성을 적용해서 이 방향을 바꿀 수 있어요.

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

export default function AxisAutoSizeRotated() {
  const [angle, setAngle] = React.useState(-45);

  return (
    <Box sx={{ width: '100%' }}>
      <Typography id="angle-slider" gutterBottom>
        Tick label angle: {angle}°
      </Typography>
      <Slider
        aria-labelledby="angle-slider"
        value={angle}
        onChange={(_, value) => setAngle(value as number)}
        min={-90}
        max={90}
        step={5}
        marks={[
          { value: -90, label: '-90°' },
          { value: -45, label: '-45°' },
          { value: 0, label: '0°' },
          { value: 45, label: '45°' },
          { value: 90, label: '90°' },
        ]}
        sx={{ mb: 2, maxWidth: 400 }}
      />

      <LineChart
        xAxis={[
          {
            scaleType: 'band',
            data: months,
            height: 'auto',
            tickLabelStyle: {
              angle,
            },
          },
        ]}
        yAxis={[
          {
            width: 'auto',
          },
        ]}
        series={[
          {
            data: temperatureData,
            label: 'Temperature (°C)',
            showMark: false,
          },
        ]}
        height={350}
      />
    </Box>
  );
}

const months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December',
];

const temperatureData = [3, 5, 10, 15, 20, 25, 28, 27, 22, 15, 8, 4];

Auto-sizing also works with grouped axes. When an axis has groups defined, the auto-size calculation accounts for each group level's tick labels and tick sizes.

import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import { BarChart } from '@mui/x-charts/BarChart';
import {
  useXAxisCoordinates,
  useXAxis,
  useYAxisCoordinates,
  useYAxis,
  type AxisCoordinates,
} from '@mui/x-charts/hooks';

export default function GroupedAxesAutoSize() {
  const [useAutoSize, setUseAutoSize] = React.useState(true);

  return (
    <Box sx={{ width: '100%' }}>
      <Stack direction="row" spacing={1} sx={{ mb: 2 }}>
        <FormControlLabel
          checked={useAutoSize}
          control={
            <Checkbox onChange={(event) => setUseAutoSize(event.target.checked)} />
          }
          label="Use auto-sizing"
          labelPlacement="end"
        />
      </Stack>

      <BarChart
        xAxis={[
          {
            data,
            scaleType: 'band',
            id: 'x-bottom-1',
            position: 'bottom',
            height: useAutoSize ? 'auto' : undefined,
            groups: [
              { getValue: getMonth, tickSize: 10 },
              { getValue: getQuarter, tickSize: 34 },
              { getValue: getYear, tickSize: 60 },
            ],
            valueFormatter,
          },
        ]}
        yAxis={[
          {
            id: 'y-left-1',
            position: 'left',
            valueFormatter: (value: number) => `${value.toFixed(0)}%`,
          },
        ]}
        height={300}
        margin={{ bottom: 0, left: 0 }}
        series={[
          {
            data: getPercents(revenue),
            label: 'Revenue',
            valueFormatter: (value: number | null) => `${(value ?? 0).toFixed(0)}%`,
          },
          {
            data: getPercents(expenses),
            label: 'Expenses',
            valueFormatter: (value: number | null) => `${(value ?? 0).toFixed(0)}%`,
          },
        ]}
      >
        <XAxisPositionIndicator axisId="x-bottom-1" color={'#e63946'} />
        <YAxisPositionIndicator axisId="y-left-1" color={'#8338ec'} />
      </BarChart>
    </Box>
  );
}

const getMonth = (date: Date) =>
  date.toLocaleDateString('en-US', { month: 'short' });

const getQuarter = (date: Date) => `Q${Math.floor(date.getMonth() / 3) + 1}`;

const getYear = (date: Date) =>
  date.toLocaleDateString('en-US', { year: 'numeric' });

const valueFormatter = (v: Date) =>
  v.toLocaleDateString('en-US', {
    month: 'short',
    year: 'numeric',
  });

const data = [
  new Date(2014, 11, 1),
  new Date(2015, 0, 1),
  new Date(2015, 1, 1),
  new Date(2015, 2, 1),
  new Date(2015, 3, 1),
  new Date(2015, 4, 1),
  new Date(2015, 5, 1),
  new Date(2015, 6, 1),
  new Date(2015, 7, 1),
  new Date(2015, 8, 1),
  new Date(2015, 9, 1),
  new Date(2015, 10, 1),
  new Date(2015, 11, 1),
  new Date(2016, 0, 1),
];

const revenue = [
  3190, 4000, 3000, 2000, 2780, 1890, 2390, 3490, 2400, 1398, 9800, 3908, 4800, 2040,
];

const expenses = [
  1200, 2400, 1398, 9800, 3908, 4800, 3800, 4300, 2181, 2500, 2100, 3000, 2000, 2040,
];

const getPercents = (array: number[]) =>
  array.map((v, index) => (100 * v) / (revenue[index] + expenses[index]));

function XAxisPositionIndicator({
  axisId,
  color,
}: {
  axisId: string;
  color: string;
}) {
  const xPosition = useXAxisCoordinates(axisId);
  const xAxis = useXAxis(axisId);

  if (!xPosition) {
    return null;
  }

  return (
    <AxisPositionIndicator
      position={xAxis.position ?? 'bottom'}
      coordinates={xPosition}
      color={color}
    />
  );
}

function YAxisPositionIndicator({
  axisId,
  color,
}: {
  axisId: string;
  color: string;
}) {
  const yPosition = useYAxisCoordinates(axisId);
  const yAxis = useYAxis(axisId);

  if (!yPosition) {
    return null;
  }

  return (
    <AxisPositionIndicator
      position={yAxis.position ?? 'left'}
      coordinates={yPosition}
      color={color}
    />
  );
}

function AxisPositionIndicator({
  position,
  coordinates,
  color,
}: {
  position: 'top' | 'bottom' | 'left' | 'right' | 'none';
  coordinates: AxisCoordinates;
  color: string;
}) {
  if (position === 'none') {
    return null;
  }

  return (
    <rect
      x={coordinates.left}
      y={coordinates.top}
      width={coordinates.right - coordinates.left}
      height={coordinates.bottom - coordinates.top}
      fill={color}
      fillOpacity={0.2}
      stroke={color}
      strokeWidth={2}
    />
  );
}

위치

축 설정의 position 속성으로 축 위치를 커스터마이즈할 수 있어요. 이 속성은 다음 값을 기대해요.

  • x축은 'top' 또는 'bottom'
  • y축은 'left' 또는 'right'
  • 축을 숨기려면 'none'
import * as React from 'react';
import Stack from '@mui/material/Stack';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import { BarChart } from '@mui/x-charts/BarChart';
import { LineChart } from '@mui/x-charts/LineChart';

export default function SymlogScale() {
  const [chartType, setChartType] = React.useState('bar');

  const handleChartType = (event: any, newChartType: string) => {
    if (newChartType !== null) {
      setChartType(newChartType);
    }
  };

  return (
    <Stack sx={{ width: '100%', gap: 2 }}>
      <ToggleButtonGroup
        value={chartType}
        exclusive
        onChange={handleChartType}
        aria-label="chart type"
        fullWidth
      >
        {['bar', 'area'].map((type) => (
          <ToggleButton key={type} value={type}>
            {type}
          </ToggleButton>
        ))}
      </ToggleButtonGroup>
      {chartType === 'bar' && <SymlogBarChart />}
      {chartType === 'area' && <SymlogAreaChart />}
    </Stack>
  );
}

function SymlogBarChart() {
  return (
    <BarChart
      xAxis={[{ data: ['group A', 'group B', 'group C'] }]}
      yAxis={[{ scaleType: 'symlog', constant: 1, width: 52 }]}
      series={[
        { data: [4_000, 30, 50] },
        { data: [1, 600, 34] },
        { data: [20, 5, 60_000] },
      ]}
      height={500}
    />
  );
}

function SymlogAreaChart() {
  return (
    <LineChart
      xAxis={[{ data: [1, 2, 3, 5, 8, 10, 12, 15] }]}
      yAxis={[{ scaleType: 'symlog', width: 56 }]}
      series={[
        {
          data: [10, 1_000, 5_000, 10_000, -50_000, 20_000, 100_000, -500],
          area: true,
        },
      ]}
      height={500}
    />
  );
}

Composition

If you're using composition, you must provide the axis settings in the <ChartsContainer /> using the xAxis and yAxis props. This provides all the scaling properties to its children, and lets you use the <XAxis/> and <YAxis/> components as children.

In turn, those components require an axisId prop to link them to an axis you defined in the <ChartsContainer />. You can choose their position with the position prop which accepts 'top'/'bottom' for <XAxis /> and 'left'/'right' for <YAxis />. The props described in the rendering playground are also available.

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

export default function AxisWithComposition() {
  return (
    <Box sx={{ width: '100%', maxWidth: 600 }}>
      <ChartsContainer
        xAxis={[
          {
            scaleType: 'band',
            data: ['Q1', 'Q2', 'Q3', 'Q4'],
            id: 'quarters',
            label: 'Quarters',
            height: 50,
          },
        ]}
        yAxis={[
          { id: 'money', position: 'right', width: 65 },
          { id: 'quantities', position: 'left', width: 65 },
        ]}
        series={[
          {
            type: 'line',
            id: 'revenue',
            yAxisId: 'money',
            data: [5645, 7542, 9135, 12221],
          },
          {
            type: 'bar',
            id: 'cookies',
            yAxisId: 'quantities',
            data: [3205, 2542, 3135, 8374],
          },
          {
            type: 'bar',
            id: 'icecream',
            yAxisId: 'quantities',
            data: [1645, 5542, 5146, 3735],
          },
        ]}
        height={400}
      >
        <BarPlot />
        <LinePlot />
        <ChartsXAxis
          axisId="quarters"
          label="2021 quarters"
          labelStyle={{ fontSize: 18 }}
        />
        <ChartsYAxis axisId="quantities" label="# units sold" />
        <ChartsYAxis axisId="money" label="revenue" />
      </ChartsContainer>
    </Box>
  );
}

축 숨기기

축을 숨기려면 position을 'none'으로 설정해요. 단, 축은 여전히 계산되고 스케일링에 사용된다는 점을 기억하세요.

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

const timeData = [
  new Date(2023, 7, 31),
  new Date(2023, 7, 31, 12),
  new Date(2023, 8, 1),
  new Date(2023, 8, 1, 12),
  new Date(2023, 8, 2),
  new Date(2023, 8, 2, 12),
  new Date(2023, 8, 3),
  new Date(2023, 8, 3, 12),
  new Date(2023, 8, 4),
];

const y1 = [5, 5, 10, 90, 85, 70, 30, 25, 25];
const y2 = [90, 85, 70, 25, 23, 40, 45, 40, 50];

const config = {
  series: [
    { type: 'line', data: y1 },
    { type: 'line', data: y2 },
  ] as LineSeriesType[],
  height: 400,
  xAxis: [
    {
      data: timeData,
      scaleType: 'time',
      valueFormatter: (date: Date) =>
        date.getHours() === 0
          ? date.toLocaleDateString('fr-FR', {
              month: '2-digit',
              day: '2-digit',
            })
          : date.toLocaleTimeString('fr-FR', {
              hour: '2-digit',
            }),
    } as const,
  ],
};

export default function ReferenceLine() {
  return (
    <Box sx={{ width: '100%', maxWidth: 600 }}>
      <ChartsContainer {...config}>
        <LinePlot />
        <ChartsReferenceLine
          x={new Date(2023, 8, 2, 9)}
          lineStyle={{ strokeDasharray: '10 5' }}
          labelStyle={{ fontSize: '10', lineHeight: 1.2 }}
          label={`Wake up\n9AM`}
          labelAlign="start"
        />
        <ChartsReferenceLine y={50} label="Middle value" labelAlign="end" />
        <ChartsXAxis />
        <ChartsYAxis />
      </ChartsContainer>
    </Box>
  );
}

더 알아보기 (Learn more)