차트 - 확대/축소 및 이동(Zoom and pan) [<span class="plan-pro"></span>](/x/introduction/licensing/#pro-plan 'Pro plan')
차트 - 확대/축소 및 이동(Zoom and pan)
차트나 특정 축을 확대/축소하고 이동(pan)하는 방법을 알아봅니다.
본문
확대/축소와 이동을 통해 사용자가 차트 데이터를 자세히 탐색할 수 있어요. 확대(Zoom)는 하나 이상의 축에서 보이는 범위를 좁혀서 뷰어가 관심 영역에 집중할 수 있게 해요. 이동(Pan)은 보이는 창을 움직여서 확대 수준을 바꾸지 않고 뷰를 옮길 수 있게 해요.
Pro 및 Premium 버전의 라인, 막대, 산점, 히트맵 차트에서 확대/축소를 활성화할 수 있어요.
기본 사용법
확대/축소와 이동을 활성화하려면 원하는 축에 zoom prop을 true로 설정하세요.
확대/축소를 활성화하면 모든 상호작용이 자동으로 활성화돼요. 이 상호작용들은 최대한 직관적이도록 설계됐어요.
기본적으로 활성화되는 동작은 다음과 같아요.
- 스크롤(Scroll): 마우스 휠을 스크롤해서 확대/축소
- 드래그(Drag): 마우스를 드래그해서 차트 이동
- 핀치(Pinch): 차트를 핀치해서 확대/축소
설정을 통해 추가 확대/축소 상호작용을 활성화할 수 있어요. 전체 목록은 상호작용을 참고하세요.
import { ScatterChartPro } from '@mui/x-charts-pro/ScatterChartPro';
export default function ZoomScatterChart() {
return (
<ScatterChartPro
height={300}
xAxis={[
{
zoom: true,
},
]}
yAxis={[
{
zoom: true,
},
]}
series={series}
/>
);
}
const data = [
{
id: 'data-0',
x1: 329.39,
x2: 391.29,
y1: 443.28,
y2: 153.9,
},
{
id: 'data-1',
x1: 96.94,
x2: 139.6,
y1: 110.5,
y2: 217.8,
},
{
id: 'data-2',
x1: 336.35,
x2: 282.34,
y1: 175.23,
y2: 286.32,
},
{
id: 'data-3',
x1: 159.44,
x2: 384.85,
y1: 195.97,
y2: 325.12,
},
{
id: 'data-4',
x1: 188.86,
x2: 182.27,
y1: 351.77,
y2: 144.58,
},
{
id: 'data-5',
x1: 143.86,
x2: 360.22,
y1: 43.253,
y2: 146.51,
},
{
id: 'data-6',
x1: 202.02,
x2: 209.5,
y1: 376.34,
y2: 309.69,
},
{
id: 'data-7',
x1: 384.41,
x2: 258.93,
y1: 31.514,
y2: 236.38,
},
{
id: 'data-8',
x1: 256.76,
x2: 70.571,
y1: 231.31,
y2: 440.72,
},
{
id: 'data-9',
x1: 143.79,
x2: 419.02,
y1: 108.04,
y2: 20.29,
},
{
id: 'data-10',
x1: 103.48,
x2: 15.886,
y1: 321.77,
y2: 484.17,
},
{
id: 'data-11',
x1: 272.39,
x2: 189.03,
y1: 120.18,
y2: 54.962,
},
{
id: 'data-12',
x1: 23.57,
x2: 456.4,
y1: 366.2,
y2: 418.5,
},
{
id: 'data-13',
x1: 219.73,
x2: 235.96,
y1: 451.45,
y2: 181.32,
},
{
id: 'data-14',
x1: 54.99,
x2: 434.5,
y1: 294.8,
y2: 440.9,
},
{
id: 'data-15',
x1: 134.13,
x2: 383.8,
y1: 121.83,
y2: 273.52,
},
{
id: 'data-16',
x1: 12.7,
x2: 270.8,
y1: 287.7,
y2: 346.7,
},
{
id: 'data-17',
x1: 176.51,
x2: 119.17,
y1: 134.06,
y2: 74.528,
},
{
id: 'data-18',
x1: 65.05,
x2: 78.93,
y1: 104.5,
y2: 150.9,
},
{
id: 'data-19',
x1: 162.25,
x2: 63.707,
y1: 413.07,
y2: 26.483,
},
{
id: 'data-20',
x1: 68.88,
x2: 150.8,
y1: 74.68,
y2: 333.2,
},
{
id: 'data-21',
x1: 95.29,
x2: 329.1,
y1: 360.6,
y2: 422.0,
},
{
id: 'data-22',
x1: 390.62,
x2: 10.01,
y1: 330.72,
y2: 488.06,
},
];
const series = [
{
label: 'Series A',
data: data.map((v) => ({ x: v.x1, y: v.y1, id: v.id })),
},
{
label: 'Series B',
data: data.map((v) => ({ x: v.x1, y: v.y2, id: v.id })),
},
];
import { BarChartPro } from '@mui/x-charts-pro/BarChartPro';
export default function ZoomBarChart() {
return (
<BarChartPro
height={300}
xAxis={[{ data: data.map((v, i) => i), zoom: true }]}
series={series}
/>
);
}
const data = [
{
y1: 443.28,
y2: 153.9,
},
{
y1: 110.5,
y2: 217.8,
},
{
y1: 175.23,
y2: 286.32,
},
{
y1: 195.97,
y2: 325.12,
},
{
y1: 351.77,
y2: 144.58,
},
{
y1: 43.253,
y2: 146.51,
},
{
y1: 376.34,
y2: 309.69,
},
{
y1: 31.514,
y2: 236.38,
},
{
y1: 231.31,
y2: 440.72,
},
{
y1: 108.04,
y2: 20.29,
},
{
y1: 321.77,
y2: 484.17,
},
{
y1: 120.18,
y2: 54.962,
},
{
y1: 366.2,
y2: 418.5,
},
{
y1: 451.45,
y2: 181.32,
},
{
y1: 294.8,
y2: 440.9,
},
{
y1: 121.83,
y2: 273.52,
},
{
y1: 287.7,
y2: 346.7,
},
{
y1: 134.06,
y2: 74.528,
},
{
y1: 104.5,
y2: 150.9,
},
{
y1: 413.07,
y2: 26.483,
},
{
y1: 74.68,
y2: 333.2,
},
{
y1: 360.6,
y2: 422.0,
},
{
y1: 330.72,
y2: 488.06,
},
];
const series = [
{
label: 'Series A',
data: data.map((v) => v.y1),
},
{
label: 'Series B',
data: data.map((v) => v.y2),
},
];
import { LineChartPro } from '@mui/x-charts-pro/LineChartPro';
export default function ZoomLineChart() {
return (
<LineChartPro
height={300}
xAxis={[
{
zoom: true,
scaleType: 'point',
data: data.map((v, i) => i),
},
]}
series={series}
/>
);
}
const data = [
{
y1: 443.28,
y2: 153.9,
},
{
y1: 110.5,
y2: 217.8,
},
{
y1: 175.23,
y2: 286.32,
},
{
y1: 195.97,
y2: 325.12,
},
{
y1: 351.77,
y2: 144.58,
},
{
y1: 43.253,
y2: 146.51,
},
{
y1: 376.34,
y2: 309.69,
},
{
y1: 31.514,
y2: 236.38,
},
{
y1: 231.31,
y2: 440.72,
},
{
y1: 108.04,
y2: 20.29,
},
{
y1: 321.77,
y2: 484.17,
},
{
y1: 120.18,
y2: 54.962,
},
{
y1: 366.2,
y2: 418.5,
},
{
y1: 451.45,
y2: 181.32,
},
{
y1: 294.8,
y2: 440.9,
},
{
y1: 121.83,
y2: 273.52,
},
{
y1: 287.7,
y2: 346.7,
},
{
y1: 134.06,
y2: 74.528,
},
{
y1: 104.5,
y2: 150.9,
},
{
y1: 413.07,
y2: 26.483,
},
{
y1: 74.68,
y2: 333.2,
},
{
y1: 360.6,
y2: 422.0,
},
{
y1: 330.72,
y2: 488.06,
},
];
const series = [
{
label: 'Series A',
data: data.map((v) => v.y1),
},
{
label: 'Series B',
data: data.map((v) => v.y2),
},
];
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { Heatmap } from '@mui/x-charts-pro/Heatmap';
import {
AxisValueFormatterContext,
HeatmapValueType,
XAxis,
YAxis,
} from '@mui/x-charts-pro/models';
import { useTheme } from '@mui/system';
import { ChartsTooltipContainer, useItemTooltip } from '@mui/x-charts/ChartsTooltip';
import data from '../dataset/muiXCommits2024.json';
const seriesData: HeatmapValueType[] = [];
let maxContributions = 0;
const firstWeekDay = new Date('2023-12-31').getTime();
for (const datum of data) {
const date = new Date(datum.date);
const weekNumber = Math.floor(
(date.getTime() - firstWeekDay) / (7 * 24 * 60 * 60 * 1000),
);
const weekDay = date.getDay();
const value = datum.count;
seriesData.push([weekNumber, weekDay, value]);
maxContributions = Math.max(maxContributions, value);
}
const weeks = Array.from({ length: 53 }).map(
(_, i) => new Date(2023, 11, 31 + i * 7),
);
const weekDays = Array.from({ length: 7 }).map((_, i) => i);
const darkThemeColors = ['#151b23', '#033a16', '#196c2e', '#2ea043', '#56d364'];
const lightThemeColors = ['#eff2f5', '#aceebb', '#4ac26b', '#2da44e', '#116329'];
const xAxis = {
data: weeks,
valueFormatter: (date) => {
if (date.getDate() < 8) {
return date.toLocaleString('en-US', { month: 'short' });
}
return '';
},
tickSize: 0,
ordinalTimeTicks: ['months', 'weeks'],
position: 'top',
disableLine: true,
categoryGapRatio: 0.1,
} satisfies XAxis<'band'>;
const yAxis = {
data: weekDays,
tickSize: 0,
valueFormatter: formatWeekDay,
disableLine: true,
categoryGapRatio: 0.1,
} satisfies YAxis<'band'>;
export default function ZoomHeatmap() {
const theme = useTheme();
return (
<Stack sx={{ width: '100%' }}>
<Typography variant="h6" align="center">
Daily Commit Count to MUI X Repo (2024)
</Typography>
<Heatmap
height={160}
xAxis={[{ ...xAxis, zoom: { minSpan: 60 } }]}
yAxis={[yAxis]}
zAxis={[
{
min: 0,
max: maxContributions,
colorMap: {
type: 'piecewise',
thresholds: [0.01, 0.33, 0.66, 1].map((v) => v * maxContributions),
colors:
theme.palette.mode === 'light' ? lightThemeColors : darkThemeColors,
},
},
]}
series={[{ data: seriesData }]}
borderRadius={4}
slots={{ tooltip: Tooltip }}
/>
<Typography variant="caption">Source: GitHub</Typography>
</Stack>
);
}
const formattedWeekDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
function formatWeekDay(value: number, context: AxisValueFormatterContext): string {
if (context.location === 'tick') {
switch (value) {
case 1:
case 3:
case 5:
return formattedWeekDays[value];
default:
return '';
}
}
return formattedWeekDays[value];
}
function Tooltip() {
return (
<ChartsTooltipContainer trigger="item" position="top">
<TooltipContent />
</ChartsTooltipContainer>
);
}
function TooltipContent() {
const tooltipData = useItemTooltip<'heatmap'>();
if (!tooltipData) {
return null;
}
const { identifier, value } = tooltipData;
const date = new Date(2023, 11, 31 + identifier.xIndex * 7 + identifier.yIndex);
return (
<Stack
sx={(theme) => ({
background: theme.palette.background.paper,
borderRadius: 2,
paddingX: 1,
paddingY: 0.5,
})}
>
<Typography>
{value} contribution{value === 1 ? '' : 's'} on{' '}
{date.toLocaleString('en-US', { month: 'long', day: 'numeric' })}
</Typography>
</Stack>
);
}
Zooming options
Customize the zooming behavior by setting the zoomOptions prop.
The following options are available:
- minStart: The starting percentage of the axis range, between 0 and 100
- maxEnd: The ending percentage of the zoom range
- step: The step of the zooming function, which defines the granularity of the zoom
- minSpan: Restricts the minimum span size
- maxSpan: Restricts the maximum span size
- panning: Enables or disables panning
import { BarChartPro } from '@mui/x-charts-pro/BarChartPro';
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
const knobs = {
panning: {
knob: 'switch',
defaultValue: true,
},
minStart: {
knob: 'number',
defaultValue: 0,
step: 1,
min: 0,
max: 50,
},
maxEnd: {
knob: 'number',
defaultValue: 100,
step: 1,
min: 50,
max: 100,
},
minSpan: {
knob: 'number',
defaultValue: 10,
step: 1,
min: 0,
max: 100,
},
maxSpan: {
knob: 'number',
defaultValue: 100,
step: 1,
min: 0,
max: 100,
},
step: {
knob: 'number',
defaultValue: 5,
step: 1,
min: 1,
max: 100,
},
} as const;
export default function ZoomOptions() {
return (
<ChartsUsageDemo
componentName="Zoom Options demo"
data={knobs}
renderDemo={(props) => (
<div style={{ width: '100%', margin: 4 }}>
<BarChartPro
height={300}
xAxis={[
{
data: data.map((v, i) => i),
zoom: props,
},
]}
series={series}
/>
</div>
)}
getCode={({ props }) => {
return `import { BarChart } from '@mui/x-charts/BarChart';
<BarChart
// ...
xAxis={[
{
// ...
zoom: {
minStart: ${props.minStart},
maxEnd: ${props.maxEnd},
minSpan: ${props.minSpan},
maxSpan: ${props.maxSpan},
step: ${props.step},
panning: ${props.panning},
}
}
]}
/>`;
}}
/>
);
}
const data = [
{
y1: 443.28,
y2: 153.9,
},
{
y1: 110.5,
y2: 217.8,
},
{
y1: 175.23,
y2: 286.32,
},
{
y1: 195.97,
y2: 325.12,
},
{
y1: 351.77,
y2: 144.58,
},
{
y1: 43.253,
y2: 146.51,
},
{
y1: 376.34,
y2: 309.69,
},
{
y1: 31.514,
y2: 236.38,
},
{
y1: 231.31,
y2: 440.72,
},
{
y1: 108.04,
y2: 20.29,
},
];
const series = [
{
label: 'Series A',
data: data.map((v) => v.y1),
},
{
label: 'Series B',
data: data.map((v) => v.y2),
},
];
Zoom filtering
Make the zoom of an axis affect one or more axes' extents by setting the zoom.filterMode prop on the axis config.
- If
zoom.filterModeis set to"discard", the data points outside the visible range of this axis are filtered out, and the other axes modify their zoom range to fit the visible ones - If
zoom.filterModeis set to"keep"(default), the data points outside the visible range are kept, and other axes are not impacted
The demo below shows how the secondary axis adapts to the visible part of the primary axis.
import { BarChartPro } from '@mui/x-charts-pro/BarChartPro';
import { dataset, valueFormatter } from './letterFrequency';
export default function ZoomFilterMode() {
return (
<BarChartPro
height={300}
dataset={dataset}
xAxis={[
{
dataKey: 'letter',
zoom: { filterMode: 'discard' },
},
]}
yAxis={[{ valueFormatter }]}
series={[{ label: 'Letter Frequency', dataKey: 'frequency', valueFormatter }]}
/>
);
}
Zoom slider
Provide an overview that lets users manipulate the zoomed area by setting the zoom.slider.enabled property on the axis config.
import { ScatterChartPro } from '@mui/x-charts-pro/ScatterChartPro';
const dataLength = 801;
const data = Array.from({ length: dataLength }).map((_, i) => ({
x: i,
y: 50 + Math.sin(i / 5) * 25,
}));
const series2Data = Array.from({ length: dataLength }).map((_, i) => ({
x: i,
y: 50 + Math.sin(i / 10) * 25,
}));
const xData = data.map((d) => d.x);
export default function ZoomSlider() {
return (
<ScatterChartPro
xAxis={[
{
id: 'x',
data: xData,
zoom: {
filterMode: 'discard',
minSpan: 10,
panning: true,
slider: { enabled: true },
},
valueFormatter: (v: number) => v.toLocaleString('en-US'),
},
{
id: 'x2',
data: series2Data.map((d) => d.x),
position: 'top',
zoom: {
slider: { enabled: true },
},
},
]}
yAxis={[
{ id: 'y', width: 28, zoom: { slider: { enabled: true } } },
{
id: 'y2',
position: 'right',
width: 28,
zoom: { slider: { enabled: true } },
},
]}
series={[{ data }, { data: series2Data, xAxisId: 'x2', yAxisId: 'y2' }]}
height={400}
margin={{ bottom: 40 }}
initialZoom={[
{ axisId: 'x', start: 45, end: 55 },
{ axisId: 'x2', start: 30, end: 70 },
{ axisId: 'y', start: 40, end: 60 },
{ axisId: 'y2', start: 30, end: 70 },
]}
/>
);
}
Set the zoom.slider.size property to customize the size reserved for the zoom slider.
This is useful if you're using a custom zoom slider and want to update the space reserved for it.
If you're using the default zoom slider, updating zoom.slider.size effectively changes the padding around the slider.
The size is the height on an x-axis and the width on a y-axis.
Tooltip
The zoom slider supports a tooltip that displays the current zoom range.
Configure the tooltip by setting the zoom.slider.showTooltip property on the axis config.
The following options are available:
true: The tooltip is always displayed'hover': The tooltip is displayed on hover (default)false: The tooltip is never displayed
Tooltip value formatting
Customize the value shown in the tooltip by using the valueFormatter property of the respective axis.
When formatting the zoom slider tooltip, the chart calls valueFormatter() with zoom-slider-tooltip as its location.
import * as React from 'react';
import { BarChartPro } from '@mui/x-charts-pro/BarChartPro';
import Stack from '@mui/material/Stack';
import FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
import Select from '@mui/material/Select';
import MenuItem from '@mui/material/MenuItem';
import type { ZoomSliderShowTooltip } from '@mui/x-charts-pro/models';
import type { AxisValueFormatterContext } from '@mui/x-charts/models';
const uData = [4000, 3000, 2000, 2780, 1890, 2390, 3490];
const pData = [2400, 1398, -9800, 3908, 4800, -3800, 4300];
const xLabels = [
'Page A',
'Page B',
'Page C',
'Page D',
'Page E',
'Page F',
'Page G',
];
export default function ZoomSliderTooltip() {
const [showTooltip, setShowTooltip] =
React.useState<ZoomSliderShowTooltip>('hover');
return (
<Stack sx={{ width: '100%' }}>
<FormControl sx={{ width: 150, mb: 2, alignSelf: 'center' }}>
<InputLabel id="show-tooltip-label">Show Tooltip</InputLabel>
<Select
labelId="show-tooltip-label"
id="show-tooltip-select"
value={showTooltip}
label="Show Tooltip"
onChange={(event) =>
setShowTooltip(event.target.value as ZoomSliderShowTooltip)
}
>
<MenuItem value="always">Always</MenuItem>
<MenuItem value="hover">On hover</MenuItem>
<MenuItem value="never">Never</MenuItem>
</Select>
</FormControl>
<BarChartPro
height={300}
series={[
{ data: pData, label: 'Blue' },
{ data: uData, label: 'Yellow' },
]}
xAxis={[
{
id: 'x',
data: xLabels,
valueFormatter: (
value: string,
{ location }: AxisValueFormatterContext,
) =>
location === 'zoom-slider-tooltip' ? `${value.slice(5)}` : `${value}`,
zoom: { slider: { enabled: true, showTooltip } },
},
]}
yAxis={[{ width: 60, max: 10000 }]}
initialZoom={[{ axisId: 'x', start: 20, end: 80 }]}
/>
</Stack>
);
}
확대/축소 옵션
zoomOptions prop을 설정해서 확대/축소 동작을 커스터마이즈할 수 있어요.
다음 옵션을 사용할 수 있어요.
- minStart: 0과 100 사이의 축 범위 시작 백분율
- maxEnd: 확대 범위의 끝 백분율
- step: 확대 함수의 단계로, 확대의 세분성을 정의해요.
- minSpan: 최소 범위 크기를 제한해요.
- maxSpan: 최대 범위 크기를 제한해요.
- panning: 이동을 활성화하거나 비활성화해요.
import * as React from 'react';
import { BarPlot } from '@mui/x-charts/BarChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { LinePlot } from '@mui/x-charts/LineChart';
import { ChartsContainerPro } from '@mui/x-charts-pro/ChartsContainerPro';
import { ChartsClipPath } from '@mui/x-charts/ChartsClipPath';
import { ChartsZoomSlider } from '@mui/x-charts-pro/ChartsZoomSlider';
import { Chance } from 'chance';
const chance = new Chance(42);
const xAxisData = Array.from({ length: 26 }, (_, i) => String.fromCharCode(65 + i));
const firstSeriesData = Array.from({ length: 26 }, () =>
chance.integer({ min: 0, max: 10 }),
);
const secondSeriesData = Array.from({ length: 26 }, () =>
chance.integer({ min: 0, max: 10 }),
);
export default function ZoomSliderComposition() {
const clipPathId = React.useId();
return (
<ChartsContainerPro
series={[
{ type: 'line', data: firstSeriesData },
{ type: 'line', data: secondSeriesData },
]}
xAxis={[
{
data: xAxisData,
scaleType: 'band',
id: 'x-axis-id',
height: 45,
zoom: { slider: { enabled: true } },
},
]}
height={200}
>
<g clipPath={`url(#${clipPathId})`}>
<BarPlot />
<LinePlot />
</g>
<ChartsXAxis label="X axis" axisId="x-axis-id" />
<ChartsZoomSlider />
<ChartsClipPath id={clipPathId} />
</ChartsContainerPro>
);
}
Preview
When the zoom slider is enabled, preview the zoomed area by enabling the zoom.slider.preview property on the axis config.
import * as React from 'react';
import { LineChartPro, LineChartProProps } from '@mui/x-charts-pro/LineChartPro';
import {
AxisValueFormatterContext,
ScatterValueType,
XAxis,
} from '@mui/x-charts/models';
import Typography from '@mui/material/Typography';
import Stack from '@mui/material/Stack';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import ToggleButton from '@mui/material/ToggleButton';
import {
ScatterChartPro,
ScatterChartProProps,
} from '@mui/x-charts-pro/ScatterChartPro';
import { BarChartPro, BarChartProProps } from '@mui/x-charts-pro/BarChartPro';
import {
BarChartPremium,
BarChartPremiumProps,
} from '@mui/x-charts-premium/BarChartPremium';
import { CandlestickChart as CandlestickChart } from '@mui/x-charts-premium/CandlestickChart';
import { OHLCValueType } from '@mui/x-charts-premium/models';
import {
dateAxisFormatter,
usUnemploymentRate,
} from '../dataset/usUnemploymentRate';
import { globalCo2GdpPopulation } from '../dataset/globalCo2GdpPopulation';
import { globalBirthPerWoman } from '../dataset/globalBirthsPerWoman';
import {
continents,
countriesInContinent,
countryData,
} from '../dataset/countryData';
import { shareOfRenewables } from '../dataset/shareOfRenewables';
import { populationPrediction2050 } from '../dataset/populationPrediction2050';
import { temperatureBerlinPorto } from '../dataset/temperatureBerlinPorto';
import sp500 from '../dataset/sp500-intraday.json';
const lineData = usUnemploymentRate.map((d) => d.rate / 100);
const percentageFormatter = new Intl.NumberFormat(undefined, {
style: 'percent',
minimumSignificantDigits: 1,
maximumSignificantDigits: 3,
});
const gdpPerCapitaFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
notation: 'compact',
});
const populationFormatter = new Intl.NumberFormat('en-US', { notation: 'compact' });
const dayFormatter = new Intl.DateTimeFormat(undefined, {
day: 'numeric',
month: '2-digit',
year: 'numeric',
});
const commonXAxisProps = {
id: 'x',
zoom: { filterMode: 'discard', slider: { enabled: true, preview: true } },
} as const;
const commonProps = {
initialZoom: [{ axisId: 'x', start: 20, end: 80 }],
height: 400,
} as const;
const lineXAxis = {
scaleType: 'time',
id: 'x',
data: usUnemploymentRate.map((d) => d.date),
valueFormatter: dateAxisFormatter,
} satisfies XAxis;
const lineSettings = {
yAxis: [
{
id: 'y',
width: 44,
valueFormatter: (v: number | null) => percentageFormatter.format(v!),
min: 0,
},
],
series: [
{
data: lineData,
valueFormatter: (v: number | null) => percentageFormatter.format(v!),
},
],
} satisfies Partial<LineChartProProps>;
const areaXAxis = {
id: 'x',
data: new Array(101).fill(null).map((_, i) => i),
label: 'Age',
valueFormatter: (v: number | null) =>
v === 100 ? '100+' : Math.round(v!).toString(),
} satisfies XAxis;
const areaSettings = {
yAxis: [
{
id: 'y',
width: 44,
valueFormatter: (v: number | null) => populationFormatter.format(v!),
},
],
series: ['Europe', 'Asia', 'Americas', 'Africa', 'Oceania'].map((continent) => ({
data: populationPrediction2050
.filter((point) => point.location === continent)
.map((point) => point.value),
area: true,
label: continent,
stack: 'population',
valueFormatter: (v: number | null) => populationFormatter.format(v!),
})),
} satisfies Partial<LineChartProProps>;
const scatterXAxis = {
valueFormatter: (v: number | null) => gdpPerCapitaFormatter.format(v!),
};
const scatterSettings = {
yAxis: [{ id: 'y', width: 16, min: 0 }],
series: continents.map((continent) => ({
label: continent,
data: countriesInContinent[continent]
.map((code) => ({
id: code,
x: globalCo2GdpPopulation.find((d) => d.code === code)?.gdpPerCapita,
y: globalBirthPerWoman.find((d) => d.code === code)?.rate,
}))
.filter(
(d): d is { id: string; x: number; y: number } =>
d.x !== undefined && d.y !== undefined,
),
valueFormatter: (value: ScatterValueType | null) =>
`${countryData[value!.id as keyof typeof countryData].country} - Birth rate: ${value!.y} - GDP per capita: ${gdpPerCapitaFormatter.format(value!.x)}`,
})),
} satisfies Partial<ScatterChartProProps>;
const sortedShareOfRenewables = shareOfRenewables.toSorted(
(a, b) => a.renewablesPercentage - b.renewablesPercentage,
);
const barXAxis = {
data: sortedShareOfRenewables.map((d) => countryData[d.code].country),
tickLabelStyle: { angle: -45 },
height: 90,
} satisfies XAxis<'band'>;
const barSettings = {
series: [
{
data: sortedShareOfRenewables.map((d) => d.renewablesPercentage / 100),
valueFormatter: (v: number | null) => percentageFormatter.format(v!),
},
],
} satisfies Partial<BarChartProProps>;
const rangeBarXAxis = {
data: temperatureBerlinPorto.months,
valueFormatter: (v: string, context: AxisValueFormatterContext) =>
context.location === 'tick' ? v.slice(0, 3) : v,
} satisfies XAxis<'band'>;
const rangeBarSettings = {
yAxis: [{ valueFormatter: (value: number) => `${value}°C` }],
series: [
{
id: 'porto',
type: 'rangeBar',
label: 'Porto, Portugal',
valueFormatter: (value) =>
value === null ? null : `${value[0]}°C - ${value[1]}°C`,
data: temperatureBerlinPorto.porto,
},
{
id: 'berlin',
type: 'rangeBar',
label: 'Berlin, Germany',
valueFormatter: (value) =>
value === null ? null : `${value[0]}°C - ${value[1]}°C`,
data: temperatureBerlinPorto.berlin,
},
],
} satisfies BarChartPremiumProps;
const candlestickXData = sp500.map((entry) => new Date(Date.parse(entry.date)));
const candlestickData: Array<OHLCValueType> = sp500.map((entry) => [
entry.open,
entry.high,
entry.low,
entry.close,
]);
export default function ZoomSliderPreview() {
const [chartType, setChartType] = React.useState('bar');
const handleChartType = (event: any, newChartType: string) => {
if (newChartType !== null) {
setChartType(newChartType);
}
};
return (
<Stack sx={{ width: '100%', gap: 2 }}>
<ToggleButtonGroup
value={chartType}
exclusive
onChange={handleChartType}
aria-label="chart type"
fullWidth
>
{['bar', 'rangeBar', 'line', 'area', 'scatter', 'candlestick'].map(
(type) => (
<ToggleButton key={type} value={type}>
{type}
</ToggleButton>
),
)}
</ToggleButtonGroup>
{chartType === 'bar' && <BarChartPreview />}
{chartType === 'rangeBar' && <RangeBarChartPreview />}
{chartType === 'line' && <LineChartPreview />}
{chartType === 'area' && <AreaChartPreview />}
{chartType === 'scatter' && <ScatterChartPreview />}
{chartType === 'candlestick' && <CandlestickChartPreview />}
</Stack>
);
}
function LineChartPreview() {
return (
<React.Fragment>
<Typography variant="h6" sx={{ alignSelf: 'center' }}>
Unemployment Rate in United States (1948-2025)
</Typography>
<LineChartPro
{...commonProps}
{...lineSettings}
xAxis={[{ ...lineXAxis, ...commonXAxisProps }]}
/>
<Typography variant="caption">
Source: Federal Reserve Bank of St. Louis. Updated: Jun 6, 2025 7:46 AM CDT.
</Typography>
</React.Fragment>
);
}
function AreaChartPreview() {
return (
<React.Fragment>
<Typography variant="h6" sx={{ alignSelf: 'center' }}>
Population by Age Group in 2050 (Projected)
</Typography>
<LineChartPro
{...commonProps}
{...areaSettings}
xAxis={[{ ...areaXAxis, ...commonXAxisProps }]}
/>
<Typography variant="caption">
Source: World Population Prospects: The 2024 Revision, United Nations.
</Typography>
</React.Fragment>
);
}
function BarChartPreview() {
return (
<React.Fragment>
<Typography variant="h6" sx={{ alignSelf: 'center' }}>
Share of Primary Energy Consumption from Renewables (2023)
</Typography>
<BarChartPro
{...commonProps}
{...barSettings}
xAxis={[{ ...barXAxis, ...commonXAxisProps }]}
/>
<Typography variant="caption">
Source: Our World in Data. Updated: 2023.
</Typography>
</React.Fragment>
);
}
function RangeBarChartPreview() {
return (
<React.Fragment>
<Typography variant="h6" sx={{ alignSelf: 'center' }}>
Average monthly temperature ranges in °C for Porto and Berlin in 1991-2020
</Typography>
<BarChartPremium
{...commonProps}
{...rangeBarSettings}
xAxis={[{ ...rangeBarXAxis, ...commonXAxisProps }]}
/>
<Typography variant="caption">
Source: IPMA (Porto), climate-data.org (Berlin)
</Typography>
</React.Fragment>
);
}
function ScatterChartPreview() {
return (
<React.Fragment>
<Typography variant="h6" sx={{ alignSelf: 'center' }}>
Births per woman vs GDP per capita (USD, 2023)
</Typography>
<ScatterChartPro
{...commonProps}
{...scatterSettings}
xAxis={[{ ...scatterXAxis, ...commonXAxisProps }]}
/>
<Typography variant="caption">
GDP per capita is expressed in international dollars at 2021 prices. <br />
Source: Our World in Data. Updated: 2023.
</Typography>
</React.Fragment>
);
}
function CandlestickChartPreview() {
return (
<React.Fragment>
<Typography variant="h6" sx={{ alignSelf: 'center' }}>
S&P 500 Intraday Price
</Typography>
<CandlestickChart
series={[{ data: candlestickData }]}
xAxis={[
{
data: candlestickXData,
valueFormatter: (v: Date | null) =>
v === null ? '' : dayFormatter.format(new Date(v)),
zoom: {
minSpan: 1,
filterMode: 'discard',
slider: { enabled: true, preview: true },
},
},
]}
height={400}
/>
<Typography variant="caption">Source: Yahoo Finance</Typography>
</React.Fragment>
);
}
확대 필터링
축 구성의 zoom.filterMode prop을 설정해서 한 축의 확대가 하나 이상의 축 범위에 영향을 주도록 만들 수 있어요.
zoom.filterMode를"discard"로 설정하면 이 축의 보이는 범위 밖에 있는 데이터 포인트가 필터링되고, 다른 축은 보이는 것들에 맞게 확대 범위를 조정해요.zoom.filterMode를"keep"(기본값)로 설정하면 보이는 범위 밖의 데이터 포인트가 유지되고, 다른 축은 영향을 받지 않아요.
아래 데모는 보조 축이 주축의 보이는 부분에 어떻게 적응하는지 보여줘요.
import * as React from 'react';
import {
LineChartPro,
type LineChartProProps,
} from '@mui/x-charts-pro/LineChartPro';
import { inflationData } from '../dataset/inflationRates';
const percentageFormatter = (v: number | null) =>
v == null ? '' : `${v.toFixed(1)}%`;
const dataset = inflationData.map((d) => ({
...d,
average: (d.rateDE + d.rateUK + d.rateFR) / 3,
}));
const chartConfig = {
height: 400,
dataset,
yAxis: [{ valueFormatter: percentageFormatter }],
series: [
{
id: 'germany',
dataKey: 'rateDE',
label: 'Germany',
valueFormatter: percentageFormatter,
},
{
id: 'uk',
dataKey: 'rateUK',
label: 'United Kingdom',
valueFormatter: percentageFormatter,
},
{
id: 'average',
dataKey: 'average',
label: 'Average',
valueFormatter: percentageFormatter,
},
],
} satisfies LineChartProProps;
export default function ZoomSliderPreviewSeriesFilter() {
return (
<LineChartPro
{...chartConfig}
xAxis={[
{
dataKey: 'year',
valueFormatter: (v: number) => `${v}`,
zoom: {
slider: {
enabled: true,
preview: { seriesIds: ['average'] },
},
},
},
]}
/>
);
}
Scatter marker size
The size of the preview marker in scatter charts is 1px by default.
Customize it by setting the zoom.slider.preview.markerSize property on the series configuration object.
import * as React from 'react';
import { ScatterValueType } from '@mui/x-charts/models';
import Typography from '@mui/material/Typography';
import Stack from '@mui/material/Stack';
import {
ScatterChartPro,
ScatterChartProProps,
} from '@mui/x-charts-pro/ScatterChartPro';
import Slider from '@mui/material/Slider';
import { globalCo2GdpPopulation } from '../dataset/globalCo2GdpPopulation';
import { globalBirthPerWoman } from '../dataset/globalBirthsPerWoman';
import {
continents,
countriesInContinent,
countryData,
} from '../dataset/countryData';
const gdpPerCapitaFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
notation: 'compact',
});
const scatterXAxis = {
valueFormatter: (v: number | null) => gdpPerCapitaFormatter.format(v!),
};
const dataPerContinent = continents.map((continent) =>
countriesInContinent[continent]
.map((code) => ({
id: code,
x: globalCo2GdpPopulation.find((d) => d.code === code)?.gdpPerCapita,
y: globalBirthPerWoman.find((d) => d.code === code)?.rate,
}))
.filter(
(d): d is { id: string; x: number; y: number } =>
d.x !== undefined && d.y !== undefined,
),
);
const scatterSettings = {
yAxis: [{ id: 'y', width: 16, min: 0 }],
height: 300,
} satisfies Partial<ScatterChartProProps>;
export default function ZoomSliderPreviewCustomMarkerSize() {
const [markerSize, setMarkerSize] = React.useState(2);
const series = continents.map((continent, continentIndex) => ({
label: continent,
data: dataPerContinent[continentIndex],
preview: { markerSize },
valueFormatter: (value: ScatterValueType | null) =>
`${countryData[value!.id as keyof typeof countryData].country} - Birth rate: ${value!.y} - GDP per capita: ${gdpPerCapitaFormatter.format(value!.x)}`,
}));
return (
<Stack
direction="row"
sx={{
width: '100%',
gap: 2,
justifyContent: 'center',
flexWrap: { xs: 'wrap-reverse', sm: 'nowrap' },
}}
>
<Stack sx={{ width: '100%', gap: 2 }}>
<Typography variant="h6" sx={{ alignSelf: 'center' }}>
Births per woman vs GDP per capita (USD, 2023)
</Typography>
<ScatterChartPro
{...scatterSettings}
xAxis={[
{ ...scatterXAxis, zoom: { slider: { enabled: true, preview: true } } },
]}
series={series}
/>
<Typography variant="caption">
GDP per capita is expressed in international dollars at 2021 prices. <br />
Source: Our World in Data. Updated: 2023.
</Typography>
</Stack>
<Stack
sx={{
minWidth: '120px',
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
}}
>
<Typography id="marker-size-slider" gutterBottom>
Marker Size: {markerSize}
</Typography>
<Slider
size="small"
min={1}
max={10}
aria-labelledby="marker-size-slider"
onChange={(event, value) => setMarkerSize(value)}
value={markerSize}
/>
</Stack>
</Stack>
);
}
확대 슬라이더
축 구성의 zoom.slider.enabled 속성을 설정해서 사용자가 확대 영역을 조작할 수 있는 개요(overview)를 제공할 수 있어요.
import * as React from 'react';
import { LineChartPro } from '@mui/x-charts-pro/LineChartPro';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
import { ZoomData } from '@mui/x-charts-pro/models';
import { useChartProApiRef } from '@mui/x-charts-pro/hooks';
import { randomData } from './randomData';
const initialZoomData: ZoomData[] = [
{
axisId: 'my-x-axis',
start: 20,
end: 40,
},
];
export default function ExternalZoomManagement() {
const apiRef = useChartProApiRef<'line'>();
const [zoomData, setZoomData] = React.useState(initialZoomData);
return (
<Stack sx={{ width: '100%', justifyContent: 'flex-start' }}>
<LineChartPro
{...chartProps}
initialZoom={initialZoomData}
apiRef={apiRef}
onZoomChange={setZoomData}
xAxis={[
{
zoom: true,
scaleType: 'point',
id: 'my-x-axis',
data: randomData.map((v, i) => i),
},
]}
/>
<pre>{JSON.stringify(zoomData, null, 2)}</pre>
<div>
<Button
variant="contained"
onClick={() =>
apiRef.current?.setZoomData([
{ axisId: 'my-x-axis', start: 0, end: 100 },
])
}
>
Reset zoom
</Button>
</div>
</Stack>
);
}
const chartProps = {
height: 300,
sx: { width: '100%' },
series: [
{
label: 'Series A',
data: randomData.map((v) => v.y1),
},
{
label: 'Series B',
data: randomData.map((v) => v.y2),
},
],
};
Initialize with a range value
Instead of percentages, an initialZoom entry can describe the range to display with { axisId, value }.
The value accepts the same formats as the toolbar range buttons: a calendar interval, an absolute range, a function, or null.
<LineChartPro
// Show the last 3 months of data
initialZoom={[{ axisId: 'x', value: { unit: 'month', step: 3 } }]}
/>
zoom.slider.size 속성을 설정해서 확대 슬라이더에 예약된 크기를 커스터마이즈할 수 있어요. 주문형 확대 슬라이더를 사용하면서 예약 공간을 업데이트하고 싶을 때 유용해요. 기본 확대 슬라이더를 사용한다면 zoom.slider.size를 업데이트하면 슬라이더 주변 여백이 효과적으로 바뀌어요.
크기는 x축에서는 높이, y축에서는 너비예요.
툴팁
확대 슬라이더는 현재 확대 범위를 표시하는 툴팁을 지원해요.
축 구성의 zoom.slider.showTooltip 속성을 설정해서 툴팁을 구성해요. 다음 옵션을 사용할 수 있어요.
true: 툴팁이 항상 표시돼요.'hover': 호버 시 툴팁이 표시돼요(기본값).false: 툴팁이 절대 표시되지 않아요.
툴팁 값 형식 지정
해당 축의 valueFormatter 속성을 사용해서 툴팁에 표시되는 값을 커스터마이즈할 수 있어요.
확대 슬라이더 툴팁을 포맷할 때 차트는 valueFormatter()를 zoom-slider-tooltip 위치 값과 함께 호출해요.
<BarChartPro
// Zoom from the 'Feb' category to the 'May' category
initialZoom={[{ axisId: 'x', value: ['Feb', 'May'] }]}
/>
Range values are only supported by the uncontrolled initialZoom prop. The controlled zoomData prop still expects explicit percentages.
:::info This feature does not support SSR. When providing a range value, the initial frame is rendered un-zoomed and the zoom is applied on the client right after hydration. :::
import * as React from 'react';
import { LineChartPro } from '@mui/x-charts-pro/LineChartPro';
import { BarChartPro } from '@mui/x-charts-pro/BarChartPro';
import { RangeButtonValue } from '@mui/x-charts-pro/ChartsToolbarPro';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import Stack from '@mui/material/Stack';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
import { dataset } from '../dataset/gdpPerCapitaEvolution';
interface Preset {
/** The label shown in the dropdown. */
label: string;
/** A readable representation of `value`, displayed above the chart. */
code: string;
/** The range value passed to `initialZoom`. */
value: RangeButtonValue;
}
// Time axis: calendar intervals, an absolute date range, a function, or a reset.
const linePresets: Preset[] = [
{
label: '5Y',
code: "{ unit: 'year', step: 5 }",
value: { unit: 'year', step: 5 },
},
{
label: '10Y',
code: "{ unit: 'year', step: 10 }",
value: { unit: 'year', step: 10 },
},
{
label: '2000s',
code: '[new Date(2000, 0, 1), new Date(2010, 0, 1)]',
value: [new Date(2000, 0, 1), new Date(2010, 0, 1)],
},
{
label: 'First half',
code: '() => ({ start: 0, end: 50 })',
value: () => ({ start: 0, end: 50 }),
},
{ label: 'All', code: 'null', value: null },
];
// Band axis: a range expressed with the axis values themselves, or a reset.
const barPresets: Preset[] = [
{ label: 'H1', code: "['Jan', 'Jun']", value: ['Jan', 'Jun'] },
{ label: 'H2', code: "['Jul', 'Dec']", value: ['Jul', 'Dec'] },
{ label: 'Spring–Summer', code: "['Mar', 'Aug']", value: ['Mar', 'Aug'] },
{ label: 'All', code: 'null', value: null },
];
const months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
const sales = [42, 38, 55, 61, 73, 88, 95, 91, 70, 58, 49, 44];
export default function ZoomInitialRange() {
const [chartType, setChartType] = React.useState<'line' | 'bar'>('line');
const [label, setLabel] = React.useState('10Y');
const presets = chartType === 'line' ? linePresets : barPresets;
const preset = presets.find((item) => item.label === label) ?? presets[0];
const handleChartType = (
_event: React.MouseEvent<HTMLElement>,
nextType: 'line' | 'bar' | null,
) => {
if (nextType === null) {
return;
}
setChartType(nextType);
// Switch to a preset that exists for the newly selected chart.
setLabel((nextType === 'line' ? linePresets : barPresets)[1].label);
};
const initialZoom = [{ axisId: 'x', value: preset.value }];
return (
<Stack sx={{ width: '100%' }} spacing={1}>
<Stack direction="row" spacing={2} sx={{ flexWrap: 'wrap' }}>
<ToggleButtonGroup
exclusive
size="small"
value={chartType}
onChange={handleChartType}
>
<ToggleButton value="line">Line</ToggleButton>
<ToggleButton value="bar">Bar</ToggleButton>
</ToggleButtonGroup>
<TextField
select
size="small"
label="Initial zoom"
value={preset.label}
onChange={(event) => setLabel(event.target.value)}
sx={{ minWidth: 180 }}
>
{presets.map((item) => (
<MenuItem key={item.label} value={item.label}>
{item.label}
</MenuItem>
))}
</TextField>
</Stack>
<HighlightedCode
code={`initialZoom={[{ axisId: 'x', value: ${preset.code} }]}`}
language="jsx"
copyButtonHidden
/>
{chartType === 'line' ? (
<LineChartPro
// Remount the chart so `initialZoom` is applied again when the preset changes.
key={`line-${preset.label}`}
dataset={dataset}
xAxis={[
{
id: 'x',
scaleType: 'time',
dataKey: 'date',
zoom: true,
tickNumber: 5,
},
]}
yAxis={[
{
width: 60,
valueFormatter: (value: number) => `$${(value / 1000).toFixed(0)}k`,
},
]}
series={[
{ dataKey: 'fr', label: 'France' },
{ dataKey: 'gb', label: 'UK' },
{ dataKey: 'dl', label: 'Germany' },
]}
height={300}
initialZoom={initialZoom}
/>
) : (
<BarChartPro
// Remount the chart so `initialZoom` is applied again when the preset changes.
key={`bar-${preset.label}`}
xAxis={[{ id: 'x', scaleType: 'band', data: months, zoom: true }]}
series={[{ label: 'Sales', data: sales }]}
height={300}
initialZoom={initialZoom}
/>
)}
</Stack>
);
}
제한(Limits)
확대 슬라이더는 확대/축소 옵션과 동일한 제한을 사용해요. 축 구성의 minStart, maxEnd, minSpan, maxSpan 속성을 설정해서 확대 슬라이더 범위를 제한하세요.
확대 슬라이더는 minStart와 maxEnd로 구분된 범위 밖의 값을 표시하지 않아요.
컴포지션(Composition)
주문형 컴포넌트를 구성할 때는 ChartsZoomSlider 컴포넌트를 렌더링해서 축의 슬라이더를 표시하세요.
import * as React from 'react';
import { LineChartPro } from '@mui/x-charts-pro/LineChartPro';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
import { ZoomData } from '@mui/x-charts-pro/models';
import { BarChartPro } from '@mui/x-charts-pro/BarChartPro';
import { randomData } from './randomData';
const lineAxis = [
{
zoom: true,
scaleType: 'point' as const,
id: 'shared-x-axis',
data: randomData.map((v, i) => i),
},
];
const barAxis = [
{
zoom: true,
id: 'shared-x-axis',
data: randomData.map((v, i) => i),
},
];
const initialZoomData: ZoomData[] = [
{
axisId: 'shared-x-axis',
start: 20,
end: 40,
},
];
export default function ZoomControlled() {
const [zoomData, setZoomData] = React.useState(initialZoomData);
return (
<Stack sx={{ width: '100%', justifyContent: 'flex-start' }}>
<LineChartPro
{...chartProps}
onZoomChange={setZoomData}
zoomData={zoomData}
xAxis={lineAxis}
/>
<BarChartPro
{...chartProps}
onZoomChange={setZoomData}
zoomData={zoomData}
xAxis={barAxis}
/>
<pre>{JSON.stringify(zoomData, null, 2)}</pre>
<div>
<Button
variant="contained"
onClick={() =>
setZoomData([{ axisId: 'shared-x-axis', start: 0, end: 100 }])
}
>
Reset zoom
</Button>
</div>
</Stack>
);
}
const chartProps = {
height: 300,
sx: { width: '100%' },
series: [
{
label: 'Series A',
data: randomData.map((v) => v.y1),
},
{
label: 'Series B',
data: randomData.map((v) => v.y2),
},
],
};
Zoom interactions configuration
Use the zoomInteractionConfig prop to choose which interactions are enabled and when.
Interactions
The zoomInteractionConfig prop lets you specify which interactions are enabled for zooming and panning:
<BarChartPro
zoomInteractionConfig={{
// Enable wheel, pinch, and tap-and-drag zoom
zoom: ['wheel', 'pinch', 'tapAndDrag'],
// Enable drag panning
pan: ['drag'],
}}
/>
미리보기(Preview)
확대 슬라이더가 활성화되어 있으면 축 구성의 zoom.slider.preview 속성을 활성화해서 확대된 영역을 미리볼 수 있어요.
import { ScatterChartPro } from '@mui/x-charts-pro/ScatterChartPro';
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';
const knobs = {
// Zoom interactions
zoom: {
knob: 'title',
displayName: 'Zoom interactions',
},
wheel: {
displayName: 'Wheel',
knob: 'switch',
defaultValue: true,
},
pinch: {
displayName: 'Pinch',
knob: 'switch',
defaultValue: true,
},
tapAndDrag: {
displayName: 'Tap and drag',
knob: 'switch',
defaultValue: false,
},
brush: {
displayName: 'Brush',
knob: 'switch',
defaultValue: false,
},
doubleTapReset: {
displayName: 'Double tap reset',
knob: 'switch',
defaultValue: false,
},
// Pan interactions
pan: {
knob: 'title',
displayName: 'Pan interactions',
},
drag: {
displayName: 'Drag',
knob: 'switch',
defaultValue: true,
},
pressAndDrag: {
displayName: 'Press and drag',
knob: 'switch',
defaultValue: false,
},
wheelPan: {
displayName: 'Pan on wheel',
knob: 'switch',
defaultValue: true,
},
} as const;
export default function ZoomAndPanInteractions() {
return (
<ChartsUsageDemo
componentName="Zoom and Pan Interactions demo"
data={knobs}
renderDemo={(props) => {
// Build zoom interactions array
const zoomInteractions: any[] = [];
if (props.wheel) {
zoomInteractions.push('wheel');
}
if (props.pinch) {
zoomInteractions.push('pinch');
}
if (props.tapAndDrag) {
zoomInteractions.push('tapAndDrag');
}
if (props.brush) {
zoomInteractions.push('brush');
}
if (props.doubleTapReset) {
zoomInteractions.push('doubleTapReset');
}
// Build pan interactions array
const panInteractions: any[] = [];
if (props.drag) {
panInteractions.push('drag');
}
if (props.pressAndDrag) {
panInteractions.push('pressAndDrag');
}
if (props.wheelPan) {
panInteractions.push('wheel');
}
const zoomInteractionConfig = {
zoom: zoomInteractions,
pan: panInteractions,
};
return (
<div style={{ width: '100%' }}>
<ScatterChartPro
height={300}
xAxis={[
{
data: data.map((v, i) => i),
zoom: true,
},
]}
yAxis={[
{
zoom: true,
width: 40,
},
]}
series={series}
zoomInteractionConfig={zoomInteractionConfig}
/>
</div>
);
}}
getCode={({ props }) => {
// Build zoom interactions array for code generation
const zoomInteractions: any[] = [];
if (props.wheel) {
zoomInteractions.push('wheel');
}
if (props.pinch) {
zoomInteractions.push('pinch');
}
if (props.tapAndDrag) {
zoomInteractions.push('tapAndDrag');
}
if (props.brush) {
zoomInteractions.push('brush');
}
if (props.doubleTapReset) {
zoomInteractions.push('doubleTapReset');
}
// Build pan interactions array
const panInteractions: any[] = [];
if (props.drag) {
panInteractions.push('drag');
}
if (props.pressAndDrag) {
panInteractions.push('pressAndDrag');
}
if (props.wheelPan) {
panInteractions.push('wheel');
}
const zoomConfig =
zoomInteractions.length > 0
? `["${zoomInteractions.join('", "')}"]`
: '[]';
const panConfig =
panInteractions.length > 0 ? `["${panInteractions.join('", "')}"]` : '[]';
return `import { ScatterChartPro } from '@mui/x-charts-pro/ScatterChartPro';
<ScatterChartPro
// ...
zoomInteractionConfig={{
zoom: ${zoomConfig},
pan: ${panConfig},
}}
/>`;
}}
/>
);
}
const data = [
{
x: 443,
y: 153,
},
{
x: 110,
y: 217,
},
{
x: 175,
y: 286,
},
{
x: 195,
y: 325,
},
{
x: 351,
y: 144,
},
{
x: 43,
y: 146,
},
{
x: 376,
y: 309,
},
{
x: 31,
y: 236,
},
{
x: 231,
y: 440,
},
{
x: 108,
y: 20,
},
];
const series = [
{
label: 'Series A',
data,
},
];
Brush zoom
The brush zoom interaction lets users select a specific area to zoom into by clicking and dragging to create a selection rectangle. This provides an intuitive way to focus on a particular region of interest in the chart.
import { LineChartPro } from '@mui/x-charts-pro/LineChartPro';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
export default function BrushZoom() {
return (
<Box sx={{ width: '100%' }}>
<Typography variant="body2" sx={{ mb: 2 }}>
Click and drag on the chart to select an area to zoom into. Double-tap to
reset the zoom.
</Typography>
<LineChartPro
height={300}
series={[
{
data: yData,
label: 'Temperature (°C)',
area: true,
},
]}
xAxis={[
{
data: xData,
scaleType: 'point',
zoom: true,
},
]}
zoomInteractionConfig={{
// Enable brush zoom and double-tap reset
zoom: ['brush', 'doubleTapReset'],
// Disable default interactions for this demo
pan: [],
}}
/>
</Box>
);
}
const xData = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
const yData = [2, 5.5, 9, 13.5, 18, 21, 23.5, 23, 20, 15, 9, 4];
시리즈 필터
미리보기에 표시할 시리즈를 선택하려면 zoom.slider.preview.seriesIds를 사용하세요.
<LineChartPro
zoomInteractionConfig={{
zoom: ['wheel', 'pinch', 'keyboard'],
pan: ['drag', 'wheel', 'keyboard'],
}}
/>
Listing the pan interactions also replaces the wheel entry the chart adds on its own to x-only zoom, so keep it if the chart relies on horizontal wheel panning.
The keys only apply while the focus is inside the chart, so they never conflict with the shortcuts of the rest of the page.
| Keys | Description |
|---|---|
| +, = | Zoom in |
| -, _ | Zoom out |
| 0 | Reset the zoom to the full range |
| Shift+Arrow Left, Shift+Arrow Right | Pan the horizontal axis |
| Shift+Arrow Up, Shift+Arrow Down | Pan the vertical axis |
산점 마커 크기
산점 차트에서 미리보기 마커의 크기는 기본적으로 1px예요. 시리즈 구성 객체의 zoom.slider.preview.markerSize 속성을 설정해서 커스터마이즈하세요.
import { LineChartPro } from '@mui/x-charts-pro/LineChartPro';
import { randomData } from './randomData';
export default function ZoomKeyboard() {
return (
<LineChartPro
height={300}
xAxis={[{ data: randomData.map((v, i) => i), zoom: true }]}
yAxis={[{ zoom: true, width: 50 }]}
series={series}
/>
);
}
const series = [
{
label: 'Series A',
data: randomData.map((v) => v.y1),
},
{
label: 'Series B',
data: randomData.map((v) => v.y2),
},
];
Key modifiers
Some interactions let you set up required keys to be pressed to enable the interaction.
Set this up using the requiredKeys property in the interaction configuration.
<BarChartPro
zoomInteractionConfig={{
// Only zoom when Control key is pressed
zoom: [{ type: 'wheel', requiredKeys: ['Control'] }],
// Only pan when Shift key is pressed
pan: [{ type: 'drag', requiredKeys: ['Shift'] }],
}}
/>
확대/축소 관리
외부 확대/축소 관리
확대/축소 상태를 관리하는 방법은 두 가지가 있어요.
initialZoomprop으로 초기 상태를 정의하기- 공개 API의
setZoomData()메서드로 명령적으로 확대 값을 설정하기
또한 onZoomChange prop은 새 확대 상태를 받는 함수예요.
zoom 상태는 확대가 활성화된 각 축의 확대 상태를 정의하는 객체의 배열이에요.
- axisId: 제어할 축의 ID
- start: 축 범위의 시작 백분율
- end: 확대 범위의 끝 백분율
<BarChartPro
zoomInteractionConfig={{
// Only pan when both Shift and Control are pressed
pan: [{ type: 'drag', requiredKeys: ['Shift', 'Control'] }],
}}
/>
Pointer modes
Restrict interactions to specific pointer types by using the mode property:
<BarChartPro
zoomInteractionConfig={{
// Only pan with touch, not mouse
pan: [{ type: 'drag', pointerMode: 'touch' }],
}}
// other props
/>
범위 값으로 초기화하기
백분율 대신 initialZoom 항목은 { axisId, value }로 표시할 범위를 설명할 수 있어요. value는 툴바 범위 버튼과 동일한 형식을 받아요. 즉 달력 구간, 절대 범위, 함수, 또는 null이에요.
<BarChartPro
zoomInteractionConfig={{
pan: [
{ type: 'drag', pointerMode: 'mouse', requiredKeys: ['ControlOrMeta'] },
{ type: 'drag', pointerMode: 'touch', requiredKeys: [] },
],
}}
// other props
/>