Charts – 스타일링
Charts – 스타일링 (Styling)
차트의 모양, 색상, 스타일을 커스터마이즈해요.
이 페이지는 차트 색상(시리즈 색상, 컬러 팔레트, 값 기반 색상 매핑)을 커스터마이즈하는 방법을 다뤄요. 또한 오버레이, 차트 크기와 배치, CSS 스타일링, 그리고 그라데이션과 패턴 같은 고급 기능을 커스터마이즈하는 방법도 설명해요.
본문
색상 (Colors)
시리즈 색상 (Series color)
차트의 시리즈에 color 속성을 설정할 수 있어요.
이것은 해당 컴포넌트들을 렌더링하는 데 사용되는 기본 색상이에요.
<LineChart series={[{ ..., color: '#fdb462'}]} />
import * as React from 'react';
import { LineChart } from '@mui/x-charts/LineChart';
import Stack from '@mui/material/Stack';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
const Tableau10 = [
'#4e79a7',
'#f28e2c',
'#e15759',
'#76b7b2',
'#59a14f',
'#edc949',
'#af7aa1',
'#ff9da7',
'#9c755f',
'#bab0ab',
];
const chartsParams = {
height: 300,
};
export default function BasicColor() {
const [color, setColor] = React.useState('#4e79a7');
const handleChange = (event: React.MouseEvent<HTMLElement>, nextColor: string) => {
setColor(nextColor);
};
return (
<Stack direction="column" spacing={2}>
<LineChart
{...chartsParams}
series={[
{
data: [15, 23, 18, 19, 13],
label: 'Example',
color,
},
]}
/>
<ToggleButtonGroup value={color} exclusive onChange={handleChange}>
{Tableau10.map((value) => (
<ToggleButton key={value} value={value} sx={{ p: 1 }}>
<div
style={{
width: 15,
height: 15,
backgroundColor: value,
display: 'inline-block',
}}
/>
</ToggleButton>
))}
</ToggleButtonGroup>
</Stack>
);
}
내장 컬러 팔레트 (Built-in color palettes)
라이브러리는 시리즈에 색상을 자동으로 할당하는 여러 내장 컬러 팔레트를 제공해요.
시리즈에 color prop이 없으면 차트는 시리즈의 인덱스를 기준으로 색상을 할당해요.
차트 컴포넌트(또는 커스텀 컴포넌트를 구성할 때는 ChartsContainer)의 colors prop으로 커스텀 컬러 팔레트를 설정할 수 있어요.
색상 배열을 전달하거나, 입력으로 테마의 모드('dark' 또는 'light')를 받고 색상 배열을 반환하는 콜백을 전달할 수 있어요.
import * as React from 'react';
import { createTheme, useTheme, ThemeProvider } from '@mui/material/styles';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Button from '@mui/material/Button';
import Brightness4Icon from '@mui/icons-material/Brightness4';
import Brightness7Icon from '@mui/icons-material/Brightness7';
import { Chance } from 'chance';
import { ScatterChart, ScatterChartProps } from '@mui/x-charts/ScatterChart';
import { ScatterValueType } from '@mui/x-charts/models';
import {
blueberryTwilightPalette,
mangoFusionPalette,
cheerfulFiestaPalette,
strawberrySkyPalette,
rainbowSurgePalette,
bluePalette,
greenPalette,
purplePalette,
redPalette,
orangePalette,
yellowPalette,
cyanPalette,
pinkPalette,
} from '@mui/x-charts/colorPalettes';
import Divider from '@mui/material/Divider';
import ListSubheader from '@mui/material/ListSubheader';
const chance = new Chance(42);
function getGaussianSeriesData(
mean: [number, number],
stdev: [number, number] = [0.3, 0.4],
N: number = 50,
) {
return [...Array(N)].map((_, i) => {
const x =
Math.sqrt(-2.0 * Math.log(1 - chance.floating({ min: 0, max: 0.99 }))) *
Math.cos(2.0 * Math.PI * chance.floating({ min: 0, max: 0.99 })) *
stdev[0] +
mean[0];
const y =
Math.sqrt(-2.0 * Math.log(1 - chance.floating({ min: 0, max: 0.99 }))) *
Math.cos(2.0 * Math.PI * chance.floating({ min: 0, max: 0.99 })) *
stdev[1] +
mean[1];
return { x, y, id: i };
});
}
const legendPlacement: Partial<ScatterChartProps> = {
slotProps: {
legend: {
direction: 'vertical',
},
},
};
const series = [
{ label: 'Series 1', data: getGaussianSeriesData([-5, 0]) },
{ label: 'Series 2', data: getGaussianSeriesData([-4, 0]) },
{ label: 'Series 3', data: getGaussianSeriesData([-3, 0]) },
{ label: 'Series 4', data: getGaussianSeriesData([-2, 0]) },
{ label: 'Series 5', data: getGaussianSeriesData([-1, 0]) },
{ label: 'Series 6', data: getGaussianSeriesData([0, 0]) },
{ label: 'Series 7', data: getGaussianSeriesData([1, 0]) },
{ label: 'Series 8', data: getGaussianSeriesData([2, 0]) },
{ label: 'Series 9', data: getGaussianSeriesData([3, 0]) },
{ label: 'Series 10', data: getGaussianSeriesData([4, 0]) },
{ label: 'Series 11', data: getGaussianSeriesData([5, 0]) },
{ label: 'Series 12', data: getGaussianSeriesData([6, 0]) },
{ label: 'Series 13', data: getGaussianSeriesData([7, 0]) },
].map((s) => ({
...s,
valueFormatter: (v: ScatterValueType | null) =>
v && `(${v.x.toFixed(1)}, ${v.y.toFixed(1)})`,
}));
const categorical = {
rainbowSurge: rainbowSurgePalette,
blueberryTwilight: blueberryTwilightPalette,
mangoFusion: mangoFusionPalette,
cheerfulFiesta: cheerfulFiestaPalette,
} as const;
const sequential = {
strawberrySky: strawberrySkyPalette,
purple: purplePalette,
blue: bluePalette,
cyan: cyanPalette,
green: greenPalette,
yellow: yellowPalette,
orange: orangePalette,
red: redPalette,
pink: pinkPalette,
} as const;
const categories = {
...categorical,
...sequential,
} as const;
type PaletteKey = keyof typeof categories;
export default function MuiColorTemplate() {
const theme = useTheme();
const [colorScheme, setColorScheme] =
React.useState<PaletteKey>('blueberryTwilight');
const [colorMode, setColorMode] = React.useState(theme.palette.mode);
React.useEffect(() => {
setColorMode(theme.palette.mode);
}, [theme.palette.mode]);
const newTheme = createTheme({ palette: { mode: colorMode } });
return (
<ThemeProvider theme={newTheme}>
<Paper sx={{ width: '100%', p: 2 }} elevation={0}>
<Stack direction="column" spacing={2}>
<ScatterChart
height={400}
series={series}
yAxis={[{ min: -1.5, max: 1.5 }]}
colors={categories[colorScheme]}
{...legendPlacement}
/>
<Stack
direction={{ xs: 'column', md: 'row' }}
sx={{ alignItems: 'center', justifyContent: 'space-evenly' }}
>
<div>
<Button
sx={{ ml: 1 }}
onClick={() =>
setColorMode((prev) => (prev === 'light' ? 'dark' : 'light'))
}
color="inherit"
endIcon={
colorMode === 'dark' ? <Brightness7Icon /> : <Brightness4Icon />
}
>
{colorMode} mode
</Button>
</div>
<TextField
select
sx={{ maxWidth: 1 }}
value={colorScheme}
onChange={(event) => setColorScheme(event.target.value as PaletteKey)}
>
<ListSubheader>Categorical</ListSubheader>
{Object.entries(categorical).map(([name, colors]) => (
<MenuItem key={name} value={name}>
<Stack
direction="row"
sx={{
alignItems: 'center',
justifyContent: 'space-between',
width: '100%',
}}
>
<Typography sx={{ mr: 2 }}>{name}</Typography>
<div style={{ width: 200, height: 20 }}>
{colors(colorMode).map((c) => (
<div
key={c}
style={{
width: 20,
height: 20,
backgroundColor: c,
display: 'inline-block',
}}
/>
))}
</div>
</Stack>
</MenuItem>
))}
<Divider />
<ListSubheader>Sequential</ListSubheader>
{Object.entries(sequential).map(([name, colors]) => (
<MenuItem key={name} value={name}>
<Stack
direction="row"
sx={{
alignItems: 'center',
justifyContent: 'space-between',
width: '100%',
}}
>
<Typography sx={{ mr: 2 }}>{name}</Typography>
<div style={{ width: 200, height: 20 }}>
{colors(colorMode).map((c) => (
<div
key={c}
style={{
width: 20,
height: 20,
backgroundColor: c,
display: 'inline-block',
}}
/>
))}
</div>
</Stack>
</MenuItem>
))}
</TextField>
</Stack>
</Stack>
</Paper>
</ThemeProvider>
);
}
커스텀 컬러 팔레트 (Custom color palettes)
d3-scale-chromatic이나 원하는 색상 조작 라이브러리를 사용해 커스텀 컬러 팔레트를 생성할 수 있어요.
아래 예시는 d3 Categorical 컬러 팔레트를 보여줘요.
import * as React from 'react';
import { ScatterChart, ScatterChartProps } from '@mui/x-charts/ScatterChart';
import { ScatterValueType } from '@mui/x-charts/models';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import Typography from '@mui/material/Typography';
import { Chance } from 'chance';
const chance = new Chance(42);
function getGaussianSeriesData(
mean: [number, number],
stdev: [number, number] = [0.3, 0.4],
N: number = 50,
) {
return [...Array(N)].map((_, i) => {
const x =
Math.sqrt(-2.0 * Math.log(1 - chance.floating({ min: 0, max: 0.99 }))) *
Math.cos(2.0 * Math.PI * chance.floating({ min: 0, max: 0.99 })) *
stdev[0] +
mean[0];
const y =
Math.sqrt(-2.0 * Math.log(1 - chance.floating({ min: 0, max: 0.99 }))) *
Math.cos(2.0 * Math.PI * chance.floating({ min: 0, max: 0.99 })) *
stdev[1] +
mean[1];
return { x, y, id: i };
});
}
const legendPlacement: Partial<ScatterChartProps> = {
slotProps: {
legend: {
position: {
vertical: 'middle',
horizontal: 'end',
},
direction: 'vertical',
},
},
};
const series = [
{ label: 'Series 1', data: getGaussianSeriesData([-5, 0]) },
{ label: 'Series 2', data: getGaussianSeriesData([-4, 0]) },
{ label: 'Series 3', data: getGaussianSeriesData([-3, 0]) },
{ label: 'Series 4', data: getGaussianSeriesData([-2, 0]) },
{ label: 'Series 5', data: getGaussianSeriesData([-1, 0]) },
{ label: 'Series 6', data: getGaussianSeriesData([0, 0]) },
{ label: 'Series 7', data: getGaussianSeriesData([1, 0]) },
{ label: 'Series 8', data: getGaussianSeriesData([2, 0]) },
{ label: 'Series 9', data: getGaussianSeriesData([3, 0]) },
{ label: 'Series 10', data: getGaussianSeriesData([4, 0]) },
{ label: 'Series 11', data: getGaussianSeriesData([5, 0]) },
{ label: 'Series 12', data: getGaussianSeriesData([6, 0]) },
{ label: 'Series 13', data: getGaussianSeriesData([7, 0]) },
].map((s) => ({
...s,
valueFormatter: (v: ScatterValueType | null) =>
v && `(${v.x.toFixed(1)}, ${v.y.toFixed(1)})`,
}));
const categories: { [key: string]: string[] } = {
Category10: [
'#1f77b4',
'#ff7f0e',
'#2ca02c',
'#d62728',
'#9467bd',
'#8c564b',
'#e377c2',
'#7f7f7f',
'#bcbd22',
'#17becf',
],
Accent: [
'#7fc97f',
'#beaed4',
'#fdc086',
'#ffff99',
'#386cb0',
'#f0027f',
'#bf5b17',
'#666666',
],
Dark2: [
'#1b9e77',
'#d95f02',
'#7570b3',
'#e7298a',
'#66a61e',
'#e6ab02',
'#a6761d',
'#666666',
],
Paired: [
'#a6cee3',
'#1f78b4',
'#b2df8a',
'#33a02c',
'#fb9a99',
'#e31a1c',
'#fdbf6f',
'#ff7f00',
'#cab2d6',
'#6a3d9a',
'#ffff99',
'#b15928',
],
Pastel1: [
'#fbb4ae',
'#b3cde3',
'#ccebc5',
'#decbe4',
'#fed9a6',
'#ffffcc',
'#e5d8bd',
'#fddaec',
'#f2f2f2',
],
Pastel2: [
'#b3e2cd',
'#fdcdac',
'#cbd5e8',
'#f4cae4',
'#e6f5c9',
'#fff2ae',
'#f1e2cc',
'#cccccc',
],
Set1: [
'#e41a1c',
'#377eb8',
'#4daf4a',
'#984ea3',
'#ff7f00',
'#ffff33',
'#a65628',
'#f781bf',
'#999999',
],
Set2: [
'#66c2a5',
'#fc8d62',
'#8da0cb',
'#e78ac3',
'#a6d854',
'#ffd92f',
'#e5c494',
'#b3b3b3',
],
Set3: [
'#8dd3c7',
'#ffffb3',
'#bebada',
'#fb8072',
'#80b1d3',
'#fdb462',
'#b3de69',
'#fccde5',
'#d9d9d9',
'#bc80bd',
'#ccebc5',
'#ffed6f',
],
Tableau10: [
'#4e79a7',
'#f28e2c',
'#e15759',
'#76b7b2',
'#59a14f',
'#edc949',
'#af7aa1',
'#ff9da7',
'#9c755f',
'#bab0ab',
],
};
export default function ColorTemplate() {
const [colorScheme, setColorScheme] = React.useState('Category10');
return (
<Stack direction="column" spacing={2} sx={{ width: '100%', maxWidth: 600 }}>
<ScatterChart
height={400}
series={series}
yAxis={[{ min: -1.5, max: 1.5 }]}
colors={categories[colorScheme]}
{...legendPlacement}
/>
<TextField
select
defaultValue="Category10"
onChange={(event) => setColorScheme(event.target.value)}
>
{Object.entries(categories).map(([name, colors]) => (
<MenuItem key={name} value={name}>
<Stack direction="row" sx={{ alignItems: 'center' }}>
<Typography sx={{ mr: 2 }}>{name}</Typography>
<div style={{ width: 200, height: 20 }}>
{colors.map((c) => (
<div
key={c}
style={{
width: 20,
height: 20,
backgroundColor: c,
display: 'inline-block',
}}
/>
))}
</div>
</Stack>
</MenuItem>
))}
</TextField>
</Stack>
);
}
값 기반 색상 (Value-based colors)
해당 축의 colorMap 속성을 사용해 항목 값에 따라 색상을 설정할 수 있어요.
이 기능에 대한 자세한 내용은 각 차트 컴포넌트의 전용 문서 섹션을 참고해요:
colorMap 속성은 piecewise, continuous, ordinal 세 가지 종류의 객체를 받아들여요.
Piecewise 색상 맵 (Piecewise color map)
_n_개의 thresholds 값과 _n+1_개의 colors 배열로 piecewise 색상 맵을 구성할 수 있어요.
{
type: 'piecewise';
thresholds: Value[];
colors: string[];
unknownColor?: string;
}
Continuous 색상 맵 (Continuous color map)
continuous 구성은 min에서 max 속성까지의 값을 해당 색상에 매핑하게 해요.
color 속성은 보간할 두 색상의 배열일 수도 있고, 0과 1 사이의 값인 숫자 _t_에 해당하는 색상을 반환하는 보간 함수일 수도 있어요.
d3-scale-chromatic 라이브러리에는 이런 함수가 많이 있어요.
min보다 낮은 값은 min 값의 색상을 얻어요.
마찬가지로 max보다 높은 값은 max 값의 색상을 얻어요.
기본적으로 min-max 범위는 0-100이에요.
{
type: 'continuous';
min?: Value;
max?: Value;
color: [string, string] | ((t: number) => string);
unknownColor?: string;
}
Ordinal 색상 맵 (Ordinal color map)
values와 colors 두 속성으로 ordinal 색상 맵을 구성할 수 있어요. 이 속성들은 값을 각각의 색상에 매핑해요.
정의되지 않은 값이 있으면 unknownColor로 폴백해요.
unknownColor도 정의되지 않았다면 시리즈 색상으로 폴백해요.
막대 차트에서 문자열 범주에 따라 색상을 설정하는 데 이 구성을 사용할 수 있어요.
{
type: 'ordinal';
values: Value[];
colors: string[];
unknownColor?: string;
}
색상 콜백 (Color callback)
색상 할당을 더 세밀하게 제어해야 한다면 차트 컴포넌트에 colorGetter() 콜백 prop을 제공할 수 있어요.
콜백 함수는 { value, dataIndex } 객체를 받고, 주어진 데이터 포인트에 대한 색상 문자열을 반환해야 해요.
시리즈 단위 색상이 필요한 컴포넌트(예: 범례)에서는 대신 color prop이 사용돼요.
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { BarChart, BarChartProps, BarSeries } from '@mui/x-charts/BarChart';
const clubs = [
'Arsenal',
'Liverpool',
'Man Utd',
'Tottenham',
'Everton',
'Sunderland',
'Newcastle',
'Nottingham Forest',
'Leeds',
'Man City',
'West Ham',
'Burnley',
'Fulham',
'Chelsea',
'Aston Villa',
'Wolves',
'Crystal Palace',
'Brentford',
'Bournemouth',
'Brighton',
];
// Source: https://www.squawka.com/en/news/premier-league-net-spend-2025-26/
const netSpendInPounds = [
251.4, 235, 166.9, 137.8, 116, 113.4, 95.6, 95.4, 91.5, 80.2, 69.7, 57.8, 18.93,
9.5, -8, -14.7, -23, -58.9, -63.3, -68.15,
];
const clubColors = [
'#EF0107', // Arsenal - Red
'#C8102E', // Liverpool - Red
'#DA291C', // Man Utd - Red
'#132257', // Tottenham - Navy Blue
'#003399', // Everton - Royal Blue
'#E03A3E', // Sunderland - Red
'#241F20', // Newcastle - Black
'#DD0000', // Nottingham Forest - Red
'#FFCD00', // Leeds - Yellow
'#6CABDD', // Man City - Sky Blue
'#7A263A', // West Ham - Claret
'#6C1D45', // Burnley - Claret
'#CC0000', // Fulham - Red
'#034694', // Chelsea - Blue
'#670E36', // Aston Villa - Claret
'#FDB913', // Wolves - Gold
'#1B458F', // Crystal Palace - Blue
'#E30613', // Brentford - Red
'#DA291C', // Bournemouth - Red
'#0057B8', // Brighton - Blue
];
const valueFormatter = (v: number | null) => (v! < 0 ? `-£${-v!}m` : `£${v!}m`);
const chartsParams = {
margin: { top: 20, right: 40, bottom: 20, left: 20 },
xAxis: [{ data: clubs, tickLabelStyle: { angle: 45 }, height: 80 }],
yAxis: [
{
width: 60,
valueFormatter,
},
],
series: [
{
data: netSpendInPounds,
colorGetter: (data) => clubColors[data.dataIndex],
valueFormatter,
} satisfies BarSeries,
],
height: 400,
} satisfies BarChartProps;
export default function ColorCallback() {
return (
<Stack spacing={2} sx={{ width: '100%' }}>
<Typography variant="h6" sx={{ textAlign: 'center' }}>
Premier League Clubs Net Spend - Summer 2025
</Typography>
<BarChart {...chartsParams} />
<Typography variant="caption">Source: squawka.com</Typography>
</Stack>
);
}
오버레이 (Overlay)
차트에는 loading prop이 true일 때 나타나는 로딩 상태와, 표시할 데이터가 없을 때 나타나는 "no data" 상태를 위한 내장 오버레이가 있어요.
import Stack from '@mui/material/Stack';
import { LineChart } from '@mui/x-charts/LineChart';
const emptySeries = {
series: [],
height: 150,
};
export default function Overlay() {
return (
<Stack direction={{ md: 'row', xs: 'column' }} sx={{ width: '100%' }}>
<LineChart loading {...emptySeries} />
<LineChart {...emptySeries} />
</Stack>
);
}
축 표시 (Axis display)
데이터를 로딩하는 동안 축을 표시하도록 축 데이터를 제공할 수 있어요.
import Stack from '@mui/material/Stack';
import { LineChart } from '@mui/x-charts/LineChart';
const emptySeries = {
series: [],
height: 150,
};
export default function OverlayWithAxis() {
return (
<Stack direction={{ md: 'row', xs: 'column' }} sx={{ width: '100%' }}>
<LineChart
loading
xAxis={[{ data: [0, 1, 2, 4, 5] }]}
yAxis={[{ min: 0, max: 10 }]}
{...emptySeries}
/>
<LineChart
yAxis={[{ min: -5, max: 5 }]}
xAxis={[
{
scaleType: 'time',
data: [
new Date(2019, 0, 1),
new Date(2020, 0, 1),
new Date(2021, 0, 1),
new Date(2022, 0, 1),
],
tickNumber: 3,
},
]}
{...emptySeries}
/>
</Stack>
);
}
커스텀 오버레이 (Custom overlay)
기본 오버레이 메시지를 수정하거나 번역하려면 선호하는 locale로 noData 또는 loading 키를 사용해요.
<BarChart
localeText={{
loading: 'Data should be available soon.',
noData: 'Select some data to display.',
}}
/>
더 고급 커스터마이즈를 위해서는 아래 데모처럼 loadingOverlay와 noDataOverlay 슬롯을 사용해요.
import { styled } from '@mui/material/styles';
import Stack from '@mui/material/Stack';
import { BarChart } from '@mui/x-charts/BarChart';
import { useDrawingArea, useXScale, useYScale } from '@mui/x-charts/hooks';
const ratios = [0.2, 0.8, 0.6, 0.5];
const LoadingRect = styled('rect')({
opacity: 0.2,
fill: 'lightgray',
});
const LoadingText = styled('text')(({ theme }) => ({
stroke: 'none',
fill: theme.palette.text.primary,
shapeRendering: 'crispEdges',
textAnchor: 'middle',
dominantBaseline: 'middle',
}));
function LoadingOverlay() {
const xScale = useXScale<'band'>();
const yScale = useYScale();
const { left, width, height } = useDrawingArea();
const bandWidth = xScale.bandwidth();
const [bottom, top] = yScale.range();
return (
<g>
{xScale.domain().map((item, index) => {
const ratio = ratios[index % ratios.length];
const barHeight = ratio * (bottom - top);
return (
<LoadingRect
key={index}
x={xScale(item)}
width={bandWidth}
y={bottom - barHeight}
height={height}
/>
);
})}
<LoadingText x={left + width / 2} y={top + height / 2}>
Loading data…
</LoadingText>
</g>
);
}
export default function CustomOverlay() {
return (
<Stack direction={{ md: 'row', xs: 'column' }} sx={{ width: '100%' }}>
<BarChart
localeText={{ noData: 'No data to display in this chart' }}
series={[]}
height={150}
/>
<BarChart
loading
xAxis={[{ data: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] }]}
slots={{ loadingOverlay: LoadingOverlay }}
series={[]}
height={150}
/>
</Stack>
);
}
스타일링 (Styling)
크기 (Size)
차트는 기본적으로 부모 요소를 채우도록 크기를 조정해요.
height 및/또는 width props를 제공해 이 동작을 수정할 수 있어요.
이 props는 차트 크기를 주어진 값(px 단위)으로 설정해요.
배치 (Placement)
차트의 배치를 정의할 때는 마진과 축 크기 모두를 고려해요:
- 마진: SVG 테두리와 축 또는 그리기 영역 사이의 공간
- 축 크기: 축이 차지하는 공간; 각 축은 고유한 크기를 가져요
축에는 기본 크기가 있어요.
xAxis와 yAxis 구성으로 업데이트할 수 있어요:
x-axis:heightprop을 사용해 축이 차지하는 공간을 정의해요y-axis: 대신widthprop을 사용해요
축은 자신이 배치된 쪽에서만 공간을 차지해요.
축이 표시되지 않으면(position: 'none'), 크기와 관계없이 어떤 공간도 차지하지 않아요.
import * as React from 'react';
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
import { BarChart } from '@mui/x-charts/BarChart';
import { useDrawingArea, useXAxis, useYAxis } from '@mui/x-charts/hooks';
const defaultMargin = {
knob: 'number',
defaultValue: 40,
step: 1,
min: 0,
max: 200,
} as const;
const defaultAxisSize = {
knob: 'number',
defaultValue: 30,
step: 1,
min: 0,
max: 200,
} as const;
export default function Margin() {
return (
<ChartsUsageDemo
componentName="Margin demos"
data={
{
left: defaultMargin,
right: defaultMargin,
top: defaultMargin,
bottom: defaultMargin,
xAxisHeight: defaultAxisSize,
yAxisWidth: defaultAxisSize,
hideXAxis: {
knob: 'switch',
defaultValue: false,
},
hideYAxis: {
knob: 'switch',
defaultValue: false,
},
} as const
}
renderDemo={(props) => (
<div style={{ width: '100%', margin: 4 }}>
<BarChart
series={[{ data: [6, 18, 12] }]}
height={300}
margin={{
left: props.left,
right: props.right,
top: props.top,
bottom: props.bottom,
}}
xAxis={[
{
id: 'x-axis',
data: ['Page 1', 'Page 2', 'Page 3'],
position: props.hideXAxis ? 'none' : 'top',
height: props.xAxisHeight,
},
]}
yAxis={[
{
id: 'y-axis',
position: props.hideYAxis ? 'none' : 'right',
width: props.yAxisWidth,
},
]}
>
<MarginVisualization />
<AxisSizeVisualization />
<DrawingAreaVisualization />
</BarChart>
</div>
)}
getCode={({ props }) =>
`import { BarChart } from '@mui/x-charts/BarChart';
<BarChart
// ...
margin={{
left: ${props.left},
right: ${props.right},
top: ${props.top},
bottom: ${props.bottom},
}}
xAxis={[{
height: ${props.xAxisHeight},
position: ${props.hideXAxis ? "'none'" : "'top'"}
}]}
yAxis={[{
width: ${props.yAxisWidth}
position: ${props.hideYAxis ? "'none'" : "'right'"}
}]}
/>`
}
/>
);
}
function MarginVisualization() {
const { bottom, left, right, top, height, width } = useDrawingArea();
const xAxis = useXAxis('x-axis');
const yAxis = useYAxis('y-axis');
const xSize = (xAxis.position !== 'none' ? xAxis.height : 0) ?? 0;
const ySize = (yAxis.position !== 'none' ? yAxis.width : 0) ?? 0;
return (
<React.Fragment>
<rect
x={0}
y={0}
width={'100%'}
height={top - xSize}
fill="#008080"
opacity={0.5}
/>
<rect
x={0}
y={height + top}
width={'100%'}
height={bottom}
fill="#008080"
opacity={0.5}
/>
<rect
x={0}
y={top - xSize}
width={left}
height={height + xSize}
fill="#008080"
opacity={0.5}
/>
<rect
x={width + left + ySize}
y={top - xSize}
width={right - ySize}
height={height + xSize}
fill="#008080"
opacity={0.5}
/>
</React.Fragment>
);
}
function AxisSizeVisualization() {
const { left, top, height, width } = useDrawingArea();
const xAxis = useXAxis('x-axis');
const yAxis = useYAxis('y-axis');
return (
<React.Fragment>
{xAxis.position !== 'none' && (
<rect
x={left}
y={top - (xAxis.height ?? 0)}
width={width}
height={xAxis.height ?? 0}
fill="#EC407A"
opacity={0.5}
/>
)}
{yAxis.position !== 'none' && (
<rect
x={width + left}
y={top}
width={yAxis.width ?? 0}
height={height}
fill="#EC407A"
opacity={0.5}
/>
)}
</React.Fragment>
);
}
function DrawingAreaVisualization() {
const { left, top, height, width } = useDrawingArea();
return (
<rect
x={left}
y={top}
width={width}
height={height}
fill="#006BD6"
opacity={0.2}
/>
);
}
CSS
차트는 SVG로 렌더링되므로 sx prop으로 커스터마이즈하고 클래스 이름으로 하위 컴포넌트를 대상으로 삼을 수 있어요.
import * as React from 'react';
import { BarChart, barClasses } from '@mui/x-charts/BarChart';
import { axisClasses } from '@mui/x-charts/ChartsAxis';
const labels: string[] = ['Group A', 'Group B', 'Group C', 'Group D', 'Group E'];
const lData: number[] = [42, 24, 56, 45, 3];
const rData: number[] = [57, 7, 19, 16, 22];
const colors: string[] = ['#006BD6', '#EC407A'];
export default function SxStyling(): React.JSX.Element {
return (
<BarChart
sx={(theme) => ({
[`.${barClasses.element}`]: {
fill: (theme.vars || theme).palette.background.paper,
strokeWidth: 2,
},
[`[data-series="l_id"] .${barClasses.element}`]: {
stroke: colors[0],
},
[`[data-series="r_id"] .${barClasses.element}`]: {
stroke: colors[1],
},
[`.${axisClasses.root}`]: {
[`.${axisClasses.tick}, .${axisClasses.line}`]: {
stroke: '#006BD6',
strokeWidth: 3,
},
[`.${axisClasses.tickLabel}`]: {
fill: '#006BD6',
},
},
border: '1px solid rgba(0, 0, 0, 0.1)',
backgroundImage:
'linear-gradient(rgba(0, 0, 0, 0.1) 1px, transparent 1px), linear-gradient(90deg, rgba(0, 0, 0, 0.1) 1px, transparent 1px)',
backgroundSize: '35px 35px',
backgroundPosition: '20px 20px, 20px 20px',
...theme.applyStyles('dark', {
borderColor: 'rgba(255,255,255, 0.1)',
backgroundImage:
'linear-gradient(rgba(255,255,255, 0.1) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255, 0.1) 1px, transparent 1px)',
}),
})}
xAxis={[{ data: labels }]}
series={[
{ data: lData, label: 'l', id: 'l_id' },
{ data: rData, label: 'r', id: 'r_id' },
]}
colors={colors}
height={300}
/>
);
}
텍스트 커스터마이즈 (Text customization)
축 눈금 라벨과 축 라벨을 커스터마이즈하려면 축 구성의 tickLabelStyle과 labelStyle 속성을 사용해요.
이것들은 SVG 스타일 객체를 받아들여요.
차트는 이 props를 통해 전달된 인라인 스타일에서만 텍스트를 측정해요.
fontSize, fontWeight, fontFamily, letterSpacing처럼 텍스트 크기에 영향을 주는 속성은 반드시 tickLabelStyle 또는 labelStyle로 설정해야 해요.
:::warning
sx prop, style prop, CSS 클래스 선택자를 통해 적용하면 텍스트는 새 크기로 렌더링되지만 측정은 원래 크기로 남아 라벨이 겹칠 수 있어요.
fill 같은 시각적 속성은 측정에 영향을 주지 않으므로 어느 쪽으로든 설정할 수 있어요.
:::
// ❌ Layout is computed for the original size, labels overlap.
<BarChart sx={{ [`.${axisClasses.tickLabel}`]: { fontSize: 18 } }} xAxis={[{ data }]} />
// ✅ Layout is computed for the new size.
<BarChart xAxis={[{ data, tickLabelStyle: { fontSize: 18 } }]} />
아래 데모는 두 축 모두에 커스텀 폰트 스타일을 적용하고 x축 눈금 라벨을 회전시켜요.
import * as React from 'react';
import { BarChart } from '@mui/x-charts/BarChart';
const months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
const data = [42, 65, 49, 78, 56, 90, 73, 81, 60, 88, 54, 95];
export default function TextStyling(): React.JSX.Element {
return (
<BarChart
height={300}
xAxis={[
{
data: months,
label: 'Month',
height: 70,
labelStyle: {
fontSize: 16,
fontWeight: 600,
fontFamily: 'Georgia, serif',
fill: '#006BD6',
},
tickLabelStyle: {
fontSize: 13,
fontFamily: 'Georgia, serif',
fill: '#006BD6',
angle: -25,
textAnchor: 'end',
},
},
]}
yAxis={[
{
label: 'Revenue',
labelStyle: {
fontSize: 16,
fontWeight: 600,
fill: '#EC407A',
},
tickLabelStyle: {
fontSize: 13,
fill: '#EC407A',
},
},
]}
series={[{ data, label: 'Revenue' }]}
colors={['#006BD6']}
/>
);
}
그리기 영역 배경 (Drawing area background)
그리기 영역에 배경색을 설정하려면 SVG <rect> 요소를 만들어요.
이 새로운 컴포넌트를 모든 플롯 컴포넌트 앞에 배치해야 하므로 커스텀 차트 구성에서만 가능해요.
아래 데모는 연한 회색 배경을 추가하는 기본 Background 컴포넌트를 정의해요.
import { useTheme } from '@mui/material/styles';
import { LinePlot } from '@mui/x-charts/LineChart';
import { XAxis } from '@mui/x-charts/models';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsGrid } from '@mui/x-charts/ChartsGrid';
import { useDrawingArea } from '@mui/x-charts/hooks';
import {
dateAxisFormatter,
percentageFormatter,
usUnemploymentRate,
} from '../dataset/usUnemploymentRate';
function Background() {
const drawingArea = useDrawingArea();
const theme = useTheme();
return (
<rect
x={drawingArea.left}
y={drawingArea.top}
width={drawingArea.width}
height={drawingArea.height}
fill={theme.palette.mode === 'light' ? '#f5f5f5' : '#303030'}
/>
);
}
export default function BackgroundStyling() {
return (
<ChartsContainer
dataset={usUnemploymentRate}
xAxis={xAxis}
yAxis={yAxis}
series={series}
height={300}
>
<Background />
<ChartsGrid vertical horizontal />
<LinePlot />
<ChartsXAxis />
<ChartsYAxis />
</ChartsContainer>
);
}
const xAxis: XAxis<'time'>[] = [
{
dataKey: 'date',
scaleType: 'time',
valueFormatter: dateAxisFormatter,
},
];
const yAxis = [
{
valueFormatter: percentageFormatter,
},
];
const series = [
{
type: 'line' as const,
dataKey: 'rate',
valueFormatter: percentageFormatter,
},
];
그라데이션과 패턴 (Gradients and patterns)
그라데이션 또는 패턴 정의를 차트 컴포넌트의 자식으로 전달해 차트를 채우는 데 사용할 수 있어요.
이렇게 정의된 그라데이션이나 패턴은 SVG에서만 사용 가능해요.
color: "url(#Pattern)"처럼 직접 정의하면 HTML 요소에서 색상이 정의되지 않게 돼요.
import { BarChart } from '@mui/x-charts/BarChart';
export default function GradientTooltip() {
return (
<BarChart
series={[
{
label: 'series A',
data: [50],
color: 'url(#Pattern)',
},
{
label: 'series B',
data: [100],
color: 'url(#Gradient)',
},
]}
height={200}
>
<linearGradient id="Gradient" x1="0%" y1="100%" x2="0%" y2="0%">
<stop offset="0" stopColor="#123456" />
<stop offset="1" stopColor="#81b2e4" />
</linearGradient>
<pattern
id="Pattern"
patternUnits="userSpaceOnUse"
width="20"
height="40"
patternTransform="scale(0.5)"
>
<rect x="0" y="0" width="100%" height="100%" fill="#123456" />
<path
d="M0 30h20L10 50zm-10-20h20L0 30zm20 0h20L20 30zM0-10h20L10 10z"
strokeWidth="1"
stroke="#81b2e4"
fill="none"
/>
</pattern>
</BarChart>
);
}