Charts - 툴팁
Charts - 툴팁 (Tooltip)
사용자가 차트 항목과 상호작용할 때 추가 데이터를 표시하는 툴팁을 사용할 수 있어요.
본문
모든 차트 컴포넌트에서 tooltip 슬롯을 통해 툴팁에 접근할 수 있어요. 커스텀 컴포넌트를 구성하는 경우에는 ChartsTooltip 컴포넌트를 사용해요.
툴팁 트리거 (Tooltip trigger)
두 종류의 이벤트로 툴팁을 트리거할 수 있어요:
'item': 차트의 항목 위에 마우스를 올리면 그 특정 항목에 대한 데이터가 표시돼요.'axis': 마우스 위치가 x축의 값과 연결돼요. 해당 x 값에서 모든 시리즈에 대한 데이터가 표시돼요.'none': 툴팁을 비활성화해요.
이 트리거 속성을 툴팁에 전달하려면 slotProps.tooltip.trigger를 사용해요.
import Stack from '@mui/material/Stack';
import { BarChart } from '@mui/x-charts/BarChart';
const barChartsParams = {
xAxis: [{ data: ['page A', 'page B', 'page C', 'page D', 'page E'] }],
series: [
{ data: [2, 5, 3, 4, 1], stack: '1', label: 'Series x' },
{ data: [10, 3, 1, 2, 10], stack: '1', label: 'Series y' },
{ data: [10, 3, 1, 2, 10], stack: '1', label: 'Series z' },
],
margin: { top: 20, right: 10 },
height: 200,
hideLegend: true,
};
export default function Interaction() {
return (
<Stack direction="column" sx={{ width: '100%', maxWidth: 400 }}>
<BarChart {...barChartsParams} slotProps={{ tooltip: { trigger: 'axis' } }} />
<BarChart {...barChartsParams} slotProps={{ tooltip: { trigger: 'item' } }} />
</Stack>
);
}
포맷팅 (Formatting)
시리즈 valueFormatter 속성을 사용해 툴팁에 렌더링되는 데이터의 형식을 수정할 수 있어요. 'axis'로 트리거되는 툴팁에서는 축 값에도 동일하게 적용할 수 있어요.
아래 데모는 다음을 보여줘요:
- 연도만 표시되도록 포맷된 시간 축 값
- 미국 달러로 포맷된 시리즈 값
import { LineChart } from '@mui/x-charts/LineChart';
const years = [
new Date(1990, 0, 1),
new Date(1991, 0, 1),
new Date(1992, 0, 1),
new Date(1993, 0, 1),
new Date(1994, 0, 1),
new Date(1995, 0, 1),
new Date(1996, 0, 1),
new Date(1997, 0, 1),
new Date(1998, 0, 1),
new Date(1999, 0, 1),
new Date(2000, 0, 1),
new Date(2001, 0, 1),
new Date(2002, 0, 1),
new Date(2003, 0, 1),
new Date(2004, 0, 1),
new Date(2005, 0, 1),
new Date(2006, 0, 1),
new Date(2007, 0, 1),
new Date(2008, 0, 1),
new Date(2009, 0, 1),
new Date(2010, 0, 1),
new Date(2011, 0, 1),
new Date(2012, 0, 1),
new Date(2013, 0, 1),
new Date(2014, 0, 1),
new Date(2015, 0, 1),
new Date(2016, 0, 1),
new Date(2017, 0, 1),
new Date(2018, 0, 1),
];
const FranceGDPperCapita = [
28129, 28294.264, 28619.805, 28336.16, 28907.977, 29418.863, 29736.645, 30341.807,
31323.078, 32284.611, 33409.68, 33920.098, 34152.773, 34292.03, 35093.824,
35495.465, 36166.16, 36845.684, 36761.793, 35534.926, 36086.727, 36691, 36571,
36632, 36527, 36827, 37124, 37895, 38515.918,
];
const UKGDPperCapita = [
26189, 25792.014, 25790.186, 26349.342, 27277.543, 27861.215, 28472.248, 29259.764,
30077.385, 30932.537, 31946.037, 32660.441, 33271.3, 34232.426, 34865.78,
35623.625, 36214.07, 36816.676, 36264.79, 34402.36, 34754.473, 34971, 35185, 35618,
36436, 36941, 37334, 37782.83, 38058.086,
];
const GermanyGDPperCapita = [
25391, 26769.96, 27385.055, 27250.701, 28140.057, 28868.945, 29349.982, 30186.945,
31129.584, 32087.604, 33367.285, 34260.29, 34590.93, 34716.44, 35528.715,
36205.574, 38014.137, 39752.207, 40715.434, 38962.938, 41109.582, 43189, 43320,
43413, 43922, 44293, 44689, 45619.785, 46177.617,
];
const lineChartsParams = {
series: [
{
label: 'French GDP per capita',
data: FranceGDPperCapita,
},
{
label: 'German GDP per capita',
data: GermanyGDPperCapita,
},
{
label: 'UK GDP per capita',
data: UKGDPperCapita,
},
],
height: 300,
margin: { left: 0 },
yAxis: [{ width: 50 }],
};
const yearFormatter = (date: Date) => date.getFullYear().toString();
const currencyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format;
export default function Formatting() {
return (
<LineChart
{...lineChartsParams}
xAxis={[{ data: years, scaleType: 'time', valueFormatter: yearFormatter }]}
series={lineChartsParams.series.map((series) => ({
...series,
valueFormatter: (v) => (v === null ? '' : currencyFormatter(v)),
}))}
/>
);
}
고급 포맷팅 (Advanced formatting)
시리즈 valueFormatter 함수는 두 번째 인자로 dataIndex 속성을 포함하는 컨텍스트를 받는데, 이를 사용해 다른 데이터 관련 값을 계산할 수 있어요.
아래 데모는 dataIndex를 사용해 각 팀의 순위를 툴팁에 추가해요.
import { PieChart, PieChartProps } from '@mui/x-charts/PieChart';
import { legendClasses } from '@mui/x-charts/ChartsLegend';
const otherProps: Partial<PieChartProps> = {
width: 200,
height: 200,
sx: {
[`.${legendClasses.root}`]: {
transform: 'translate(20px, 0)',
},
},
};
const data = [
{ team: 'Amber Ants', rank: 3, points: 31 },
{ team: 'Eagle Warriors', rank: 1, points: 50 },
{ team: 'Elephant Trunk', rank: 4, points: 18 },
{ team: 'Jaguars', rank: 2, points: 37 },
{ team: 'Smooth Pandas', rank: 5, points: 6 },
];
export default function SeriesFormatter() {
return (
<PieChart
series={[
{
data: data.map((d) => ({ label: d.team, id: d.team, value: d.points })),
valueFormatter: (v, { dataIndex }) => {
const { rank } = data[dataIndex];
return `has ${v.value} points and is ranked ${rank}.`;
},
},
]}
{...otherProps}
/>
);
}
축 포매터 (Axis formatter)
축에서 데이터가 표시되는 방식을 수정하려면 valueFormatter 속성을 사용해요.
그 두 번째 인자는 'tick' 또는 'tooltip' 값을 가진 location 속성을 제공하는 컨텍스트예요.
이 데모에서 볼 수 있는 것:
- 국가 축은 국가 코드만 표시해요.
- 라벨은 주석 데이터인
Country: name (code)를 표시해요.
import { BarChart, BarChartProps } from '@mui/x-charts/BarChart';
const dataset = [
{ name: 'Austria', code: 'AT', gdp: 471 },
{ name: 'Belgium', code: 'BE', gdp: 583 },
{ name: 'Bulgaria', code: 'BG', gdp: 90.35 },
{ name: 'Croatia', code: 'HR', gdp: 71.6 },
{ name: 'Czech Republic', code: 'CZ', gdp: 291 },
{ name: 'Denmark', code: 'DK', gdp: 400 },
{ name: 'Finland', code: 'FI', gdp: 283 },
{ name: 'France', code: 'FR', gdp: 2779 },
{ name: 'Germany', code: 'DE', gdp: 4082 },
{ name: 'Greece', code: 'GR', gdp: 218 },
{ name: 'Hungary', code: 'HU', gdp: 177 },
{ name: 'Ireland', code: 'IE', gdp: 533 },
{ name: 'Italy', code: 'IT', gdp: 2050 },
{ name: 'Netherlands', code: 'NL', gdp: 1009 },
{ name: 'Poland', code: 'PL', gdp: 688 },
{ name: 'Portugal', code: 'PT', gdp: 255 },
{ name: 'Romania', code: 'RO', gdp: 301 },
{ name: 'Slovakia', code: 'SK', gdp: 115 },
{ name: 'Spain', code: 'ES', gdp: 1418 },
{ name: 'Sweden', code: 'SE', gdp: 591 },
];
const chartParams: BarChartProps = {
yAxis: [
{
label: 'GDP (million $USD)',
width: 70,
},
],
series: [
{
label: 'GDP',
dataKey: 'gdp',
valueFormatter: (v) =>
new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
compactDisplay: 'short',
notation: 'compact',
}).format((v || 0) * 1_000_000),
},
],
margin: { left: 0 },
hideLegend: true,
dataset,
height: 400,
};
export default function AxisFormatter() {
return (
<BarChart
xAxis={[
{
scaleType: 'band',
dataKey: 'code',
valueFormatter: (code, context) =>
context.location === 'tick'
? code
: `Country: ${dataset.find((d) => d.code === code)?.name} (${code})`,
},
]}
{...chartParams}
/>
);
}
라벨 포맷팅 (Label formatting)
시리즈 label 속성에 함수를 제공해 툴팁 안의 라벨 텍스트를 조건부로 포맷할 수도 있어요.
아래 예시는 범례에서는 길게 유지하면서 툴팁에서 시리즈 라벨을 줄이는 방법을 보여줘요.
<LineChart
// ...
series={[
{
data: [ ... ],
label: (location) => location === 'tooltip' ? 'BR' : 'Brazil'
}
]}
/>
:::info 자세한 내용은 Label—Conditional formatting 문서를 참고하세요. :::
값 숨기기 (Hiding values)
축 (Axis)
축 props에서 hideTooltip을 사용해 축 값을 숨길 수 있어요. 이렇게 하면 툴팁에서 x축 값을 보여주는 헤더가 제거돼요.
<LineChart
// ...
xAxis={[{ data: [ ... ], hideTooltip: true }]}
/>
시리즈 (Series)
시리즈를 숨기려면 포맷된 값을 null로 설정해요. 공백과 함께 시리즈를 표시하려면 빈 문자열을 반환해요.
값 정렬 (Sorting values)
sort prop을 사용해 축 툴팁에서 시리즈 순서를 수정할 수 있어요. 이 prop은 다음 값을 받아요:
'none'(기본값): 정의된 순서대로 시리즈를 표시해요.'asc': 값을 오름차순으로 정렬해요.'desc': 값을 내림차순으로 정렬해요.
sort prop이 'asc' 또는 'desc'인지와 관계없이, 값이 null인 시리즈는 항상 마지막에 정렬돼요.
import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import { LineChart } from '@mui/x-charts/LineChart';
import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
const sortOptions = ['none', 'asc', 'desc'] as const;
function getExample(sort: 'none' | 'asc' | 'desc') {
return `<LineChart
slotProps={{ tooltip: { trigger: 'axis', sort: '${sort}' } }}
{/* ... */}
/>`;
}
export default function SortDemo() {
const [sort, setSort] = React.useState<'none' | 'asc' | 'desc'>('none');
return (
<Box sx={{ p: 2, width: 1, maxWidth: 600 }}>
<TextField
select
label="sort"
value={sort}
sx={{ minWidth: 200, mb: 2 }}
onChange={(event) => setSort(event.target.value as 'none' | 'asc' | 'desc')}
>
{sortOptions.map((option) => (
<MenuItem key={option} value={option}>
{option}
</MenuItem>
))}
</TextField>
<LineChart
xAxis={[
{
scaleType: 'point',
data: ['page A', 'page B', 'page C', 'page D', 'page E'],
},
]}
series={[
{ data: [2, 5, 3, 4, 1], label: 'Series x', showMark: true },
{ data: [5, 3, 1, null, 10], label: 'Series y', showMark: true },
{ data: [10, 4, 6, 2, 8], label: 'Series z', showMark: true },
]}
slotProps={{ tooltip: { trigger: 'axis', sort } }}
height={300}
hideLegend
margin={{ top: 20, right: 10 }}
/>
<HighlightedCode code={getExample(sort)} language="tsx" />
</Box>
);
}
위치 (Position)
기본적으로 툴팁은 포인터 위치에 상대적으로 배치돼요. 포인터를 사용할 수 없으면 대신 노드(예: 막대 차트의 막대)에 상대적으로 배치돼요.
anchor, position, placement props로 이 동작을 수정할 수 있어요.
anchor: 'pointer' | 'node' | 'chart': 툴팁의 기준이 되는 요소를 나타내요.anchor: 'node'는trigger: 'item'인 툴팁에서만 사용할 수 있어요.anchor: 'chart'는trigger: 'axis'인 툴팁에서만 사용할 수 있어요.
position: 'top' | 'right' | 'bottom' | 'left': 노드 또는 차트에 비교한 기준 위치를 정의해요. 기준이 포인터라면 이 prop은 효과가 없어요.placement: PopperJS의 툴팁 배치예요. 기준 위치에 대한 툴팁 위치를 지정해요. 기본적으로 정의된 경우position과 같은 값을 사용해요.
예를 들어 막대 차트에서 anchor: 'node', position: 'bottom', placement: 'top'으로 설정하면 막대 하단 위에 툴팁이 렌더링돼요.
이 props들은 slotProps.tooltip으로 툴팁에 전달하거나, 커스텀 컴포넌트를 구성하는 경우 ChartsTooltip 또는 ChartsTooltipContainer에 직접 전달할 수 있어요.
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
import { BarChart } from '@mui/x-charts/BarChart';
import { AxisValueFormatterContext } from '@mui/x-charts/models';
import { dataset, valueFormatter } from '../dataset/weather';
const chartSetting = {
height: 300,
};
export default function TooltipPosition() {
return (
<ChartsUsageDemo
componentName="Tooltip"
data={
{
anchor: {
knob: 'select',
defaultValue: 'node',
options: ['undefined', 'pointer', 'node'],
},
position: {
knob: 'select',
defaultValue: 'top',
options: ['undefined', 'top', 'bottom', 'left', 'right'],
},
placement: {
knob: 'select',
defaultValue: 'undefined',
options: [
'undefined',
'top',
'bottom',
'left',
'right',
'top-start',
'top-end',
'bottom-start',
'bottom-end',
],
},
} as const
}
renderDemo={(props) => (
<Box sx={{ width: '100%' }}>
<Typography variant="h6" gutterBottom>
Monthly precipitation
</Typography>
<BarChart
dataset={dataset}
xAxis={[
{
dataKey: 'month',
label: 'months',
height: 50,
valueFormatter: (
value: string,
ctx: AxisValueFormatterContext<'band'>,
) => (ctx.location === 'tick' ? value.slice(0, 1) : value),
},
]}
series={[
{ dataKey: 'london', label: 'London', valueFormatter },
{ dataKey: 'paris', label: 'Paris', valueFormatter },
{ dataKey: 'newYork', label: 'New York', valueFormatter },
{ dataKey: 'seoul', label: 'Seoul', valueFormatter },
]}
slotProps={{
tooltip: {
trigger: 'item',
anchor: props.anchor === 'undefined' ? undefined : props.anchor,
position:
props.position === 'undefined' ? undefined : props.position,
placement:
props.placement === 'undefined' ? undefined : props.placement,
},
}}
{...chartSetting}
/>
</Box>
)}
getCode={({ props }) => `import { BarChart } from '@mui/x-charts/BarChart';
<BarChart
// ...
slotProps={{
tooltip: {
trigger: 'item',${
props.anchor === 'undefined'
? ''
: `
anchor: '${props.anchor}',`
}${
props.position === 'undefined'
? ''
: `
position: '${props.position}',`
}${
props.placement === 'undefined'
? ''
: `
placement: '${props.placement}',`
}
},
}}
/>`}
/>
);
}
툴팁 포탈 (Portaling the tooltip)
기본적으로 툴팁은 고정 위치로 차트 컨테이너 안에 렌더링돼요.
툴팁을 밖에 렌더링하려면 container prop을 사용해 툴팁을 받는 요소를 제공해요. slotProps.tooltip으로 전달하거나, 커스텀 컴포넌트를 구성할 때 ChartsTooltip/ChartsTooltipContainer에 직접 전달할 수 있어요.
<BarChart
// ...
slotProps={{ tooltip: { container: document.body } }}
/>
또는 disablePortal을 설정해 툴팁을 부모의 DOM 계층에 인라인으로 렌더링할 수 있어요.
스타일 수정 (Style modification)
다른 차트 요소와 마찬가지로 CSS 클래스를 사용해 툴팁을 스타일링할 수 있어요. 툴팁은 차트 컨테이너 안에 렌더링되므로 차트의 sx prop을 사용해 스타일링할 수 있어요:
import { chartsTooltipClasses } from '@mui/x-charts';
<LineChart
sx={{
[`& .${chartsTooltipClasses.root} .${chartsTooltipClasses.valueCell}`]: {
color: 'red',
},
}}
/>;
slotProps.tooltip을 통해 툴팁 자체의 sx prop을 사용할 수도 있어요.
import { LineChart } from '@mui/x-charts/LineChart';
import { chartsTooltipClasses } from '@mui/x-charts/ChartsTooltip';
const params = {
xAxis: [{ data: [1, 2, 3, 5, 8, 10] }],
series: [{ data: [2, 5.5, 2, 8.5, 1.5, 5] }],
height: 300,
axisHighlight: { x: 'line' },
} as const;
export default function TooltipStyle() {
return (
<LineChart
{...params}
sx={{
[`& .${chartsTooltipClasses.root} .${chartsTooltipClasses.valueCell}`]: {
color: 'red',
},
}}
/>
);
}
커스텀 툴팁 사용 (Using a custom tooltip)
고급 사용 사례를 위해 완전히 커스터마이즈된 툴팁을 직접 만들 수 있어요. 단일 컴포넌트 차트에서는 slots를 사용해 기본 툴팁을 교체해요:
<LineChart slots={{ tooltip: CustomItemTooltip }} />
커스텀 컴포넌트를 구성할 때는 ChartsDataProvider 안에서 컴포넌트를 사용해요:
<ChartsDataProvider>
<ChartsSurface>{/* ... */}</ChartsSurface>
<CustomItemTooltip />
</ChartsDataProvider>
항목 툴팁 제어 (Controlling the item tooltip)
tooltipItem과 onTooltipItemChange로 항목 툴팁을 제어할 수 있어요.
항목 툴팁이 제어될 때, 포인터가 차트 밖에 있으면 anchor가 'node'로 설정돼요.
:::warning
툴팁 trigger가 "item"으로 설정되어 있는지 확인하세요. 그렇지 않으면 툴팁이 표시되지 않아요.
:::
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import { BarChart, BarChartProps } from '@mui/x-charts/BarChart';
import FormControl from '@mui/material/FormControl';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormLabel from '@mui/material/FormLabel';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import { BarItemIdentifier } from '@mui/x-charts/models';
type Placement = 'top' | 'bottom' | 'left' | 'right';
export default function ControlledTooltip() {
const [tooltipItem, setTooltipItem] = React.useState<BarItemIdentifier | null>({
type: 'bar',
seriesId: 'A',
dataIndex: 0,
});
const [position, setPosition] = React.useState<Placement>('top');
const handleTooltipSeries = (_event: any, newTooltipSeries: string) => {
if (newTooltipSeries !== null) {
setTooltipItem((prev) => ({
type: 'bar',
dataIndex: 0,
...prev,
seriesId: newTooltipSeries,
}));
}
};
const handleTooltipItem = (event: any) => {
setTooltipItem((prev) => ({
type: 'bar',
seriesId: 'A',
...prev,
dataIndex: Number(event.target.value),
}));
};
const handlePosition = (event: React.ChangeEvent<HTMLInputElement>) => {
setPosition(event.target.value as Placement);
};
return (
<Stack
direction={{ xs: 'column', xl: 'row' }}
spacing={1}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1 }}>
<Stack spacing={2} sx={{ alignItems: 'center' }}>
<ToggleButtonGroup
value={tooltipItem?.seriesId ?? null}
exclusive
onChange={handleTooltipSeries}
aria-label="highlighted series"
fullWidth
>
{['A', 'B'].map((type) => (
<ToggleButton key={type} value={type}>
Series {type}
</ToggleButton>
))}
</ToggleButtonGroup>
<FormControl>
<FormLabel id="item-id-radio-group">Item ID</FormLabel>
<RadioGroup
aria-labelledby="item-id-radio-group"
name="radio-buttons-group"
value={tooltipItem?.dataIndex ?? null}
onChange={handleTooltipItem}
row
>
<FormControlLabel value="0" control={<Radio />} label="0" />
<FormControlLabel value="1" control={<Radio />} label="1" />
<FormControlLabel value="2" control={<Radio />} label="2" />
<FormControlLabel value="3" control={<Radio />} label="3" />
<FormControlLabel value="4" control={<Radio />} label="4" />
</RadioGroup>
</FormControl>
<FormControl>
<FormLabel id="position-radio-group">Position</FormLabel>
<RadioGroup
aria-labelledby="position-radio-group"
name="position-radio-group"
value={position}
onChange={handlePosition}
row
>
{(['top', 'bottom', 'left', 'right'] as const).map((p) => (
<FormControlLabel key={p} value={p} control={<Radio />} label={p} />
))}
</RadioGroup>
</FormControl>
</Stack>
<BarChart
{...barChartsProps}
slotProps={{ tooltip: { trigger: 'item', position } }}
tooltipItem={tooltipItem}
onTooltipItemChange={setTooltipItem}
/>
</Box>
</Stack>
);
}
const barChartsProps: BarChartProps = {
series: [
{
data: [3, 4, 1, 6, 5],
label: 'A',
id: 'A',
highlightScope: { highlight: 'item', fade: 'global' },
},
{
data: [4, 3, 1, 5, 8],
label: 'B',
id: 'B',
highlightScope: { highlight: 'item', fade: 'global' },
},
],
height: 250,
};
항목 툴팁 동기화 (Synchronizing item tooltip)
항목 툴팁 제어를 사용해 여러 차트 사이에서 툴팁을 동기화할 수 있어요.
import * as React from 'react';
import Stack from '@mui/material/Stack';
import { styled } from '@mui/material/styles';
import { BarChart, BarChartProps } from '@mui/x-charts/BarChart';
import { PieChart, PieChartProps } from '@mui/x-charts/PieChart';
import { BarItemIdentifier, PieItemIdentifier } from '@mui/x-charts/models';
const CodeBlock = styled('pre')({
minHeight: 125,
});
export default function SyncTooltip() {
const [pieTooltipItem, setPieTooltipItem] =
React.useState<PieItemIdentifier | null>(null);
const [barTooltipItem, setBarTooltipItem] =
React.useState<BarItemIdentifier | null>(null);
return (
<Stack
direction={{ xs: 'column', md: 'row' }}
spacing={1}
sx={{ width: '100%' }}
>
<Stack direction="column" spacing={1} sx={{ flex: 1 }}>
<BarChart
{...barChartsProps}
slotProps={{ tooltip: { trigger: 'item' } }}
tooltipItem={barTooltipItem}
onTooltipItemChange={(newItem) => {
setBarTooltipItem(newItem);
setPieTooltipItem(
newItem === null
? null
: ({
...newItem,
type: 'pie',
} as PieItemIdentifier | null),
);
}}
/>
<CodeBlock>
Tooltip Item: {JSON.stringify(barTooltipItem, null, 2)}
</CodeBlock>
</Stack>
<Stack direction="column" spacing={1} sx={{ flex: 1 }}>
<PieChart
{...pieChartProps}
tooltipItem={pieTooltipItem}
onTooltipItemChange={(newItem) => {
setPieTooltipItem(newItem);
setBarTooltipItem(
newItem === null
? null
: ({
...newItem,
type: 'bar',
} as BarItemIdentifier | null),
);
}}
/>
<CodeBlock>
Tooltip Item: {JSON.stringify(pieTooltipItem, null, 2)}
</CodeBlock>
</Stack>
</Stack>
);
}
const barChartsProps: BarChartProps = {
series: [
{
data: [3, 4, 1, 6, 5],
id: 'sync',
highlightScope: { highlight: 'item', fade: 'global' },
},
],
xAxis: [{ data: ['A', 'B', 'C', 'D', 'E'] }],
height: 200,
hideLegend: true,
};
const pieChartProps: PieChartProps = {
series: [
{
id: 'sync',
data: [
{ value: 3, label: 'A', id: 'A' },
{ value: 4, label: 'B', id: 'B' },
{ value: 1, label: 'C', id: 'C' },
{ value: 6, label: 'D', id: 'D' },
{ value: 5, label: 'E', id: 'E' },
],
highlightScope: { highlight: 'item', fade: 'global' },
},
],
height: 150,
hideLegend: true,
};
축 툴팁 제어 (Controlling the axis tooltip)
tooltipAxis와 onTooltipAxisChange로 축 툴팁을 제어할 수 있어요. { axisId, dataIndex } 객체의 배열을 관리해요.
축 툴팁이 제어될 때, 포인터가 차트 밖에 있으면 anchor가 'chart'로 설정돼요.
:::warning
툴팁 trigger가 "axis"로 설정되어 있는지 확인하세요. 그렇지 않으면 툴팁이 표시되지 않아요.
:::
import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import { BarChart, BarChartProps } from '@mui/x-charts/BarChart';
import FormControl from '@mui/material/FormControl';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormLabel from '@mui/material/FormLabel';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import { AxisItemIdentifier } from '@mui/x-charts/models';
export default function ControlledAxisTooltip() {
const [tooltipAxis, setTooltipAxis] = React.useState<AxisItemIdentifier[]>([
{
axisId: 'x-axis',
dataIndex: 0,
},
]);
const handleTooltipAxis = (event: any) => {
setTooltipAxis([
{
axisId: 'x-axis',
dataIndex: Number(event.target.value),
},
]);
};
return (
<Stack
direction={{ xs: 'column', xl: 'row' }}
spacing={1}
sx={{ width: '100%' }}
>
<Box sx={{ flexGrow: 1 }}>
<Stack spacing={2} sx={{ alignItems: 'center' }}>
<FormControl>
<FormLabel id="item-id-radio-group">Item ID</FormLabel>
<RadioGroup
aria-labelledby="item-id-radio-group"
name="radio-buttons-group"
value={tooltipAxis?.[0]?.dataIndex ?? null}
onChange={handleTooltipAxis}
row
>
<FormControlLabel value="0" control={<Radio />} label="0" />
<FormControlLabel value="1" control={<Radio />} label="1" />
<FormControlLabel value="2" control={<Radio />} label="2" />
<FormControlLabel value="3" control={<Radio />} label="3" />
<FormControlLabel value="4" control={<Radio />} label="4" />
</RadioGroup>
</FormControl>
</Stack>
<BarChart
{...barChartsProps}
slotProps={{
tooltip: { trigger: 'axis', anchor: 'chart', position: 'bottom' },
}}
tooltipAxis={tooltipAxis}
onTooltipAxisChange={setTooltipAxis}
/>
</Box>
</Stack>
);
}
const barChartsProps: BarChartProps = {
series: [
{
data: [3, 4, 1, 6, 5],
label: 'A',
id: 'A',
highlightScope: { highlight: 'item', fade: 'global' },
},
{
data: [4, 3, 1, 5, 8],
label: 'B',
id: 'B',
highlightScope: { highlight: 'item', fade: 'global' },
},
],
xAxis: [{ id: 'x-axis', scaleType: 'band', data: ['A', 'B', 'C', 'D', 'E'] }],
height: 250,
};
차트 간 툴팁 동기화 (Synchronizing tooltips across charts)
쌓인(stacked) 차트들 사이에서 같은 위치의 값을 비교하려면 차트들 간에 강조된 축을 공유하고 모든 차트에 대해 단일 툴팁을 렌더링해요.
각 차트는 동일한 highlightedAxis 상태를 받고 onHighlightedAxisChange로 갱신하므로, 한 차트에 마우스를 올리면 모든 차트에서 십자선이 움직여요. 내장 툴팁은 slotProps={{ tooltip: { trigger: 'none' } }}로 꺼두고, 하나의 툴팁이 공유된 dataIndex에서 각 차트의 값을 읽어요.
import * as React from 'react';
import NoSsr from '@mui/material/NoSsr';
import Paper from '@mui/material/Paper';
import Popper, { PopperProps } from '@mui/material/Popper';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { LineChart } from '@mui/x-charts/LineChart';
import { AxisItemIdentifier } from '@mui/x-charts/models';
const X_AXIS_ID = 'shared-x';
const months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
const charts = [
{
id: 'temperature',
label: 'Temperature',
color: '#02B2AF',
data: [3.9, 5.1, 8.4, 12.1, 16.2, 19.8, 21.9, 21.5, 17.9, 13.4, 8.1, 4.8],
valueFormatter: (value: number) => `${value} °C`,
},
{
id: 'rainfall',
label: 'Rainfall',
color: '#2E96FF',
data: [51, 42, 48, 53, 65, 55, 62, 59, 55, 62, 56, 60],
valueFormatter: (value: number) => `${value} mm`,
},
{
id: 'sunshine',
label: 'Sunshine',
color: '#B800D8',
data: [62, 81, 129, 166, 194, 202, 212, 212, 168, 118, 68, 51],
valueFormatter: (value: number) => `${value} h`,
},
];
export default function SynchronizedTooltip() {
// Shared between every chart. `[]` when no chart is hovered.
const [highlightedAxis, setHighlightedAxis] = React.useState<AxisItemIdentifier[]>(
[],
);
const dataIndex = highlightedAxis[0]?.dataIndex ?? null;
const popperRef: PopperProps['popperRef'] = React.useRef(null);
const positionRef = React.useRef({ x: 0, y: 0 });
const handlePointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
positionRef.current = { x: event.clientX, y: event.clientY };
popperRef.current?.update();
};
const anchorEl = React.useMemo(
() => ({
getBoundingClientRect: () => ({
x: positionRef.current.x,
y: positionRef.current.y,
top: positionRef.current.y,
left: positionRef.current.x,
right: positionRef.current.x,
bottom: positionRef.current.y,
width: 0,
height: 0,
toJSON: () => '',
}),
}),
[],
);
return (
<Stack sx={{ width: '100%' }} onPointerMove={handlePointerMove}>
{charts.map((chart) => (
<LineChart
key={chart.id}
height={160}
margin={{ top: 10, bottom: 10 }}
series={[
{
id: chart.id,
data: chart.data,
label: chart.label,
color: chart.color,
showMark: false,
valueFormatter: (value) =>
value === null ? '' : chart.valueFormatter(value),
},
]}
xAxis={[
{
id: X_AXIS_ID,
scaleType: 'point',
data: months,
// Only the last chart displays the shared axis labels.
tickLabelStyle:
chart.id === charts[charts.length - 1].id
? undefined
: { display: 'none' },
},
]}
yAxis={[{ width: 52 }]}
axisHighlight={{ x: 'line' }}
// Disable the built-in tooltip, a single one is rendered below.
slotProps={{ tooltip: { trigger: 'none' } }}
highlightedAxis={highlightedAxis}
onHighlightedAxisChange={setHighlightedAxis}
hideLegend
/>
))}
<NoSsr>
<Popper
open={dataIndex !== null}
placement="right-start"
anchorEl={anchorEl}
popperRef={popperRef}
modifiers={popperModifiers}
sx={{ pointerEvents: 'none', zIndex: (theme) => theme.zIndex.modal }}
>
{dataIndex !== null && (
<Paper elevation={2} sx={{ p: 1.5, minWidth: 160 }}>
<Typography sx={{ fontWeight: 'medium', mb: 0.5 }}>
{months[dataIndex]}
</Typography>
<Stack spacing={0.5}>
{charts.map((chart) => (
<Stack
key={chart.id}
direction="row"
spacing={1}
sx={{ alignItems: 'center' }}
>
<div
style={{
width: 10,
height: 10,
borderRadius: 2,
backgroundColor: chart.color,
}}
/>
<Typography sx={{ flexGrow: 1, fontWeight: 'light' }}>
{chart.label}
</Typography>
<Typography>
{chart.valueFormatter(chart.data[dataIndex])}
</Typography>
</Stack>
))}
</Stack>
</Paper>
)}
</Popper>
</NoSsr>
</Stack>
);
}
const popperModifiers = [
{ name: 'offset', options: { offset: [0, 8] } },
{ name: 'preventOverflow', options: { altAxis: true } },
];
툴팁 만들기 (Creating a tooltip)
커스텀 툴팁을 만드는 것을 돕기 위해, 라이브러리는 다음 섹션에서 설명하는 헬퍼들을 내보내요:
ChartsTooltipContainer: 툴팁의 열림/닫힘 상태와 위치를 제공하는 래퍼ChartsItemTooltipContent: 기본 항목 툴팁의 콘텐츠를 렌더링해요.ChartsAxisTooltipContent: 기본 축 툴팁의 콘텐츠를 렌더링해요.useItemTooltip(): 현재 항목 툴팁과 관련된 모든 기본 정보를 제공해요.useAxesTooltip(): 현재 축 툴팁과 관련된 모든 기본 정보를 제공해요.
위치 수정 (Modifying the position)
툴팁 위치를 재정의하려면 위치를 관리하는 래퍼를 만들 수 있어요.
function CustomTooltipPopper(props){
// ... (event management) ...
return <NoSsr>
<Popper {/* position */}>
{props.children}
</Popper>
</NoSsr>
}
그런 다음 내장 콘텐츠(ChartsItemTooltipContent 또는 ChartsAxisTooltipContent 사용)나 자체 컴포넌트를 렌더링할 수 있어요.
<CustomTooltipPopper>
<ChartsItemTooltipContent />
</CustomTooltipPopper>
아래 데모는 useXAxis()와 useDrawingArea() 같은 추가 훅을 사용해 툴팁 위치를 커스터마이즈하는 방법을 보여줘요.
import * as React from 'react';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import RadioGroup from '@mui/material/RadioGroup';
import Radio from '@mui/material/Radio';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { BarPlot } from '@mui/x-charts/BarChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsClipPath } from '@mui/x-charts/ChartsClipPath';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import {
ChartsTooltipContainer,
ChartsItemTooltipContent,
} from '@mui/x-charts/ChartsTooltip';
import { ItemTooltip } from './ItemTooltip';
import { ItemTooltipFixedY } from './ItemTooltipFixedY';
import { ItemTooltipTopElement } from './ItemTooltipTopElement';
import { dataset, valueFormatter } from '../dataset/weather';
export default function CustomTooltipPosition() {
const [tooltipType, setTootltipType] = React.useState<
'mouse' | 'fixedY' | 'itemTop'
>('itemTop');
const id = React.useId();
const clipPathId = `${id}-clip-path`;
// Pick one of the custom tooltip wrapper according to the state.
const TooltipPlacement =
(tooltipType === 'mouse' && ItemTooltip) ||
(tooltipType === 'fixedY' && ItemTooltipFixedY) ||
(tooltipType === 'itemTop' && ItemTooltipTopElement) ||
ChartsTooltipContainer;
return (
<div style={{ width: '100%' }}>
<FormControl>
<FormLabel id="tooltip-placement-radio-buttons-group-label">
tooltip placement
</FormLabel>
<RadioGroup
row
aria-labelledby="tooltip-placement-radio-buttons-group-label"
name="tooltip-placement"
value={tooltipType}
onChange={(event) =>
setTootltipType(event.target.value as 'mouse' | 'fixedY' | 'itemTop')
}
>
<FormControlLabel value="mouse" control={<Radio />} label="mouse" />
<FormControlLabel
value="fixedY"
control={<Radio />}
label="top of chart"
/>
<FormControlLabel value="itemTop" control={<Radio />} label="top of bar" />
</RadioGroup>
</FormControl>
<ChartsContainer
height={300}
dataset={dataset}
series={[
{ type: 'bar', dataKey: 'seoul', label: 'Seoul', valueFormatter },
{ type: 'bar', dataKey: 'paris', label: 'Paris', valueFormatter },
]}
xAxis={[{ scaleType: 'band', dataKey: 'month' }]}
>
<g clipPath={`url(#${clipPathId})`}>
<BarPlot />
</g>
<ChartsXAxis />
<ChartsYAxis />
{/* Our custom tooltip wrapper with the default item content. */}
<TooltipPlacement>
<ChartsItemTooltipContent />
</TooltipPlacement>
<ChartsClipPath id={clipPathId} />
</ChartsContainer>
</div>
);
}
콘텐츠 수정 (Modifying the content)
기본 위치를 유지하려면 ChartsTooltipContainer 래퍼를 사용해요. 이 래퍼는 Popper가 언제 열릴지 정의하는 trigger = 'item' | 'axis' prop을 받아요.
항목 콘텐츠 (Item content)
useItemTooltip() 훅은 사용자가 상호작용 중인 현재 항목에 대한 정보를 제공해요. 다음을 포함해요:
identifier: 항목을 식별하는 객체로, 종종 시리즈 유형, 시리즈 ID, 데이터 인덱스를 포함해요.color: 항목을 표시하는 데 사용되는 색으로,colorMap의 영향을 포함해요.label,value,formattedValue: 툴팁 생성을 단순화하기 위해 계산된 값들
import * as React from 'react';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { BarPlot } from '@mui/x-charts/BarChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsClipPath } from '@mui/x-charts/ChartsClipPath';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsTooltipContainer } from '@mui/x-charts/ChartsTooltip';
import { CustomItemTooltip } from './CustomItemTooltip';
import { dataset, valueFormatter } from '../dataset/weather';
export default function CustomTooltipContent() {
const id = React.useId();
const clipPathId = `${id}-clip-path`;
return (
<div style={{ width: '100%' }}>
<ChartsContainer
height={300}
dataset={dataset}
series={[
{ type: 'bar', dataKey: 'seoul', label: 'Seoul', valueFormatter },
{ type: 'bar', dataKey: 'paris', label: 'Paris', valueFormatter },
]}
xAxis={[{ scaleType: 'band', dataKey: 'month' }]}
>
<ChartsClipPath id={clipPathId} />
<g clipPath={`url(#${clipPathId})`}>
<BarPlot />
</g>
<ChartsXAxis />
<ChartsYAxis />
<ChartsTooltipContainer trigger="item">
<CustomItemTooltip />
</ChartsTooltipContainer>
</ChartsContainer>
</div>
);
}
축 콘텐츠 (Axis content)
useAxesTooltip() 훅은 사용자가 상호작용 중인 현재 축과 관련 시리즈에 대한 정보를 반환해요. 각 축에 대해 다음을 포함해요:
identifier: 축을 식별하는 객체로, 종종 시리즈 유형, 시리즈 ID, 데이터 인덱스를 포함해요.color: 항목을 표시하는 데 사용되는 색으로,colorMap의 영향을 포함해요.label,value,formattedValue: 툴팁 생성을 단순화하기 위해 계산된 값들
import * as React from 'react';
import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { BarPlot } from '@mui/x-charts/BarChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsClipPath } from '@mui/x-charts/ChartsClipPath';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ChartsTooltipContainer } from '@mui/x-charts/ChartsTooltip';
import { CustomAxisTooltip } from './CustomAxisTooltip';
import { dataset, valueFormatter } from '../dataset/weather';
export default function CustomAxisTooltipContent() {
const id = React.useId();
const clipPathId = `${id}-clip-path`;
return (
<div style={{ width: '100%' }}>
<ChartsContainer
height={300}
dataset={dataset}
series={[
{ type: 'bar', dataKey: 'seoul', label: 'Seoul', valueFormatter },
{ type: 'bar', dataKey: 'paris', label: 'Paris', valueFormatter },
]}
xAxis={[{ scaleType: 'band', dataKey: 'month' }]}
>
<ChartsClipPath id={clipPathId} />
<g clipPath={`url(#${clipPathId})`}>
<BarPlot />
</g>
<ChartsXAxis />
<ChartsYAxis />
<ChartsTooltipContainer trigger="axis">
<CustomAxisTooltip />
</ChartsTooltipContainer>
</ChartsContainer>
</div>
);
}