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

Charts - 축 커스터마이징

원문 보기 위키 갱신

차트 축이 렌더링되고 스타일링되는 방식을 커스터마이즈할 수 있어요.

출처: MUI X documentation

본문

축 정의 외에도 축이 렌더링되는 방식을 더 세부적으로 커스터마이즈할 수 있는 방법이 몇 가지 더 있어요.

축 스타일링

특정 축을 그 ID로 지정하려면 data-axis-id 속성을 선택자로 사용하세요. 축이 여러 개일 때 서로 다르게 스타일링하고 싶을 때 유용해요.

아래 예제에서는 revenue 축 라벨을 teal 색으로, profit 축 라벨을 blue 색으로 스타일링해서 각각의 시리즈와 맞췄어요.

import * as React from 'react';
import { LineChart, type LineChartProps } from '@mui/x-charts/LineChart';
import { axisClasses } from '@mui/x-charts/ChartsAxis';

const years = [2010, 2011, 2012, 2013, 2014, 2015];
const revenue = [4000, 3000, 2000, 2780, 1890, 2390];
const profit = [24, 13, 98, 39, 48, 38];

const chartConfig: LineChartProps = {
  xAxis: [{ data: years, scaleType: 'point' }],
  yAxis: [
    { id: 'revenue-axis', label: 'Revenue ($)' },
    { id: 'profit-axis', label: 'Profit (%)', position: 'right' },
  ],
  series: [
    { data: revenue, label: 'Revenue', yAxisId: 'revenue-axis', color: '#02b2af' },
    { data: profit, label: 'Profit', yAxisId: 'profit-axis', color: '#2e96ff' },
  ],
  height: 300,
};

export default function AxisIdStyling() {
  return (
    <LineChart
      sx={{
        // Style the axis with id "revenue-axis"
        [`& .${axisClasses.root}[data-axis-id="revenue-axis"] .${axisClasses.label}`]:
          {
            fill: '#02b2af',
          },
        // Style the axis with id "profit-axis"
        [`& .${axisClasses.root}[data-axis-id="profit-axis"] .${axisClasses.label}`]:
          {
            fill: '#2e96ff',
          },
      }}
      {...chartConfig}
    />
  );
}

그룹화된 축 스타일링

틱 크기

groups 배열에 tickSize 속성을 제공하면 각 그룹화된 축의 틱 크기를 커스터마이즈할 수 있어요. tickSize는 틱 라벨 위치에도 영향을 줘요. 배열의 각 항목은 getValue() 함수에서 정의한 그룹에 대응해요.

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

export default function GroupedAxesTickSize() {
  return (
    <BarChart
      xAxis={[
        {
          data,
          height: 32,
          groups: [
            {
              getValue: getMonth,
              tickSize: 0,
            },
            {
              getValue: formatQuarterYear,
              tickSize: 32,
            },
          ],
          valueFormatter,
        },
      ]}
      {...chartConfig}
    />
  );
}

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

const formatQuarterYear = (date: Date) => {
  const quarter = Math.floor(date.getMonth() / 3) + 1;
  const year = date.getFullYear().toString().slice(-2);
  return `Q${quarter} '${year}`;
};

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

const data = [
  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),
];
const a = [4000, 3000, 2000, 2780, 1890, 2390, 3490, 2400, 1398, 9800, 3908, 4800];
const b = [2400, 1398, 9800, 3908, 4800, 3800, 4300, 2181, 2500, 2100, 3000, 2000];

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;

그룹 선택하기

특정 그룹을 지정하려면 data-group-index 속성을 선택자로 사용하세요. 아래 예제에서는 마지막 그룹에 노란색 틱 색을, 첫 번째 그룹에 파란색 텍스트를 적용했어요.

import { LineChart } from '@mui/x-charts/LineChart';
import { axisClasses } from '@mui/x-charts/ChartsAxis';

export default function GroupedAxesStyling() {
  return (
    <LineChart
      sx={{
        [`& [data-group-index="1"] .${axisClasses.tick}`]: {
          stroke: 'rgb(255, 180, 34)',
        },
        [`& [data-group-index="0"] .${axisClasses.tickLabel}`]: {
          fill: 'rgb(66, 84, 251)',
        },
      }}
      xAxis={[
        {
          data,
          scaleType: 'point',
          groups: [{ getValue: getMonth }, { getValue: formatQuarterYear }],
          valueFormatter,
        },
      ]}
      {...chartConfig}
    />
  );
}
const getMonth = (date: Date) =>
  date.toLocaleDateString('en-US', { month: 'short' });
const formatQuarterYear = (date: Date) => {
  const quarter = Math.floor(date.getMonth() / 3) + 1;
  const year = date.getFullYear().toString().slice(-2);
  return `Q${quarter} '${year}`;
};

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

const data = [
  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 = [
  4000, 3000, 2000, 2780, 1890, 2390, 3490, 2400, 1398, 9800, 3908, 4800, 2040,
];
const b = [
  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;

틱 라벨 넘침 문제 해결하기

틱 라벨이 너무 길면 넘침을 방지하기 위해 잘려요. 넘침으로 인한 잘림을 줄이려면 틱 라벨에 각도를 적용하거나, 자동 크기 조정을 사용하거나, 축 크기를 늘려 라벨을 수용하면 돼요. 아래 데모에서는 x축과 y축의 크기를 수정해서 틱 라벨에 쓸 공간을 늘렸어요.

첫 번째와 마지막 틱 라벨은 마진으로 삐져나올 수 있는데, 그 마진이 라벨을 표시하기에 부족하면 잘릴 수 있어요. 이를 피하려면 margin prop으로 차트와 컨테이너 가장자리 사이의 공간을 늘리면 돼요.

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

export default function MarginAndLabelPosition() {
  const [fixMargin, setFixMargin] = React.useState(true);

  return (
    <Box sx={{ width: '100%' }}>
      <Stack direction="row" spacing={1} sx={{ mb: 2 }}>
        <FormControlLabel
          checked={fixMargin}
          control={
            <Checkbox onChange={(event) => setFixMargin(event.target.checked)} />
          }
          label="Increase axes size"
          labelPlacement="end"
        />
      </Stack>

      <BarChart
        xAxis={[
          {
            scaleType: 'band',
            dataKey: 'code',
            valueFormatter: (value, context) =>
              context.location === 'tick'
                ? value.split('').join('\n')
                : usAirportPassengers.find((item) => item.code === value)!.fullName,
            label: 'airports',
            height: fixMargin ? 75 : undefined,
          },
        ]}
        // Other props
        height={300}
        dataset={usAirportPassengers}
        series={[
          { dataKey: '2018', label: '2018' },
          { dataKey: '2019', label: '2019' },
          { dataKey: '2020', label: '2020' },
          { dataKey: '2021', label: '2021' },
          { dataKey: '2022', label: '2022' },
        ]}
        hideLegend
        yAxis={[
          {
            valueFormatter: (value: number) => `${(value / 1000).toLocaleString()}k`,
            label: 'passengers',
            width: fixMargin ? 85 : undefined,
          },
        ]}
      />
    </Box>
  );
}

const usAirportPassengers = [
  {
    fullName: 'Hartsfield–Jackson Atlanta International Airport',
    code: 'ATL',
    2022: 45396001,
    2021: 36676010,
    2020: 20559866,
    2019: 53505795,
    2018: 51865797,
  },
  {
    fullName: 'Dallas/Fort Worth International Airport',
    code: 'DFW',
    2022: 35345138,
    2021: 30005266,
    2020: 18593421,
    2019: 35778573,
    2018: 32821799,
  },
  {
    fullName: 'Denver International Airport',
    code: 'DEN',
    2022: 33773832,
    2021: 28645527,
    2020: 16243216,
    2019: 33592945,
    2018: 31362941,
  },
  {
    fullName: "O'Hare International Airport",
    code: 'ORD',
    2022: 33120474,
    2021: 26350976,
    2020: 14606034,
    2019: 40871223,
    2018: 39873927,
  },
  {
    fullName: 'Los Angeles International Airport',
    code: 'LAX',
    2022: 32326616,
    2021: 23663410,
    2020: 14055777,
    2019: 42939104,
    2018: 42624050,
  },
  {
    fullName: 'John F. Kennedy International Airport',
    code: 'JFK',
    2022: 26919982,
    2021: 15273342,
    2020: 8269819,
    2019: 31036655,
    2018: 30620769,
  },
  {
    fullName: 'Harry Reid International Airport',
    code: 'LAS',
    2022: 25480500,
    2021: 19160342,
    2020: 10584059,
    2019: 24728361,
    2018: 23795012,
  },
  {
    fullName: 'Orlando International Airport',
    code: 'MCO',
    2022: 24469733,
    2021: 19618838,
    2020: 10467728,
    2019: 24562271,
    2018: 23202480,
  },
  {
    fullName: 'Miami International Airport',
    code: 'MIA',
    2022: 23949892,
    2021: 17500096,
    2020: 8786007,
    2019: 21421031,
    2018: 21021640,
  },
  {
    fullName: 'Charlotte Douglas International Airport',
    code: 'CLT',
    2022: 23100300,
    2021: 20900875,
    2020: 12952869,
    2019: 24199688,
    2018: 22281949,
  },
  {
    fullName: 'Seattle–Tacoma International Airport',
    code: 'SEA',
    2022: 22157862,
    2021: 17430195,
    2020: 9462411,
    2019: 25001762,
    2018: 24024908,
  },
  {
    fullName: 'Phoenix Sky Harbor International Airport',
    code: 'PHX',
    2022: 21852586,
    2021: 18940287,
    2020: 10531436,
    2019: 22433552,
    2018: 21622580,
  },
  {
    fullName: 'Newark Liberty International Airport',
    code: 'EWR',
    2022: 21572147,
    2021: 14514049,
    2020: 7985474,
    2019: 23160763,
    2018: 22797602,
  },
  {
    fullName: 'San Francisco International Airport',
    code: 'SFO',
    2022: 20411420,
    2021: 11725347,
    2020: 7745057,
    2019: 27779230,
    2018: 27790717,
  },
  {
    fullName: 'George Bush Intercontinental Airport',
    code: 'IAH',
    2022: 19814052,
    2021: 16242821,
    2020: 8682558,
    2019: 21905309,
    2018: 21157398,
  },
  {
    fullName: 'Logan International Airport',
    code: 'BOS',
    2022: 17443775,
    2021: 10909817,
    2020: 6035452,
    2019: 20699377,
    2018: 20006521,
  },
  {
    fullName: 'Fort Lauderdale–Hollywood International Airport',
    code: 'FLL',
    2022: 15370165,
    2021: 13598994,
    2020: 8015744,
    2019: 17950989,
    2018: 17612331,
  },
  {
    fullName: 'Minneapolis–Saint Paul International Airport',
    code: 'MSP',
    2022: 15242089,
    2021: 12211409,
    2020: 7069720,
    2019: 19192917,
    2018: 18361942,
  },
  {
    fullName: 'LaGuardia Airport',
    code: 'LGA',
    2022: 14367463,
    2021: 7827307,
    2020: 4147116,
    2019: 15393601,
    2018: 15058501,
  },
  {
    fullName: 'Detroit Metropolitan Airport',
    code: 'DTW',
    2022: 13751197,
    2021: 11517696,
    2020: 6822324,
    2019: 18143040,
    2018: 17436837,
  },
];

props 전달하기

아래 데모는 축 렌더링을 커스터마이즈할 수 있는 모든 props를 보여줘요:

import Box from '@mui/material/Box';
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
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 defaultXAxis = {
  disableLine: false,
  disableTicks: false,
  fontSize: 12,
  label: 'My axis',
  tickSize: 6,
};
export default function AxisCustomization() {
  return (
    <ChartsUsageDemo
      componentName="Alert"
      data={{
        disableLine: { knob: 'switch', defaultValue: false },
        disableTicks: { knob: 'switch', defaultValue: false },
        label: { knob: 'input', defaultValue: 'my axis' },
        tickSize: { knob: 'number', defaultValue: 6 },
      }}
      renderDemo={(props) => (
        <Box sx={{ width: '100%', maxWidth: 400 }}>
          <ScatterChart
            series={[
              {
                type: 'scatter',
                id: 'linear',
                data,
              },
            ]}
            yAxis={[{ position: 'none' }]}
            xAxis={[
              {
                ...defaultXAxis,
                ...props,
              },
            ]}
            height={300}
          />
        </Box>
      )}
      getCode={({
        props,
      }) => `import { ScatterChart } from '@mui/x-charts/ScatterChart';

<ScatterChart
  // ...
  xAxis={{
    disableLine: ${props.disableLine},
    disableTicks: ${props.disableTicks},
    label: "${props.label}",
    tickSize: ${props.tickSize},
  }}
/>
`}
    />
  );
}

텍스트 커스터마이징

텍스트 요소(틱 라벨과 축 라벨)를 커스터마이즈하려면 축 설정의 tickLabelStyle과 labelStyle 속성을 사용하세요.

설정하지 않으면 textAnchor와 dominantBaseline 속성의 기본값은 angle 속성의 값에 따라 달라져요. 이 값들이 어떻게 동작하고 서로 어떻게 관련되는지는 아래 데모에서 테스트해 볼 수 있어요:

import Box from '@mui/material/Box';
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
import { BarChart } from '@mui/x-charts/BarChart';
import { dataset, valueFormatter } from '../dataset/weather';

const chartSetting = {
  height: 300,
};

export default function AxisTextCustomization() {
  return (
    <ChartsUsageDemo
      componentName="Alert"
      data={
        {
          angle: { knob: 'number', defaultValue: 45, min: -180, max: 180 },
          textAnchor: {
            knob: 'select',
            defaultValue: 'undefined',
            options: ['undefined', 'start', 'middle', 'end'],
          },
          dominantBaseline: {
            knob: 'select',
            defaultValue: 'undefined',
            options: ['undefined', 'auto', 'central', 'hanging'],
          },
          fontSize: { knob: 'number', defaultValue: 12 },
          labelFontSize: { knob: 'number', defaultValue: 14 },
        } as const
      }
      renderDemo={(props) => (
        <Box sx={{ width: '100%', maxWidth: 400 }}>
          <BarChart
            dataset={dataset}
            xAxis={[
              {
                dataKey: 'month',
                label: 'months',
                height: 60,
                labelStyle: {
                  fontSize: props.labelFontSize,
                },
                tickLabelStyle: {
                  angle: props.angle,
                  ...(props.textAnchor === 'undefined'
                    ? {}
                    : { textAnchor: props.textAnchor }),
                  ...(props.dominantBaseline === 'undefined'
                    ? {}
                    : { dominantBaseline: props.dominantBaseline }),
                  fontSize: props.fontSize,
                },
              },
            ]}
            series={[
              { dataKey: 'london', label: 'London', valueFormatter },
              { dataKey: 'paris', label: 'Paris', valueFormatter },
              { dataKey: 'newYork', label: 'New York', valueFormatter },
              { dataKey: 'seoul', label: 'Seoul', valueFormatter },
            ]}
            {...chartSetting}
          />
        </Box>
      )}
      getCode={({ props }) => `import { BarChart } from '@mui/x-charts/BarChart';

<BarChart
  // ...
  xAxis={[
    {
      labelStyle: {
        fontSize: ${props.labelFontSize},
      },
      tickLabelStyle: {
        angle: ${props.angle},${
          props.textAnchor === 'undefined'
            ? ''
            : `
        textAnchor: '${props.textAnchor}',`
        }${
          props.dominantBaseline === 'undefined'
            ? ''
            : `
        dominantBaseline: '${props.dominantBaseline}',`
        }
        fontSize: ${props.fontSize},
      },
    },
  ]}
/>`}
    />
  );
}

틱 라벨 아이콘 추가하기

foreignObject 요소를 사용하면 SVG 안에 non-SVG 요소를 렌더링할 수 있어요. 이를 활용해 차트 데이터와 상호작용하는 컴포넌트를 만들 수 있어요. 아래 데모에서는 텍스트 아래에 아이콘을 표시해서 커스텀 틱 라벨을 만들었어요.

foreignObject를 사용하면 차트 내보내기가 되지 않을 수 있다는 점을 유의하세요.

import * as React from 'react';
import Box from '@mui/material/Box';
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 { ChartsTextProps } from '@mui/x-charts/ChartsText';
import { iconMap } from '../dataset/company.icons';

function CustomTick(props: ChartsTextProps) {
  const { x, y, text } = props;
  const logo = iconMap[text];

  return (
    <g transform={`translate(${x},${y})`}>
      <foreignObject x={-20} y={-10} width={40} height={40}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          }}
        >
          <Box
            sx={{
              width: '100%',
              height: '100%',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            {logo && (
              <img
                src={logo}
                alt={text}
                style={{
                  width: '40px',
                  height: '40px',
                  objectFit: 'contain',
                }}
              />
            )}
          </Box>
        </div>
      </foreignObject>
    </g>
  );
}

export default function TickLabelImage() {
  return (
    <Box sx={{ width: '100%', maxWidth: 600 }}>
      <ChartsContainer
        xAxis={[
          {
            scaleType: 'band',
            data: ['Netflix', 'Alphabet', 'Microsoft'],
            id: 'companies',
          },
        ]}
        yAxis={[{ id: 'revenue', position: 'left', width: 60 }]}
        series={[
          {
            type: 'bar',
            yAxisId: 'revenue',
            data: [39, 350, 245.1],
          },
        ]}
        height={300}
      >
        <BarPlot />
        <ChartsXAxis axisId="companies" slots={{ axisTickLabel: CustomTick }} />
        <ChartsYAxis axisId="revenue" label="FY 2024 revenue in USD Billions" />
      </ChartsContainer>
    </Box>
  );
}

커스텀 축 렌더링

xAxis 또는 yAxis 슬롯에 컴포넌트를 제공하면 축과 틱이 렌더링되는 방식을 완전히 커스터마이즈할 수 있어요. 커스텀 축을 만드는 방법에 대한 자세한 내용은 조합(composition) 섹션을 참고하세요.

같은 기법으로 틱 라벨을 플롯 안쪽으로 옮길 수도 있어요. 그리드 위의 라벨에서 확인할 수 있어요.

import * as React from 'react';
import { useTheme } from '@mui/material/styles';
import { BarChart, BarChartProps } from '@mui/x-charts/BarChart';
import { ChartsYAxisProps } from '@mui/x-charts/models';
import { rainbowSurgePalette } from '@mui/x-charts/colorPalettes';
import { useYAxes, useYAxisCoordinates, useYAxisTicks } from '@mui/x-charts/hooks';

const labels = [
  'Server Products',
  'Enterprise Services',
  'M365 Commercial',
  'M365 Consumer',
  'LinkedIn',
  'Dynamics',
  'Gaming',
  'Windows & Devices',
  'Search & News Ads',
];

const data = [98.4, 7.7, 87.7, 7.4, 17.8, 7.8, 23.4, 17.3, 13.8];

const chartSetting = {
  height: 400,
  margin: { left: 0 },
  layout: 'horizontal',
  xAxis: [{ id: 'x' }],
  yAxis: [{ id: 'y', scaleType: 'band', data: labels, width: 4 }],
} satisfies Partial<BarChartProps>;

export default function CustomAxisTicks() {
  const theme = useTheme();
  const seriesColor = rainbowSurgePalette(theme.palette.mode)[
    theme.palette.mode === 'dark' ? 0 : 1
  ];

  return (
    <BarChart
      {...chartSetting}
      slots={{ yAxis: YAxis }}
      series={[{ data, color: seriesColor }]}
    />
  );
}

function YAxis(props: ChartsYAxisProps) {
  const theme = useTheme();
  const { yAxisIds } = useYAxes();
  const axisId = props.axisId ?? yAxisIds[0];

  // The top, left, right, bottom of the axis according to the charts settings
  const axisCoordinates = useYAxisCoordinates(axisId);

  // The array of ticks to place according to the settings
  const ticks = useYAxisTicks(axisId);

  if (!axisCoordinates) {
    return null;
  }

  return (
    <React.Fragment>
      <line
        x1={axisCoordinates.right}
        x2={axisCoordinates.right}
        y1={axisCoordinates.top}
        y2={axisCoordinates.bottom}
        stroke={(theme.vars || theme).palette.text.primary}
      />
      {ticks.map((tick, index) => (
        <g
          key={index}
          transform={`translate(${axisCoordinates.right}, ${tick.offset})`}
        >
          <line x1={-4} x2={4} stroke={(theme.vars || theme).palette.text.primary} />

          <text
            x={8}
            y={tick.labelOffset}
            dominantBaseline="central"
            textAnchor="start"
            fill={theme.palette.text.primary}
            fontSize={12}
          >
            {tick.formattedValue ?? ''}
          </text>
        </g>
      ))}
    </React.Fragment>
  );
}

더 알아보기 (Learn more)