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

차트 - 히트맵 [<span class="plan-pro"></span>](/x/introduction/licensing/#pro-plan 'Pro plan')

원문 보기 위키 갱신

차트 - 히트맵

히트맵 차트로 두 차원에 걸쳐 색상 셀 그리드로 강도(intensity)를 표시합니다.

개요

히트맵은 두 차원에 걸쳐 숫자 값이 어떻게 변하는지 색상 셀 그리드로 보여줍니다. 각 셀은 x와 y 범주 또는 눈금(tick)의 교차점이며, 색상이 값을 나타냅니다.

히트맵을 사용하여 강도가 높거나 낮은 영역, 클러스터, 이상치를 찾아낼 수 있습니다.

아래 데모는 파리의 요일별·시간별 자전거 이용량을 보여줍니다.

import { interpolateBlues } from 'd3-scale-chromatic';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { Heatmap } from '@mui/x-charts-pro/Heatmap';
import { HeatmapValueType } from '@mui/x-charts-pro/models';
import bikeData from '../dataset/ParisBicycle.json';

const days = [
  new Date(2025, 1, 24),
  new Date(2025, 1, 25),
  new Date(2025, 1, 26),
  new Date(2025, 1, 27),
  new Date(2025, 1, 28),
  new Date(2025, 2, 1),
  new Date(2025, 2, 2),
];

const hours = [
  '00',
  '01',
  '02',
  '03',
  '04',
  '05',
  '06',
  '07',
  '08',
  '09',
  '10',
  '11',
  '12',
  '13',
  '14',
  '15',
  '16',
  '17',
  '18',
  '19',
  '20',
  '21',
  '22',
  '23',
];

const shortDayFormatter = new Intl.DateTimeFormat('en-US', { weekday: 'short' })
  .format;
const dateFormatter = new Intl.DateTimeFormat('en-US', {
  weekday: 'short',
  day: 'numeric',
  month: 'short',
  year: 'numeric',
}).format;

export default function HeatmapDemo() {
  return (
    <Stack sx={{ width: '100%' }}>
      <Typography align="center" sx={{ width: '100%', mb: 1 }}>
        Bicycle count: Paris - Rivoli street (West-East)
      </Typography>
      <div style={{ flexGrow: 1, minHeight: 0 }}>
        <Heatmap
          height={400}
          margin={{ left: 2 }}
          xAxis={[
            {
              data: days,
              label: 'Day',
              valueFormatter: (value: Date, context) => {
                return context.location === 'tick'
                  ? shortDayFormatter(value)
                  : dateFormatter(value);
              },
              tickLabelStyle: { angle: 45 },
              height: 70,
            },
          ]}
          yAxis={[
            {
              data: hours,
              label: 'Hour of the day',
              tickLabelInterval: (_, index) => index % 2 === 0,
              valueFormatter: (value) => `${value}h`,
              width: 60,
            },
          ]}
          series={[
            {
              data: bikeData as unknown as HeatmapValueType[],
              label: 'Bicycle count',
              highlightScope: { highlight: 'item', fade: 'global' },
            },
          ]}
          zAxis={[
            {
              colorMap: {
                max: 700,
                type: 'continuous',

                color: (t: number) => interpolateBlues(Math.sqrt(t)),
              },
            },
          ]}
          hideLegend={false}
          slotProps={{
            legend: {
              direction: 'vertical',
              position: { vertical: 'top' },
              sx: { height: 200 },
            },
          }}
        />
      </div>
      <Typography variant="caption" sx={{ textAlign: 'end' }}>
        Data from{' '}
        <a href="https://parisdata.opendatasoft.com/explore/dataset/comptage-velo-donnees-compteurs/">
          Paris Data
        </a>
      </Typography>
    </Stack>
  );
}

기초 (Basics)

히트맵 시리즈는 반드시 3-튜플(tuple) 배열인 data 속성을 포함해야 합니다. 각 튜플은 [xIndex, yIndex, value]입니다. 처음 두 숫자는 셀의 x, y 인덱스이고, 세 번째는 셀 값입니다.

<Heatmap
  series={[
    {
      data: [
        [0, 2, 2.7], // Cell (0, 2) receives the value 2.7
        [1, 2, 4.5], // Cell (1, 2) receives the value 4.5
      ],
    },
  ]}
/>

xAxis와 yAxis prop을 사용하여 x, y 눈금을 설정합니다.

import Box from '@mui/material/Box';
import { Heatmap } from '@mui/x-charts-pro/Heatmap';
import { data } from './dumbData';

export default function BasicHeatmap() {
  return (
    <Box sx={{ width: '100%', maxWidth: 400 }}>
      <Heatmap
        xAxis={[{ data: [1, 2, 3, 4] }]}
        yAxis={[{ data: ['A', 'B', 'C', 'D', 'E'] }]}
        series={[{ data }]}
        height={300}
      />
    </Box>
  );
}

데이터셋 사용

dataset prop에 시리즈의 valueGetter를 조합하여 데이터셋 항목을 히트맵 값으로 변환할 수 있습니다. 자세한 내용은 데이터셋 페이지를 참고하세요.

색상 매핑

zAxis 구성을 사용하여 값이 색상에 매핑되는 방식을 커스터마이즈합니다. 조각별(piecewise) 또는 연속(continuous) 스케일을 사용할 수 있습니다. 자세한 내용은 스타일링—값 기반 색상을 참고하세요.

import Stack from '@mui/material/Stack';
import { interpolateBlues } from 'd3-scale-chromatic';
import { Heatmap } from '@mui/x-charts-pro/Heatmap';
import { HeatmapValueType } from '@mui/x-charts-pro/models';

const dataset = [
  {
    london: 59,
    paris: 57,
    newYork: 86,
    seoul: 21,
    month: 'January',
  },
  {
    london: 50,
    paris: 52,
    newYork: 78,
    seoul: 28,
    month: 'February',
  },
  {
    london: 47,
    paris: 53,
    newYork: 106,
    seoul: 41,
    month: 'March',
  },
  {
    london: 54,
    paris: 56,
    newYork: 92,
    seoul: 73,
    month: 'April',
  },
  {
    london: 57,
    paris: 69,
    newYork: 92,
    seoul: 99,
    month: 'May',
  },
  {
    london: 60,
    paris: 63,
    newYork: 103,
    seoul: 144,
    month: 'June',
  },
  {
    london: 59,
    paris: 60,
    newYork: 105,
    seoul: 319,
    month: 'July',
  },
  {
    london: 65,
    paris: 60,
    newYork: 106,
    seoul: 249,
    month: 'August',
  },
  {
    london: 51,
    paris: 51,
    newYork: 95,
    seoul: 131,
    month: 'September',
  },
  {
    london: 60,
    paris: 65,
    newYork: 97,
    seoul: 55,
    month: 'October',
  },
  {
    london: 67,
    paris: 64,
    newYork: 76,
    seoul: 48,
    month: 'November',
  },
  {
    london: 61,
    paris: 70,
    newYork: 103,
    seoul: 25,
    month: 'December',
  },
];

const data = dataset.flatMap(
  ({ london, paris, newYork, seoul }, monthIndex): HeatmapValueType[] => [
    [0, monthIndex, london],
    [1, monthIndex, paris],
    [2, monthIndex, newYork],
    [3, monthIndex, seoul],
  ],
);

const xData = ['London', 'Paris', 'New York', 'Seoul'];
const yData = dataset.flatMap(({ month }) => month);

export default function ColorConfig() {
  return (
    <Stack sx={{ width: '100%' }}>
      <Heatmap
        height={400}
        xAxis={[{ data: xData }]}
        yAxis={[{ data: yData, width: 80 }]}
        series={[{ data }]}
        zAxis={[
          {
            min: 20,
            max: 300,
            colorMap: {
              type: 'continuous',
              color: interpolateBlues,
            },
          },
        ]}
      />
    </Stack>
  );
}

하이라이트 (Highlight)

highlightScope.highlight를 'item'으로 설정하면 마우스를 올린 셀을 강조합니다. highlightScope.fade를 'global'로 설정하면 다른 셀들을 흐리게 처리합니다.

import Box from '@mui/material/Box';
import { Heatmap } from '@mui/x-charts-pro/Heatmap';
import { data } from './dumbData';

export default function HighlightHeatmap() {
  return (
    <Box sx={{ width: '100%', maxWidth: 400 }}>
      <Heatmap
        xAxis={[{ data: [1, 2, 3, 4] }]}
        yAxis={[{ data: ['A', 'B', 'C', 'D', 'E'] }]}
        series={[{ data, highlightScope: { highlight: 'item', fade: 'global' } }]}
        height={300}
      />
    </Box>
  );
}

기본적으로 하이라이트와 페이드는 CSS filter: saturate(...) 속성을 사용합니다. heatmapClasses.highlighted와 heatmapClasses.faded 클래스로 효과를 재정의할 수 있습니다.

아래 데모는 강조된 셀에 테두리 반경을 적용하고, 흐려진 셀의 채도를 낮춥니다.

import Box from '@mui/material/Box';
import { Heatmap, heatmapClasses } from '@mui/x-charts-pro/Heatmap';
import { data } from './dumbData';

export default function HighlightClasses() {
  return (
    <Box sx={{ width: '100%', maxWidth: 400 }}>
      <Heatmap
        sx={{
          [`.${heatmapClasses.cell}`]: {
            [`&.${heatmapClasses.highlighted}`]: {
              filter: 'none', // Remove the default filter effect.
              rx: '10px', // Round the corners
            },
            [`&.${heatmapClasses.faded}`]: {
              filter: 'saturated(95%)', // Reduce the faded default saturation
            },
          },
        }}
        xAxis={[{ data: [1, 2, 3, 4] }]}
        yAxis={[{ data: ['A', 'B', 'C', 'D', 'E'] }]}
        series={[
          {
            data,
            highlightScope: {
              highlight: 'item',
              fade: 'global',
            },
          },
        ]}
        height={300}
      />
    </Box>
  );
}

클릭 이벤트

onItemClick을 사용하여 셀 클릭을 처리합니다.

핸들러는 첫 번째 인자로 클릭 이벤트를, 두 번째 인자로 항목 객체를 받습니다. 항목에는 xIndex와 yIndex(x축·y축에서의 셀 위치)가 포함되며, 셀에 데이터가 있을 때는 dataIndex(시리즈 data 배열에서의 인덱스)도 포함됩니다.

import * as React from 'react';
import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import UndoOutlinedIcon from '@mui/icons-material/UndoOutlined';
import { Heatmap } from '@mui/x-charts-pro/Heatmap';
import type { HeatmapItemIdentifier } from '@mui/x-charts-pro/models';
import { data } from './dumbData';

export default function HeatmapCellClick() {
  const [cellData, setCellData] = React.useState<HeatmapItemIdentifier | null>(null);

  return (
    <Stack
      direction={{ xs: 'column', md: 'row' }}
      spacing={{ xs: 0, md: 4 }}
      sx={{ width: '100%' }}
    >
      <Box sx={{ flexGrow: 1 }}>
        <Heatmap
          xAxis={[{ data: [1, 2, 3, 4] }]}
          yAxis={[{ data: ['A', 'B', 'C', 'D', 'E'] }]}
          series={[
            {
              data: data.filter((_, index) => index !== 5 && index !== 13),
              highlightScope: { highlight: 'item' },
            },
          ]}
          height={300}
          onItemClick={(event, params) => setCellData(params)}
        />
      </Box>

      <Stack direction="column" sx={{ width: { xs: '100%', md: '40%' } }}>
        <Box
          sx={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <Typography>Click on the chart</Typography>
          <IconButton
            aria-label="reset"
            size="small"
            onClick={() => {
              setCellData(null);
            }}
          >
            <UndoOutlinedIcon fontSize="small" />
          </IconButton>
        </Box>
        <HighlightedCode
          code={`// Data from cell click
${cellData ? JSON.stringify(cellData, null, 2) : '// The data will appear here'}
`}
          language="json"
          copyButtonHidden
        />
      </Stack>
    </Stack>
  );
}

공통 기능

히트맵 차트는 다른 차트들과 동일한 축, 툴팁, 범례 패턴을 사용합니다. 이 섹션은 히트맵 특유의 세부 사항을 다룹니다. 전체 옵션은 연결된 페이지를 참고하세요.

축

히트맵 축은 다른 차트 축처럼 구성할 수 있습니다. 자세한 내용은 축 커스터마이즈를 참고하세요.

툴팁

기본 히트맵 툴팁은 항목 기반(item-based)입니다. slots로 커스터마이즈할 수 있습니다. 자세한 내용은 툴팁을 참고하세요.

히트맵 패키지는 재사용하거나 확장하고 싶다면 기본 툴팁과 그 내용을 내보냅니다:

import { HeatmapTooltip, HeatmapTooltipContent } from '@mui/x-charts/Heatmap';

범례

히트맵은 기본적으로 ContinuousColorLegend를 포함합니다.

범례를 숨기려면 hideLegend를 true로 설정하세요. slots.legend와 slotProps.legend로 커스터마이즈합니다.

import Box from '@mui/material/Box';
import { Heatmap } from '@mui/x-charts-pro/Heatmap';
import { data } from './dumbData';

export default function HeatmapLegend() {
  return (
    <Box sx={{ width: '100%', maxWidth: 400 }}>
      <Heatmap
        xAxis={[{ data: [1, 2, 3, 4] }]}
        yAxis={[{ data: ['A', 'B', 'C', 'D', 'E'] }]}
        series={[{ data }]}
        height={300}
        hideLegend={false}
        slotProps={{
          legend: {
            direction: 'vertical',
            position: { vertical: 'middle' },
            sx: { height: 200 },
          },
        }}
      />
    </Box>
  );
}

사용자 정의 셀

cell 슬롯을 사용하여 기본 셀 모양을 바꾸거나 라벨을 추가할 수 있습니다.

import * as React from 'react';
import Box from '@mui/material/Box';
import { Heatmap, type HeatmapCellProps } from '@mui/x-charts-pro/Heatmap';
import { data } from './dumbData';

function CustomCell(props: HeatmapCellProps) {
  const { x, y, width, height, ownerState, ...other } = props;

  return (
    <React.Fragment>
      <rect
        {...other}
        x={x + 4}
        y={y + 4}
        width={width - 2 * 4}
        height={height - 2 * 4}
        fill={ownerState.color}
        clipPath={ownerState.isHighlighted ? undefined : 'inset(0px round 10px)'}
      />
      <text
        x={x + width / 2}
        y={y + height / 2}
        textAnchor="middle"
        dominantBaseline="middle"
        pointerEvents="none"
      >
        {ownerState.value}
      </text>
    </React.Fragment>
  );
}
export default function CustomItem() {
  return (
    <Box sx={{ width: '100%', maxWidth: 400 }}>
      <Heatmap
        slots={{ cell: CustomCell }}
        xAxis={[{ data: [1, 2, 3, 4] }]}
        yAxis={[{ data: ['A', 'B', 'C', 'D', 'E'] }]}
        series={[{ data, highlightScope: { highlight: 'item' } }]}
        height={300}
      />
    </Box>
  );
}

WebGL 렌더러

히트맵은 셀이 많을 수 있는데, 이는 렌더링을 느리게 만들 수 있습니다. 대규모 데이터셋에서 더 나은 성능을 위해 renderer prop을 'webgl'로 설정하세요.

WebGL 렌더러에는 몇 가지 제한이 있습니다:

  • cell 슬롯이 지원되지 않습니다
  • CSS로 셀을 스타일링할 수 없습니다

아래 데모는 WebGL로 렌더링된 약 8,800개의 셀을 보여줍니다.

import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { interpolateOrRd } from 'd3-scale-chromatic';
import {
  HeatmapPremium,
  HeatmapPremiumProps,
} from '@mui/x-charts-premium/HeatmapPremium';
import data from '../dataset/nyc-yellow-taxi-2024-trip-count.json';

const seriesData = data as [number, number, number][];
const max = Math.max(...seriesData.map(([, , value]) => value));
const xData = Array.from({ length: 366 }, (_, i) => {
  const date = new Date(2024, 0, 1);

  date.setDate(i + 1);

  return date;
});
const yData = Array.from({ length: 24 }, (_, i) => i);

const settings: HeatmapPremiumProps = {
  xAxis: [
    {
      data: xData,
      ordinalTimeTicks: ['months', 'biweekly', 'weeks', 'days'],
      valueFormatter: (date: Date) =>
        date.toLocaleString('en-US', { month: 'short', day: 'numeric' }),
      zoom: { minSpan: 3 },
    },
  ],
  yAxis: [{ data: yData, valueFormatter: (hour: number) => `${hour}:00` }],
  zAxis: [
    {
      min: 0,
      max,
      colorMap: {
        type: 'continuous',
        color: interpolateOrRd,
        max,
      },
    },
  ],
  series: [{ data: seriesData }],
  height: 450,
};

export default function WebGLHeatmap() {
  return (
    <Stack sx={{ width: '100%' }}>
      <Typography variant="h6" sx={{ alignSelf: 'center', textAlign: 'center' }}>
        Yellow Taxi Trip Count - 2024
      </Typography>
      <HeatmapPremium renderer="webgl" {...settings} />
      <Typography variant="caption">Source: NYC.gov</Typography>
    </Stack>
  );
}

더 알아보기 (Learn more)