차트 - 축 눈금과 그리드
축 눈금(tick)과 차트 그리드(grid)를 설정하는 방법을 알아봅시다.
본문
그리드 (Grid)
grid prop을 사용하면 카테시안(Cartesian) 차트의 배경에 그리드를 추가할 수 있어요. 이 prop은 vertical과 horizontal 속성을 가진 객체를 받는데, 각각을 true로 설정하면 해당 방향의 선이 생성됩니다.
composition을 사용한다면 아래처럼 <ChartsGrid /> 컴포넌트에 prop으로 전달할 수 있어요.
<BarChart grid={{ vertical: true }}>
<ChartsContainer>
<ChartsGrid vertical />
</ChartsContainer>
이 데모에서는 수평 그리드를 몇 가지 CSS 선택자로 커스터마이즈했습니다.
import { chartsGridClasses } from '@mui/x-charts/ChartsGrid';
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 GridDemo() {
return (
<BarChart
dataset={dataset}
xAxis={[{ dataKey: 'month' }]}
series={[{ dataKey: 'seoul', label: 'Seoul rainfall', valueFormatter }]}
grid={{ horizontal: true }}
sx={{
[`& .${chartsGridClasses.line}`]: { strokeDasharray: '5 3', strokeWidth: 2 },
}}
{...chartSetting}
/>
);
}
그리드 위의 라벨 (Labels on the grid)
가로 공간이 부족할 때는 y축을 제거하고 그 값을 그리드 선 위에 표시할 수도 있어요.
y축의 width를 0으로 설정하면 공간을 차지하지 않게 되고, yAxis slot에 컴포넌트를 제공하면 됩니다. useYAxisTicks() 훅은 축의 눈금을, useDrawingArea()는 데이터가 그려지는 영역을 반환해요. 이 둘을 함께 사용하면 각 그리드 선 위에 라벨을 하나씩 배치할 수 있습니다.
:::info
position: 'none'으로 설정해도 공간은 확보되지만, 그러면 축이 차트에서 제거되어 yAxis slot이 더 이상 렌더링되지 않아요.
:::
import * as React from 'react';
import { LineChart, lineClasses } from '@mui/x-charts/LineChart';
import { chartsGridClasses } from '@mui/x-charts/ChartsGrid';
import { ChartsYAxisProps } from '@mui/x-charts/models';
import { useDrawingArea, useYAxes, useYAxisTicks } from '@mui/x-charts/hooks';
import { dataset, valueFormatter } from '../dataset/weather';
const LABEL_GAP = 4;
function GridLabelsYAxis(props: ChartsYAxisProps) {
const { yAxisIds } = useYAxes();
const axisId = props.axisId ?? yAxisIds[0];
const ticks = useYAxisTicks(axisId);
const { left } = useDrawingArea();
return (
<React.Fragment>
{ticks.map((tick) => (
<text
key={tick.value}
x={left + LABEL_GAP}
y={tick.offset - LABEL_GAP}
textAnchor="start"
className="grid-label"
>
{tick.formattedValue}
</text>
))}
</React.Fragment>
);
}
export default function GridLabels() {
return (
<LineChart
dataset={dataset}
xAxis={[{ dataKey: 'month', scaleType: 'point' }]}
// A width of 0 gives the space back to the drawing area.
yAxis={[{ width: 0, valueFormatter }]}
series={[
{ dataKey: 'london', label: 'London rainfall', area: true, valueFormatter },
]}
slots={{ yAxis: GridLabelsYAxis }}
grid={{ horizontal: true }}
hideLegend
height={300}
sx={(theme) => ({
[`& .${chartsGridClasses.horizontalLine}`]: { strokeDasharray: '4 4' },
// A lighter area keeps the grid and its labels visible behind the data.
[`& .${lineClasses.area}`]: { fillOpacity: 0.3 },
'& .grid-label': {
fill: (theme.vars || theme).palette.text.secondary,
fontSize: 12,
// Outline the text so that it stays readable over the area.
stroke: (theme.vars || theme).palette.background.paper,
strokeWidth: 3,
paintOrder: 'stroke',
},
})}
/>
);
}
눈금 위치 (Tick position)
자동 눈금 위치 (Automatic tick position)
tickNumber 속성으로 눈금의 개수를 커스터마이즈할 수 있어요.
:::info
이 숫자가 실제로 표시되는 눈금의 정확한 개수를 의미하는 것은 아니에요. D3가 사람이 읽기 좋게 눈금을 자동으로 배치하기 때문에, 제공된 tickNumber를 기준으로 필요에 따라 반올림하거나 반내림합니다.
예를 들어 tickNumber=5로 설정했는데 축에 표시할 연도가 4개뿐이라면, 4년을 5로 나누는 대신 총 4개의 눈금(연도별 1개)을 렌더링해요.
:::
눈금이 더 잘 제어되도록 tickMinStep과 tickMaxStep을 제공할 수도 있어요. 이 값들은 두 눈금 사이의 간격이 최솟값과 최댓값을 따르도록 tickNumber를 계산해 줍니다.
아래 데모에서 위쪽 축은 tickMinStep이 하루의 절반이고, 아래쪽 축은 하루 전체입니다.
import Box from '@mui/material/Box';
import { LineChart } from '@mui/x-charts/LineChart';
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 valueFormatter = (date: Date) =>
date.getHours() === 0
? date.toLocaleDateString('fr-FR', {
month: '2-digit',
day: '2-digit',
})
: date.toLocaleTimeString('fr-FR', {
hour: '2-digit',
});
const config = {
series: [{ data: y1 }, { data: y2 }],
height: 300,
};
const xAxisCommon = {
data: timeData,
scaleType: 'time',
valueFormatter,
} as const;
export default function TickNumber() {
return (
<Box sx={{ width: '100%', maxWidth: 800 }}>
<LineChart
xAxis={[
{
...xAxisCommon,
tickMinStep: 3600 * 1000 * 24, // min step: 24h
},
{
...xAxisCommon,
id: 'half days',
position: 'top',
tickMinStep: 3600 * 1000 * 12, // min step: 12hu
},
]}
yAxis={[{ position: 'none' }]}
{...config}
/>
</Box>
);
}
눈금 간격 (Tick spacing)
tickSpacing 속성으로 두 눈금 사이의 최소 픽셀 간격을 정의할 수 있어요.
눈금 사이에 최소 공간을 두면 축의 가독성이 좋아지고 차트 성능도 개선될 수 있어요.
이 속성은 기본값이 0이며, 밴드(band) 또는 포인트(point) 스케일을 가진 순서형(ordinal) 축에서만 사용할 수 있습니다.
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Slider from '@mui/material/Slider';
import Typography from '@mui/material/Typography';
import { BarChartPro } from '@mui/x-charts-pro/BarChartPro';
import data from '../dataset/sp500-intraday.json';
const tickLabelDateFormatter = new Intl.DateTimeFormat(undefined, {
month: 'short',
day: 'numeric',
});
export default function TickSpacing() {
const [tickSpacing, setTickSpacing] = React.useState(50);
return (
<Stack direction="column" sx={{ gap: 4, width: '100%' }}>
<Stack
direction="column"
spacing={1}
sx={{ flex: 1, width: '100%', maxWidth: 400, alignSelf: 'center' }}
>
<Typography gutterBottom id="tickSpacing">
Tick Spacing
</Typography>
<Slider
value={tickSpacing}
onChange={(event, value) => setTickSpacing(value as number)}
valueLabelDisplay="auto"
min={0}
max={100}
step={5}
sx={{ mt: 2 }}
aria-labelledby="tickSpacing"
/>
</Stack>
<BarChartPro
xAxis={[
{
data: data.map((d) => new Date(Date.parse(d.date))),
valueFormatter: (v: Date) => tickLabelDateFormatter.format(v),
tickSpacing,
tickPlacement: 'middle',
zoom: true,
},
]}
series={[{ data: data.map((d) => d.close), label: 'Close' }]}
height={300}
/>
</Stack>
);
}
고정 눈금 위치 (Fixed tick position)
눈금 위치를 더 세밀하게 제어하고 싶다면 tickInterval 속성을 사용할 수 있어요. 이 속성은 눈금이 배치될 정확한 위치를 정의하는 값 배열을 받습니다.
'point' 스케일 타입을 가진 축에서는 tickInterval 속성을 (value, index) => boolean 형태의 필터링 함수로 사용할 수 있어요.
아래 데모에서 두 축 모두 scaleType='point'로 설정되어 있습니다. 위쪽 축은 각 포인트마다 눈금이 있는 기본 동작을 보여주고, 아래쪽 축은 필터링 함수를 사용해서 하루의 시작 부분에만 눈금을 표시해요.
import Box from '@mui/material/Box';
import { ShowMarkParams } from '@mui/x-charts/models';
import { LineChart } from '@mui/x-charts/LineChart';
export default function TickPosition() {
return (
<Box sx={{ width: '100%', maxWidth: 800 }}>
<LineChart
xAxis={[
{
...xAxisCommon,
scaleType: 'point',
tickInterval: (time) => time.getHours() === 0,
position: 'bottom',
},
{
...xAxisCommon,
scaleType: 'point',
position: 'top',
},
]}
{...config}
/>
</Box>
);
}
const valueFormatter = (date: Date) =>
date.toLocaleDateString('fr-FR', {
month: '2-digit',
day: '2-digit',
});
const timeData = [
new Date(2023, 7, 31),
new Date(2023, 7, 31, 3),
new Date(2023, 7, 31, 6),
new Date(2023, 7, 31, 9),
new Date(2023, 7, 31, 12),
new Date(2023, 7, 31, 15),
new Date(2023, 7, 31, 18),
new Date(2023, 8, 1),
new Date(2023, 8, 1, 3),
new Date(2023, 8, 1, 6),
new Date(2023, 8, 1, 9),
new Date(2023, 8, 1, 12),
new Date(2023, 8, 1, 15),
new Date(2023, 8, 1, 18),
new Date(2023, 8, 2),
new Date(2023, 8, 2, 3),
new Date(2023, 8, 2, 6),
new Date(2023, 8, 2, 9),
new Date(2023, 8, 2, 12),
new Date(2023, 8, 2, 15),
new Date(2023, 8, 2, 18),
new Date(2023, 8, 3),
new Date(2023, 8, 3, 3),
new Date(2023, 8, 3, 6),
new Date(2023, 8, 3, 9),
new Date(2023, 8, 3, 12),
new Date(2023, 8, 3, 15),
new Date(2023, 8, 3, 18),
new Date(2023, 8, 4),
];
const y1 = [
5, 5.5, 5.3, 4.9, 5, 6.2, 8.9, 10, 15, 30, 80, 90, 94, 93, 85, 86, 75, 70, 68, 50,
20, 30, 35, 28, 25, 27, 30, 28, 25,
];
const y2 = [
90, 93, 89, 84, 85, 83, 73, 70, 63, 32, 30, 25, 18, 19, 23, 30, 32, 36, 40, 40, 42,
45, 46, 42, 39, 40, 41, 43, 50,
];
const showMark = (params: ShowMarkParams) => {
const { position } = params as ShowMarkParams<Date>;
return position.getHours() === 0;
};
const config = {
series: [
{ data: y1, showMark },
{ data: y2, showMark },
],
height: 300,
yAxis: [{ position: 'none' as const }],
};
const xAxisCommon = {
data: timeData,
scaleType: 'time',
valueFormatter,
} as const;
눈금 라벨 필터링 (Filtering tick labels)
tickLabelInterval 속성을 사용하면 특정 눈금 부분 집합에만 라벨을 표시할 수 있어요. 이는 (value, index) => boolean 형태의 필터링 함수입니다. 예를 들어 tickLabelInterval: (value, index) => index % 2 === 0은 눈금 두 개마다 라벨을 하나씩 보여줍니다.
:::warning
value와 index 인자는 축 데이터가 아니라 눈금(tick)의 값입니다.
:::
기본적으로는 라벨이 서로 겹치지 않도록 눈금이 필터링됩니다. tickLabelInterval: () => true로 이 동작을 재정의하면, 모든 눈금마다 라벨을 강제로 표시할 수 있어요.
아래 예시에서 위쪽 축은 기본 동작의 기준입니다. 라벨이 넘치지 않아요. 아래쪽에서는 하루의 시작과 중간에 눈금이 하나씩 있지만, 라벨은 하루의 시작 부분에만 표시됩니다.
import Box from '@mui/material/Box';
import { ShowMarkParams } from '@mui/x-charts/models';
import { LineChart } from '@mui/x-charts/LineChart';
export default function TickLabelPosition() {
return (
<Box sx={{ width: '100%', maxWidth: 800 }}>
<LineChart
xAxis={[
{
...xAxisCommon,
id: 'bottomAxis',
scaleType: 'point',
tickInterval: (time) => [0, 12].includes(time.getHours()),
tickLabelInterval: (time) => time.getHours() === 0,
position: 'bottom',
},
{
...xAxisCommon,
id: 'topAxis',
scaleType: 'point',
position: 'top',
},
]}
yAxis={[{ position: 'none' }]}
{...config}
/>
</Box>
);
}
const valueFormatter = (date: Date) =>
date.toLocaleDateString('fr-FR', {
month: '2-digit',
day: '2-digit',
});
const timeData = [
new Date(2023, 7, 31),
new Date(2023, 7, 31, 3),
new Date(2023, 7, 31, 6),
new Date(2023, 7, 31, 9),
new Date(2023, 7, 31, 12),
new Date(2023, 7, 31, 15),
new Date(2023, 7, 31, 18),
new Date(2023, 8, 1),
new Date(2023, 8, 1, 3),
new Date(2023, 8, 1, 6),
new Date(2023, 8, 1, 9),
new Date(2023, 8, 1, 12),
new Date(2023, 8, 1, 15),
new Date(2023, 8, 1, 18),
new Date(2023, 8, 2),
new Date(2023, 8, 2, 3),
new Date(2023, 8, 2, 6),
new Date(2023, 8, 2, 9),
new Date(2023, 8, 2, 12),
new Date(2023, 8, 2, 15),
new Date(2023, 8, 2, 18),
new Date(2023, 8, 3),
new Date(2023, 8, 3, 3),
new Date(2023, 8, 3, 6),
new Date(2023, 8, 3, 9),
new Date(2023, 8, 3, 12),
new Date(2023, 8, 3, 15),
new Date(2023, 8, 3, 18),
new Date(2023, 8, 4),
];
const y1 = [
5, 5.5, 5.3, 4.9, 5, 6.2, 8.9, 10, 15, 30, 80, 90, 94, 93, 85, 86, 75, 70, 68, 50,
20, 30, 35, 28, 25, 27, 30, 28, 25,
];
const y2 = [
90, 93, 89, 84, 85, 83, 73, 70, 63, 32, 30, 25, 18, 19, 23, 30, 32, 36, 40, 40, 42,
45, 46, 42, 39, 40, 41, 43, 50,
];
const showMark = (params: ShowMarkParams) => {
const { position } = params as ShowMarkParams<Date>;
return position.getHours() === 0;
};
const config = {
series: [
{ data: y1, showMark },
{ data: y2, showMark },
],
height: 300,
};
const xAxisCommon = {
data: timeData,
scaleType: 'time',
valueFormatter,
} as const;
순서형 눈금 관리 (Ordinal tick management)
순서형 스케일('band'와 'point')은 기본적으로 항목마다 눈금을 하나씩 표시해요. 날짜 축이 있다면 ordinalTimeTicks 속성으로 표시할 눈금을 설정할 수 있습니다.
이 속성은 눈금을 배치할 수 있는 주기(frequency) 배열을 받아요. 이 주기들은 큰 것부터 작은 것 순으로 정렬되어야 합니다. 예를 들어 ['years', 'months', 'days']처럼요. 표시되는 눈금은 이 주기들과 tickNumber를 기준으로 선택됩니다.
ordinalTimeTicks 속성은 TickFrequencyDefinition 타입의 구현이거나, 내장 주기('years', 'quarterly', 'months', 'biweekly', 'weeks', 'days', 'hours')의 부분 집합일 수 있어요.
ordinalTimeTicks를 사용하면 tickPlacement 속성은 무시되고, 마치 'middle'로 설정된 것처럼 계산됩니다.
다음 데모에서는 내장 주기를 기반으로 ordinalTimeTicks를 수정하면서 zoom 동작에 어떤 영향을 주는지 확인할 수 있어요.
import * as React from 'react';
import Box from '@mui/material/Box';
import { BarChartPro } from '@mui/x-charts-pro/BarChartPro';
import { BarSeriesType, XAxis, YAxis, ZoomOptions } from '@mui/x-charts-pro/models';
import { TickFrequency } from '@mui/x-charts/models';
import alphabetStock from '../dataset/GOOGL.json';
import SelectTimeFrequency from './SelectTimeFrequency';
const tickFrequencies: TickFrequency[] = [
'years',
'quarterly',
'months',
'biweekly',
'weeks',
'days',
];
export default function OrdinalTickPlacement() {
const [ordinalTimeTicks, setOrdinalTimeTicks] =
React.useState<FilteredTicksState>(defaultTicks);
const [tickNumber, setTickNumber] = React.useState(5);
return (
<Box sx={{ width: '100%' }}>
<SelectTimeFrequency
tickFrequencies={tickFrequencies}
ordinalTimeTicks={ordinalTimeTicks}
setOrdinalTimeTicks={setOrdinalTimeTicks}
tickNumber={tickNumber}
setTickNumber={setTickNumber}
/>
<BarChartPro
{...barSettings}
xAxis={[
{
...xAxis,
tickNumber,
ordinalTimeTicks: tickFrequencies.filter(
(frequency) =>
ordinalTimeTicks[frequency as keyof typeof ordinalTimeTicks],
),
},
]}
/>
</Box>
);
}
type FilteredTicksState = Record<TickFrequency, boolean>;
const defaultTicks = Object.fromEntries(
tickFrequencies.map((frequency) => [frequency, true]),
) as FilteredTicksState;
const zoom: ZoomOptions = { minSpan: 1, filterMode: 'discard' };
const xAxis: XAxis = {
id: 'date',
data: alphabetStock.map((day) => new Date(day.date)),
scaleType: 'band',
zoom,
valueFormatter: (value) => value.toLocaleDateString(),
height: 30,
};
const barSettings = {
height: 200,
hideLegend: true,
margin: { bottom: 5 },
series: [
{
type: 'bar',
yAxisId: 'volume',
label: 'Volume',
color: 'lightgray',
data: alphabetStock.map((day) => day.volume),
} as BarSeriesType,
],
yAxis: [
{
id: 'volume',
scaleType: 'linear',
position: 'left',
valueFormatter: (value) => `${(value / 1000000).toLocaleString()}M`,
width: 55,
} as YAxis,
],
};
TickFrequencyDefinition은 다음 속성들로 이루어진 객체입니다.
getTickNumber: (from: Date, to: Date) => numberfrom과to날짜 사이에 표시될 눈금 개수를 반환해요.isTick: (prev: Date, value: Date) => booleanvalue위치에 눈금을 배치해야 하면true를 반환해요. 예를 들어 새 달의 시작인 경우 등입니다.format: (d: Date) => string눈금 라벨을 반환해요.
내장된 주기 정의는 '@mui/x-charts/utils'에서 tickFrequencies로 내보내집니다.
다음 데모에서는 tickFrequencies를 사용해서 분기(quarter)와 주(week)를 서로 다른 라벨로 표시합니다.
import * as React from 'react';
import Box from '@mui/material/Box';
import { BarChartPro } from '@mui/x-charts-pro/BarChartPro';
import { BarSeriesType, XAxis, YAxis, ZoomOptions } from '@mui/x-charts-pro/models';
import { tickFrequencies } from '@mui/x-charts/utils';
import alphabetStock from '../dataset/GOOGL.json';
export default function CustomTickFrequency() {
return (
<Box sx={{ width: '100%' }}>
<BarChartPro
{...barSettings}
xAxis={[
{
...xAxis,
ordinalTimeTicks: [
'years',
{ ...tickFrequencies.quarterly, format: quarterFormat },
{ ...tickFrequencies.weeks, format: weekFormat },
],
},
]}
/>
</Box>
);
}
const quarterFormat = (d: Date) => `Q${Math.floor(d.getMonth() / 3) + 1}`;
const weekFormat = (d: Date) => `W${getWeekNumber(d)}`;
const zoom: ZoomOptions = { minSpan: 1, filterMode: 'discard' };
const xAxis: XAxis = {
id: 'date',
data: alphabetStock.map((day) => new Date(day.date)),
scaleType: 'band',
zoom,
valueFormatter: (value) => value.toLocaleDateString(),
height: 30,
tickNumber: 15,
};
const barSettings = {
height: 200,
hideLegend: true,
margin: { bottom: 5 },
series: [
{
type: 'bar',
yAxisId: 'volume',
label: 'Volume',
color: 'lightgray',
data: alphabetStock.map((day) => day.volume),
} as BarSeriesType,
],
yAxis: [
{
id: 'volume',
scaleType: 'linear',
position: 'left',
valueFormatter: (value) => `${(value / 1000000).toLocaleString()}M`,
width: 55,
} as YAxis,
],
grid: { vertical: true, horizontal: true },
};
function getWeekNumber(date: Date) {
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
const dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
}