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

차트 - Sankey

원문 보기 위키 갱신

차트 - Sankey (샌키)

Sankey 차트로 노드 사이에서 값이 어떻게 흐르는지 보여줄 수 있어요. 링크의 너비는 값의 크기에 비례합니다.

출처: MUI X documentation

본문

개요 (Overview)

Sankey 차트는 노드 사이에서 값이 어떻게 이동하는지 보여주는 흐름 다이어그램이에요. 링크는 소스(source)와 타깃(target)을 연결하고, 링크의 너비는 각 흐름의 크기를 나타냅니다.

아래 데모는 수익(revenue)에서 순이익(net income)까지의 흐름을 USD 기준 십억 단위로 보여줘요.

import * as React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useTheme } from '@mui/material/styles';
import {
  SankeyLinkPlot,
  SankeyNodePlot,
  SankeyTooltip,
  SankeyDataProvider,
} from '@mui/x-charts-pro/SankeyChart';
import { ChartsWrapper } from '@mui/x-charts-pro/ChartsWrapper';
import { ChartsSurface } from '@mui/x-charts-pro/ChartsSurface';
import { CustomNodeLabelPlot } from './CustomNodeLabelPlot';

const data = {
  nodes: [
    // Sub-segment
    { id: 'Server Products', color: '#595b63' },
    { id: 'Enterprise Services', color: '#595b63' },
    { id: 'M365 Commercial', color: '#595b63' },
    { id: 'M365 Consumer', color: '#595b63' },
    { id: 'LinkedIn', color: '#595b63' },
    { id: 'Dynamics', color: '#595b63' },
    { id: 'Gaming', color: '#595b63' },
    { id: 'Windows & Devices', color: '#595b63' },
    { id: 'Search & News Ads', color: '#595b63' },

    // Main revenue segments
    { id: 'Intelligent Cloud', label: 'Cloud', color: '#595b63' },
    { id: 'Productivity', color: '#595b63' },
    { id: 'Personal Computing', label: 'Personal Computing', color: '#595b63' },
    { id: 'Revenue', label: 'Total Revenue', color: '#595b63' },

    // Gross Profit and breakdown
    { id: 'Gross Profit', label: 'Gross Profit', color: '#44CE8D' },
    { id: 'Operating Profit', label: 'Operating Profit', color: '#44CE8D' },
    { id: 'Net Profit', label: 'Net Profit', color: '#44CE8D' },
    { id: 'Tax', label: 'Income Tax', color: '#F35865' },
    { id: 'Other Loss', label: 'Other Loss', color: '#F35865' },
    { id: 'Operating Expenses', label: 'Operating Expenses', color: '#F35865' },
    { id: 'R&D', label: 'R&D', color: '#F35865' },
    { id: 'S&M', label: 'Sales & Marketing', color: '#F35865' },
    { id: 'G&A', label: 'General & Administration', color: '#F35865' },

    // Cost of Revenue and breakdown
    { id: 'Cost of Revenue', label: 'Cost of Revenue', color: '#F35865' },
    { id: 'Product Costs', label: 'Product Costs', color: '#F35865' },
    { id: 'Service Costs', label: 'Service Costs', color: '#F35865' },
  ],

  links: [
    // Revenue-in links
    { source: 'Server Products', target: 'Intelligent Cloud', value: 98.4 },
    { source: 'Enterprise Services', target: 'Intelligent Cloud', value: 7.7 },
    { source: 'M365 Commercial', target: 'Productivity', value: 87.7 },
    { source: 'M365 Consumer', target: 'Productivity', value: 7.4 },
    { source: 'LinkedIn', target: 'Productivity', value: 17.8 },
    { source: 'Dynamics', target: 'Productivity', value: 7.8 },
    { source: 'Gaming', target: 'Personal Computing', value: 23.4 },
    { source: 'Windows & Devices', target: 'Personal Computing', value: 17.3 },
    { source: 'Search & News Ads', target: 'Personal Computing', value: 13.8 },
    { source: 'Intelligent Cloud', target: 'Revenue', value: 106.2 },
    { source: 'Productivity', target: 'Revenue', value: 120.8 },
    { source: 'Personal Computing', target: 'Revenue', value: 54.6 },

    // Revenue-out links
    { source: 'Revenue', target: 'Cost of Revenue', value: 87.8 },
    { source: 'Revenue', target: 'Gross Profit', value: 193.8 },
    { source: 'Gross Profit', target: 'Operating Profit', value: 128.5 },
    { source: 'Gross Profit', target: 'Operating Expenses', value: 65.3 },
    { source: 'Cost of Revenue', target: 'Product Costs', value: 13.5 },
    { source: 'Cost of Revenue', target: 'Service Costs', value: 74.3 },
    { source: 'Operating Profit', target: 'Tax', value: 21.7 },
    { source: 'Operating Profit', target: 'Other Loss', value: 4.9 },
    { source: 'Operating Profit', target: 'Net Profit', value: 101.8 },
    { source: 'Operating Expenses', target: 'R&D', value: 32.4 },
    { source: 'Operating Expenses', target: 'S&M', value: 25.6 },
    { source: 'Operating Expenses', target: 'G&A', value: 7.2 },
  ],
};

const valueFormatter = (value: number, context: { type: string }) => {
  if (context.type === 'link') {
    return `${value}B`;
  }
  // The value of a node is the sum of its incoming links
  return `${value}B total`;
};

export default function SankeyOverview() {
  const theme = useTheme();
  const isDesktop = useMediaQuery(theme.breakpoints.up('sm'));

  return (
    <Box sx={{ width: '100%' }}>
      <Typography
        variant="h5"
        component="h2"
        gutterBottom
        align="center"
        sx={{ fontWeight: 'bold' }}
      >
        Microsoft FY 2025 Income Statement
      </Typography>
      <Typography
        variant="subtitle1"
        align="center"
        sx={{ color: 'text.secondary', mb: 2 }}
      >
        Flow from Revenue to Net Income (in Billions USD)
      </Typography>
      <Box sx={{ width: '100%', height: 600 }}>
        <SankeyDataProvider
          series={[
            {
              type: 'sankey' as const,
              data,
              valueFormatter,
              nodeOptions: {
                sort: 'fixed',
                padding: 20,
                width: 9,
                showLabels: isDesktop,
              },
              linkOptions: {
                color: 'target',
                opacity: 0.6,
                curveCorrection: 0,
                showValues: !isDesktop,
              },
            },
          ]}
          margin={{ top: 20 }}
        >
          <ChartsWrapper>
            <ChartsSurface>
              <SankeyNodePlot />
              <SankeyLinkPlot />
              <CustomNodeLabelPlot />
              <CustomNodeLabelPlot />
            </ChartsSurface>
            {<SankeyTooltip trigger="item" />}
          </ChartsWrapper>
        </SankeyDataProvider>
      </Box>
    </Box>
  );
}

기본 (Basics)

nodes와 links가 있는 데이터 구조를 제공하세요.

  • nodes: 개별 노드를 커스터마이즈하기 위한 선택 배열(라벨, 색상)
  • links: 연결 배열(필수). 각 연결은 source, target, value를 가집니다.

자동 노드 (Automatic nodes)

links에는 나타나지만 nodes에는 없는 노드가 있다면, 차트가 자동으로 생성하고 그 ID를 라벨로 사용해요.

import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';

export default function SankeyBasicDataStructure() {
  return (
    <SankeyChart
      height={250}
      series={{
        data: {
          links: [
            { source: 'A', target: 'B', value: 10 },
            { source: 'A', target: 'C', value: 5 },
            { source: 'B', target: 'D', value: 8 },
            { source: 'C', target: 'D', value: 3 },
          ],
        },
      }}
    />
  );
}

명시적 노드 (Explicit nodes)

nodes 배열에 노드를 정의하면 각 노드에 라벨과 색상을 설정할 수 있어요.

import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';

export default function SankeyDetailedDataStructure() {
  return (
    <SankeyChart
      height={250}
      series={{
        data: {
          nodes: [
            { id: 'source', label: 'Energy Source', color: '#e57373' },
            { id: 'oil', label: 'Oil Production', color: '#f06292' },
            { id: 'gas', label: 'Natural Gas', color: '#ba68c8' },
            { id: 'usage', label: 'Energy Usage', color: '#64b5f6' },
          ],
          links: [
            { source: 'source', target: 'oil', value: 30, color: '#e57373' },
            { source: 'source', target: 'gas', value: 20, color: '#e57373' },
            { source: 'oil', target: 'usage', value: 25, color: '#f06292' },
            { source: 'gas', target: 'usage', value: 15, color: '#ba68c8' },
          ],
        },
      }}
    />
  );
}

스타일링 (Styling)

기본 노드 스타일 (Default node styles)

nodeOptions prop을 사용해 모든 노드에 기본 스타일을 적용할 수 있어요.

import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';

const data = {
  nodes: [
    { id: 'A', label: 'Source A' },
    { id: 'B', label: 'Process B' },
    { id: 'C', label: 'Process C' },
    { id: 'D', label: 'Output D' },
  ],
  links: [
    { source: 'A', target: 'B', value: 15 },
    { source: 'A', target: 'C', value: 10 },
    { source: 'B', target: 'D', value: 12 },
    { source: 'C', target: 'D', value: 8 },
  ],
};

export default function SankeyNodeStyling() {
  return (
    <ChartsUsageDemo
      componentName="SankeyChart"
      data={{
        color: {
          knob: 'input',
          defaultValue: '#1976d2',
        },
        width: {
          knob: 'number',
          defaultValue: 15,
          min: 5,
          max: 50,
        },
        padding: {
          knob: 'number',
          defaultValue: 10,
          min: 0,
          max: 50,
        },
        showLabels: {
          knob: 'switch',
          defaultValue: true,
        },
      }}
      renderDemo={(props) => (
        <SankeyChart
          height={300}
          series={{
            data,
            nodeOptions: {
              color: props.color,
              width: props.width,
              padding: props.padding,
              showLabels: props.showLabels,
            },
          }}
        />
      )}
      getCode={({ props }) => {
        return `import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';

<SankeyChart
  height={300}
  series={{
    data: {
      // ... your data
    },
    nodeOptions: {
      color: '${props.color}',
      width: ${props.width},
      padding: ${props.padding},
      showLabels: ${props.showLabels},
    },
  }}
/>`;
      }}
    />
  );
}

linkOptions prop을 사용해 모든 링크에 기본 스타일을 적용할 수 있어요.

import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';

const data = {
  nodes: [
    { id: 'A', label: 'Source A' },
    { id: 'B', label: 'Process B' },
    { id: 'C', label: 'Process C' },
    { id: 'D', label: 'Output D' },
  ],
  links: [
    { source: 'A', target: 'B', value: 15 },
    { source: 'A', target: 'C', value: 10 },
    { source: 'B', target: 'D', value: 12 },
    { source: 'C', target: 'D', value: 8 },
  ],
};

export default function SankeyLinkStyling() {
  return (
    <ChartsUsageDemo
      componentName="SankeyChart"
      data={{
        color: {
          knob: 'input',
          defaultValue: '#90a4ae',
        },
        opacity: {
          knob: 'number',
          defaultValue: 0.8,
          min: 0.1,
          max: 1,
          step: 0.1,
        },
        showValues: {
          knob: 'switch',
          defaultValue: true,
        },
      }}
      renderDemo={(props) => (
        <SankeyChart
          height={300}
          series={{
            data,
            linkOptions: {
              color: props.color,
              opacity: props.opacity,
              showValues: props.showValues,
            },
            nodeOptions: {
              showLabels: false,
            },
          }}
        />
      )}
      getCode={({ props }) => {
        return `import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';

<SankeyChart
  height={300}
  series={{
    data: {
      // ... your data
    },
    linkOptions: {
      color: '${props.color}',
      opacity: ${props.opacity},
      showValues: ${props.showValues},
    },
  }}
/>`;
      }}
    />
  );
}

링크 색상은 'source'를 사용해 소스 노드에서, 'target'을 사용해 타깃 노드에서 상속받을 수 있어요.

이것은 개별 링크 색상과 linkOptions의 기본값 모두에서 동작합니다.

import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';

const data = {
  nodes: [
    { id: 'Input', label: 'Input' },
    { id: 'ProcessA', label: 'Process A' },
    { id: 'ProcessB', label: 'Process B' },
    { id: 'Output', label: 'Output' },
  ],
  links: [
    { source: 'Input', target: 'ProcessA', value: 30 },
    { source: 'Input', target: 'ProcessB', value: 20 },
    { source: 'ProcessA', target: 'Output', value: 25 },
    { source: 'ProcessB', target: 'Output', value: 15 },
  ],
};

export default function SankeyLinkKeywordColors() {
  return (
    <ChartsUsageDemo
      componentName="SankeyChart"
      data={{
        linkColorMode: {
          knob: 'radio',
          options: ['default', 'source', 'target'],
          defaultValue: 'source',
        },
      }}
      renderDemo={(props) => {
        const linkColor =
          props.linkColorMode === 'default' ? undefined : props.linkColorMode;

        return (
          <SankeyChart
            height={300}
            series={{
              data,
              nodeOptions: {
                showLabels: true,
              },
              linkOptions: {
                color: linkColor,
                opacity: 0.6,
              },
            }}
          />
        );
      }}
      getCode={({ props }) => {
        const linkColor =
          props.linkColorMode === 'default' ? undefined : props.linkColorMode;

        return `import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';

<SankeyChart
  height={300}
  series={{
    data,
    linkOptions: {
      color: ${linkColor ? `'${linkColor}'` : 'undefined'},
      opacity: 0.6,
    },
  }}
/>`;
      }}
    />
  );
}

노드 정렬 (Node alignment)

노드 정렬은 노드를 배치하는 방식을 제어해요.

  • 레이아웃은 그래프 구조에서 노드를 열(column)로 그룹화합니다.
  • 소스 노드는 항상 타깃보다 왼쪽에 위치합니다.
  • 일부 노드는 고정된 열을 가집니다. 이들을 옮기면 레이아웃에 열이 하나 추가됩니다.
  • 다른 노드들은 정렬 방식에 따라 서로 다른 열에 위치할 수 있습니다.

아래 데모에서:

  • 노드 A, B, D, G, I, K는 고정된 위치를 가집니다(이동하면 열이 추가됨)
  • 노드 E는 첫 번째 또는 두 번째 열에 위치할 수 있습니다
  • 노드 F는 4, 5, 6열에 위치할 수 있어요
import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';
import { Stack } from '@mui/system';
import Typography from '@mui/material/Typography';

export default function SankeyNodeAlignment() {
  return (
    <Stack spacing={2} sx={{ width: '100%' }}>
      <Stack direction={['column', 'column', 'row']} spacing={2} sx={{ flex: 1 }}>
        <Stack sx={{ width: '100%' }}>
          <Typography>Left</Typography>
          <SankeyChart
            height={200}
            series={{
              data,
              nodeOptions: {
                align: 'left',
                sort: nodeSortFunction,
              },
            }}
          />
        </Stack>
        <Stack sx={{ width: '100%' }}>
          <Typography>Right</Typography>
          <SankeyChart
            height={200}
            series={{
              data,
              nodeOptions: {
                align: 'right',
                sort: nodeSortFunction,
              },
            }}
          />
        </Stack>
      </Stack>
      <Stack direction={['column', 'column', 'row']} spacing={2} sx={{ flex: 1 }}>
        <Stack sx={{ width: '100%' }}>
          <Typography>Justify</Typography>
          <SankeyChart
            height={200}
            series={{
              data,
              nodeOptions: {
                align: 'justify',
                sort: nodeSortFunction,
              },
            }}
          />
        </Stack>
        <Stack sx={{ width: '100%' }}>
          <Typography>Center</Typography>
          <SankeyChart
            height={200}
            series={{
              data,
              nodeOptions: {
                align: 'center',
                sort: nodeSortFunction,
              },
            }}
          />
        </Stack>
      </Stack>
    </Stack>
  );
}

const data = {
  nodes: [],
  links: [
    { source: 'A', target: 'B', value: 2 },
    { source: 'B', target: 'D', value: 4 },
    { source: 'E', target: 'D', value: 4 },
    { source: 'D', target: 'F', value: 1 },
    { source: 'D', target: 'G', value: 7 },
    { source: 'G', target: 'H', value: 2 },
    { source: 'G', target: 'I', value: 5 },
    { source: 'I', target: 'J', value: 3 },
    { source: 'I', target: 'K', value: 2 },
  ],
};

// Sort nodes alphabetically by label
const nodeSortFunction = (a: any, b: any) => {
  const labelA = a.label || a.id;
  const labelB = b.label || b.id;
  return labelA.localeCompare(labelB);
};

커브 보정 (Curve correction)

curveCorrection prop은 제어점의 x 좌표를 이동시켜 링크 커브를 조정해요. 효과는 그래프 레이아웃과 차트 높이에 따라 달라집니다. 값이 높을수록 링크가 더 두꺼워 보이고, 낮을수록 더 얇아 보여요. 기본값은 10입니다.

import * as React from 'react';
import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';
import Typography from '@mui/material/Typography';
import Slider from '@mui/material/Slider';
import Box from '@mui/material/Box';

const data = {
  links: [
    { source: 'C', target: 'Y', value: 10 },
    { source: 'A', target: 'X', value: 25 },
    { source: 'B', target: 'X', value: 10 },
    { source: 'X', target: 'Z', value: 25 },
    { source: 'Y', target: 'Z', value: 8 },
    { source: 'B', target: 'Y', value: 5 },
  ],
};

export default function SankeyCurveCorrection() {
  const [curveCorrection, setCurveCorrection] = React.useState(10);

  return (
    <Box sx={{ width: '100%' }}>
      <SliderHandle
        curveCorrection={curveCorrection}
        setCurveCorrection={setCurveCorrection}
      />
      <SankeyChart
        height={400}
        series={{
          data,
          linkOptions: {
            curveCorrection,
          },
        }}
      />
    </Box>
  );
}

function SliderHandle(props: {
  curveCorrection: number;
  setCurveCorrection: (value: number) => void;
}) {
  return (
    <React.Fragment>
      <Typography variant="h6" gutterBottom>
        Curve Correction: {props.curveCorrection}
      </Typography>
      <Slider
        value={props.curveCorrection}
        onChange={(_, value) => props.setCurveCorrection(value as number)}
        min={-20}
        max={20}
        step={1}
        sx={{ mb: 3 }}
        marks={[
          { value: -20, label: '-20' },
          { value: -10, label: '-10' },
          { value: 0, label: '0' },
          { value: 5, label: '5' },
          { value: 10, label: '10 (default)' },
          { value: 20, label: '20' },
        ]}
      />
    </React.Fragment>
  );
}

값 포맷팅 (Value formatting)

valueFormatter prop을 사용해 툴팁과 라벨에 값이 표시되는 방식을 커스터마이즈할 수 있어요. 포맷터는 숫자 값과 컨텍스트 객체를 받습니다. 컨텍스트는 location('tooltip' 또는 'label'), type('node' 또는 'link'), 그리고 노드의 경우 nodeId, 링크의 경우 sourceId와 targetId를 포함합니다.

아래 데모는 값에 단위를 추가하고, 포인터가 노드 위에 있을 때 "total"을 표시해요.

import {
  SankeyChart,
  type SankeyValueFormatterContext,
} from '@mui/x-charts-pro/SankeyChart';

const data = {
  nodes: [
    { id: 'Coal', label: 'Coal' },
    { id: 'Natural Gas', label: 'Natural Gas' },
    { id: 'Nuclear', label: 'Nuclear' },
    { id: 'Hydro', label: 'Hydro' },
    { id: 'Wind', label: 'Wind' },
    { id: 'Solar', label: 'Solar' },
    { id: 'Electricity', label: 'Electricity' },
    { id: 'Residential', label: 'Residential' },
    { id: 'Commercial', label: 'Commercial' },
    { id: 'Industrial', label: 'Industrial' },
  ],
  links: [
    { source: 'Coal', target: 'Electricity', value: 300 },
    { source: 'Natural Gas', target: 'Electricity', value: 400 },
    { source: 'Nuclear', target: 'Electricity', value: 200 },
    { source: 'Hydro', target: 'Electricity', value: 100 },
    { source: 'Wind', target: 'Electricity', value: 150 },
    { source: 'Solar', target: 'Electricity', value: 80 },
    { source: 'Electricity', target: 'Residential', value: 450 },
    { source: 'Electricity', target: 'Commercial', value: 350 },
    { source: 'Electricity', target: 'Industrial', value: 430 },
  ],
};

export default function SankeyValueFormatter() {
  return (
    <SankeyChart
      height={300}
      series={{
        data,
        valueFormatter: (value: number, context: SankeyValueFormatterContext) => {
          // Format the value as energy units
          const formatted =
            value >= 1000 ? `${(value / 1000).toFixed(1)} GWh` : `${value} MWh`;

          // You can customize formatting based on context type
          if (context.type === 'link') {
            return `${formatted}`;
          }

          return `${formatted} total`;
        },
        linkOptions: {
          showValues: true,
        },
      }}
    />
  );
}

정렬 (Sorting)

노드는 nodes 배열의 순서대로 렌더링돼요. nodes를 생략하면 links에 처음 나타나는 순서대로 렌더링됩니다. 정렬 옵션을 사용해 순서를 변경할 수 있어요.

노드 정렬 (Node sorting)

nodeOptions.sort 속성은 각 열에서 노드의 세로 순서를 제어합니다. 다음을 받습니다.

  • 두 개의 SankeyLayoutNode 객체를 받아 숫자를 반환하는 함수(Array.sort()처럼)
  • 'auto' (기본값): 링크 교차를 줄이기 위한 자동 정렬
  • 'fixed': nodes 배열의 순서를 유지
import Stack from '@mui/material/Stack';
import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';
import Typography from '@mui/material/Typography';

const data = {
  nodes: [
    { id: 'C' },
    { id: 'B' },
    { id: 'A' },
    { id: 'X' },
    { id: 'Y' },
    { id: 'Z' },
  ],
  links: [
    { source: 'C', target: 'Y', value: 10 },
    { source: 'A', target: 'X', value: 25 },
    { source: 'B', target: 'X', value: 10 },
    { source: 'X', target: 'Z', value: 25 },
    { source: 'Y', target: 'Z', value: 8 },
    { source: 'B', target: 'Y', value: 5 },
  ],
};

// Sort nodes alphabetically by label
const nodeSortFunction = (a: any, b: any) => {
  const labelA = a.label || a.id;
  const labelB = b.label || b.id;
  return labelB.localeCompare(labelA);
};

export default function SankeyNodeSorting() {
  return (
    <Stack
      direction={{ xs: 'column', md: 'row' }}
      spacing={3}
      sx={{ width: '100%', '&>div': { flex: '1 0 0' } }}
    >
      <div style={{ flexGrow: 1 }}>
        <Typography variant="h6" gutterBottom>
          auto (default)
        </Typography>
        <SankeyChart
          height={300}
          series={{
            data,
            nodeOptions: {
              sort: 'auto',
            },
          }}
        />
      </div>

      <div style={{ flexGrow: 1 }}>
        <Typography variant="h6" gutterBottom>
          fixed
        </Typography>
        <SankeyChart
          height={300}
          series={{
            data,
            nodeOptions: {
              sort: 'fixed',
            },
          }}
        />
      </div>

      <div style={{ flexGrow: 1 }}>
        <Typography variant="h6" gutterBottom>
          Custom Function
        </Typography>
        <SankeyChart
          height={300}
          series={{
            data,
            nodeOptions: {
              sort: nodeSortFunction,
            },
          }}
        />
      </div>
    </Stack>
  );
}

linkOptions.sort 속성은 각 노드에서 나가는 링크의 순서를 제어합니다. 다음을 받습니다.

  • 두 개의 SankeyLayoutLink 객체를 받아 숫자를 반환하는 함수
  • 'auto' (기본값): 링크 교차를 줄이기 위한 자동 정렬
  • 'fixed': links 배열의 순서를 유지
import Stack from '@mui/material/Stack';
import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';
import Typography from '@mui/material/Typography';

const data = {
  links: [
    { source: 'C', target: 'Y', value: 10 },
    { source: 'B', target: 'X', value: 10 },
    { source: 'B', target: 'Y', value: 5 },
    { source: 'X', target: 'Z', value: 25 },
    { source: 'Y', target: 'Z', value: 8 },
    { source: 'A', target: 'X', value: 25 },
  ],
};

// Sort links by value (descending)
const linkSortFunction = (a: any, b: any) => b.value - a.value;

export default function SankeyLinkSorting() {
  return (
    <Stack
      direction={{ xs: 'column', md: 'row' }}
      spacing={3}
      sx={{ width: '100%', '&>div': { flex: '1 0 0' } }}
    >
      <div style={{ flexGrow: 1 }}>
        <Typography variant="h6" gutterBottom>
          auto (default)
        </Typography>
        <SankeyChart
          height={300}
          series={{
            data,
            linkOptions: {
              sort: 'auto',
            },
          }}
        />
      </div>

      <div style={{ flexGrow: 1 }}>
        <Typography variant="h6" gutterBottom>
          fixed
        </Typography>
        <SankeyChart
          height={300}
          series={{
            data,
            linkOptions: {
              sort: 'fixed',
            },
          }}
        />
      </div>

      <div style={{ flexGrow: 1 }}>
        <Typography variant="h6" gutterBottom>
          Custom Function
        </Typography>
        <SankeyChart
          height={300}
          series={{
            data,
            linkOptions: {
              sort: linkSortFunction,
            },
          }}
        />
      </div>
    </Stack>
  );
}

레이아웃 반복 (Layout iterations)

iterations prop은 레이아웃 알고리즘이 몇 번 실행될지 설정해요. 반복이 많을수록 보통 레이아웃이 좋아지지만 시간은 더 오래 걸립니다.

import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';
import ChartsUsageDemo from 'docs/src/modules/components/ChartsUsageDemo';

const data = {
  nodes: [
    { id: 'A', label: 'Energy' },
    { id: 'B', label: 'Coal' },
    { id: 'C', label: 'Gas' },
    { id: 'D', label: 'Oil' },
    { id: 'E', label: 'Electricity' },
    { id: 'F', label: 'Heat' },
    { id: 'G', label: 'Residential' },
    { id: 'H', label: 'Commercial' },
    { id: 'I', label: 'Industrial' },
  ],
  links: [
    { source: 'A', target: 'B', value: 30 },
    { source: 'A', target: 'C', value: 25 },
    { source: 'A', target: 'D', value: 20 },
    { source: 'B', target: 'E', value: 25 },
    { source: 'C', target: 'E', value: 20 },
    { source: 'C', target: 'F', value: 5 },
    { source: 'D', target: 'F', value: 18 },
    { source: 'E', target: 'G', value: 15 },
    { source: 'E', target: 'H', value: 20 },
    { source: 'E', target: 'I', value: 10 },
    { source: 'F', target: 'G', value: 8 },
    { source: 'F', target: 'H', value: 10 },
    { source: 'F', target: 'I', value: 5 },
  ],
};

export default function SankeyIterations() {
  return (
    <ChartsUsageDemo
      componentName="SankeyChart"
      data={{
        iterations: {
          knob: 'slider',
          defaultValue: 32,
          min: 1,
          max: 100,
        },
      }}
      renderDemo={(props) => (
        <SankeyChart
          height={400}
          series={{
            data,
            iterations: props.iterations,
          }}
        />
      )}
      getCode={({ props }) => {
        return `import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';

<SankeyChart
  height={400}
  series={{
    data: {
      // ... your data
    },
    iterations: ${props.iterations},
  }}
/>`;
      }}
    />
  );
}

상호작용 (Interaction)

클릭 이벤트 (Click events)

onNodeClick과 onLinkClick prop으로 노드와 링크의 클릭을 처리할 수 있어요. 각 콜백은 마우스 이벤트와 클릭된 항목에 대한 세부 정보가 담긴 식별자 객체(SankeyNodeIdentifierWithData 또는 SankeyLinkIdentifierWithData)를 받습니다. 둘 다 하나의 콜백에서 처리할 때는 SankeyItemIdentifierWithData를 사용하세요.

import * as React from 'react';
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 { SankeyChart, SankeyItemIdentifier } from '@mui/x-charts-pro/SankeyChart';
import { HighlightedCode } from '@mui/internal-core-docs/HighlightedCode';

const getCircularReplacer = () => {
  const seen = new WeakSet();
  return (key: string, value: any) => {
    if (key === 'source' || key === 'target') {
      return '(Circular Node)';
    }
    if (key === 'sourceLinks' || key === 'targetLinks') {
      return '[...(Circular Links)]';
    }

    if (typeof value === 'object' && value !== null) {
      if (seen.has(value)) {
        return undefined;
      }
      seen.add(value);
    }
    return value;
  };
};

const sankeyChartsParams = {
  series: {
    data: {
      nodes: [
        { id: 'Coal', label: 'Coal' },
        { id: 'Natural Gas', label: 'Natural Gas' },
        { id: 'Nuclear', label: 'Nuclear' },
        { id: 'Hydro', label: 'Hydro' },
        { id: 'Wind', label: 'Wind' },
        { id: 'Solar', label: 'Solar' },
        { id: 'Electricity', label: 'Electricity' },
        { id: 'Residential', label: 'Residential' },
        { id: 'Commercial', label: 'Commercial' },
        { id: 'Industrial', label: 'Industrial' },
      ],
      links: [
        { source: 'Coal', target: 'Electricity', value: 30 },
        { source: 'Natural Gas', target: 'Electricity', value: 40 },
        { source: 'Nuclear', target: 'Electricity', value: 20 },
        { source: 'Hydro', target: 'Electricity', value: 10 },
        { source: 'Wind', target: 'Electricity', value: 15 },
        { source: 'Solar', target: 'Electricity', value: 8 },
        { source: 'Electricity', target: 'Residential', value: 45 },
        { source: 'Electricity', target: 'Commercial', value: 35 },
        { source: 'Electricity', target: 'Industrial', value: 43 },
      ],
    },
    highlightScope: {
      highlight: 'item',
    },
  },
  height: 400,
  margin: { left: 20, right: 120 },
} as const;

export default function SankeyClick() {
  const [itemData, setItemData] = React.useState<SankeyItemIdentifier>();

  return (
    <Stack
      direction={{ xs: 'column', md: 'row' }}
      spacing={{ xs: 0, md: 4 }}
      sx={{ width: '100%' }}
    >
      <Box sx={{ flexGrow: 1 }}>
        <SankeyChart
          {...sankeyChartsParams}
          onNodeClick={(event, d) => setItemData(d)}
          onLinkClick={(event, d) => setItemData(d)}
        />
      </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={() => {
              setItemData(undefined);
            }}
          >
            <UndoOutlinedIcon fontSize="small" />
          </IconButton>
        </Box>
        <HighlightedCode
          code={`// Data from item click
${itemData ? JSON.stringify(itemData, getCircularReplacer(), 2) : '// The data will appear here'}
`}
          language="json"
          copyButtonHidden
        />
      </Stack>
    </Stack>
  );
}

하이라이팅 (Highlighting)

호버하거나 프로그래밍 방식으로 노드와 링크를 강조할 수 있어요. 항목이 강조되면 다른 것들을 흐리게(fade) 만들어 초점을 높일 수 있습니다.

import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';

export default function SankeyHighlighting() {
  const [nodeHighlight, setNodeHighlight] = React.useState<
    'nodes' | 'links' | 'incoming' | 'outgoing' | 'none'
  >('links');
  const [nodeFade, setNodeFade] = React.useState<'global' | 'none'>('global');
  const [linkHighlight, setLinkHighlight] = React.useState<
    'links' | 'nodes' | 'source' | 'target' | 'none'
  >('links');
  const [linkFade, setLinkFade] = React.useState<'global' | 'none'>('global');

  return (
    <Stack spacing={2} sx={{ width: '100%' }}>
      <Box sx={{ width: '100%' }}>
        <SankeyChart
          series={{
            data: {
              nodes: [
                { id: 'A', label: 'A' },
                { id: 'B', label: 'B' },
                { id: 'C', label: 'C' },
                { id: 'D', label: 'D' },
                { id: 'E', label: 'E' },
                { id: 'F', label: 'F' },
              ],
              links: [
                { source: 'A', target: 'D', value: 3 },
                { source: 'A', target: 'E', value: 4 },
                { source: 'B', target: 'D', value: 2 },
                { source: 'B', target: 'E', value: 3 },
                { source: 'C', target: 'E', value: 2 },
                { source: 'D', target: 'F', value: 5 },
                { source: 'E', target: 'F', value: 9 },
              ],
            },
            nodeOptions: {
              highlight: nodeHighlight,
              fade: nodeFade,
            },
            linkOptions: {
              highlight: linkHighlight,
              fade: linkFade,
            },
          }}
          height={300}
          margin={{ left: 80, right: 80 }}
        />
      </Box>
      <Stack
        direction={{ xs: 'column', sm: 'row' }}
        spacing={2}
        sx={{ width: '100%' }}
      >
        <Stack spacing={2} sx={{ flex: 1 }}>
          <TextField
            select
            label="Node Highlight"
            value={nodeHighlight}
            onChange={(event) =>
              setNodeHighlight(
                event.target.value as
                  'nodes' | 'links' | 'incoming' | 'outgoing' | 'none',
              )
            }
            fullWidth
          >
            <MenuItem value="nodes">nodes</MenuItem>
            <MenuItem value="links">links</MenuItem>
            <MenuItem value="incoming">incoming</MenuItem>
            <MenuItem value="outgoing">outgoing</MenuItem>
            <MenuItem value="none">none</MenuItem>
          </TextField>
          <TextField
            select
            label="Node Fade"
            value={nodeFade}
            onChange={(event) =>
              setNodeFade(event.target.value as 'global' | 'none')
            }
            fullWidth
          >
            <MenuItem value="global">global</MenuItem>
            <MenuItem value="none">none</MenuItem>
          </TextField>
        </Stack>
        <Stack spacing={2} sx={{ flex: 1 }}>
          <TextField
            select
            label="Link Highlight"
            value={linkHighlight}
            onChange={(event) =>
              setLinkHighlight(
                event.target.value as
                  'links' | 'nodes' | 'source' | 'target' | 'none',
              )
            }
            fullWidth
          >
            <MenuItem value="links">links</MenuItem>
            <MenuItem value="nodes">nodes</MenuItem>
            <MenuItem value="source">source</MenuItem>
            <MenuItem value="target">target</MenuItem>
            <MenuItem value="none">none</MenuItem>
          </TextField>
          <TextField
            select
            label="Link Fade"
            value={linkFade}
            onChange={(event) =>
              setLinkFade(event.target.value as 'global' | 'none')
            }
            fullWidth
          >
            <MenuItem value="global">global</MenuItem>
            <MenuItem value="none">none</MenuItem>
          </TextField>
        </Stack>
      </Stack>
    </Stack>
  );
}

하이라이팅은 노드와 링크에 대해 별도로 설정됩니다.

노드 하이라이팅 (Node highlighting)

nodeOptions.highlight와 nodeOptions.fade를 사용하세요.

nodeOptions.highlight는 노드가 선택되었을 때 무엇을 강조할지 설정합니다.

  • 'nodes': 선택된 노드만
  • 'links': 노드에 연결된 모든 링크
  • 'incoming': 들어오는 링크만
  • 'outgoing': 나가는 링크만
  • 'none': 하이라이팅 없음

nodeOptions.fade는 강조되지 않은 항목을 어떻게 흐리게 할지 설정합니다.

  • 'global': 강조되지 않은 항목을 흐리게
  • 'none': 흐리게 끄기

linkOptions.highlight와 linkOptions.fade를 사용하세요.

linkOptions.highlight는 링크가 선택되었을 때 무엇을 강조할지 설정합니다.

  • 'links': 선택된 링크만
  • 'nodes': 소스와 타깃 노드
  • 'source': 소스 노드만
  • 'target': 타깃 노드만
  • 'none': 하이라이팅 없음

linkOptions.fade는 강조되지 않은 항목을 어떻게 흐리게 할지 설정합니다.

  • 'global': 강조되지 않은 항목을 흐리게
  • 'none': 흐리게 끄기

제어된 하이라이팅 (Controlled highlighting)

highlightedItem과 onHighlightChange prop을 사용해 외부에서 하이라이팅을 제어할 수 있어요. 특정 항목을 프로그래밍 방식으로 강조하거나 차트를 다른 UI와 동기화하고 싶을 때 이 패턴을 사용하세요.

highlightedItem prop은 SankeyNodeIdentifier 또는 SankeyLinkIdentifier를 받습니다.

노드의 경우:

{
  type: 'sankey',
  seriesId: string,
  subType: 'node',
  nodeId: string | number,
}

링크의 경우:

{
  type: 'sankey',
  seriesId: string,
  subType: 'link',
  sourceId: string | number,
  targetId: string | number,
}

onHighlightChange 콜백은 강조된 항목이 변경될 때(사용자 상호작용 또는 프로그래밍 업데이트로) 실행됩니다.

import * as React from 'react';
import Box from '@mui/material/Box';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import { SankeyChart } from '@mui/x-charts-pro/SankeyChart';
import { HighlightItemIdentifier } from '@mui/x-charts-pro/models';

export default function SankeyControlledHighlight() {
  type HighlightItem = HighlightItemIdentifier<'sankey'> | null;
  const [highlightedItem, setHighlightedItem] = React.useState<HighlightItem>({
    seriesId: 'series-id',
    subType: 'node',
    nodeId: 'A',
  });

  const handleHighlightChange: (item: HighlightItem) => void = (item) => {
    setHighlightedItem(item);
  };

  const handleToggleChange = (
    _event: React.MouseEvent<HTMLElement>,
    newValue: string | null,
  ) => {
    if (newValue === null) {
      setHighlightedItem(null);
      return;
    }

    if (newValue.startsWith('node-')) {
      const nodeId = newValue.replace('node-', '');
      setHighlightedItem({
        seriesId: 'series-id',
        subType: 'node',
        nodeId,
      });
    } else if (newValue.startsWith('link-')) {
      const [source, target] = newValue.replace('link-', '').split('-');
      setHighlightedItem({
        seriesId: 'series-id',
        subType: 'link',
        sourceId: source,
        targetId: target,
      });
    }
  };

  const getCurrentValue = () => {
    if (!highlightedItem) {
      return null;
    }
    if (highlightedItem.subType === 'node') {
      return `node-${highlightedItem.nodeId}`;
    }
    return `link-${highlightedItem.sourceId}-${highlightedItem.targetId}`;
  };

  return (
    <Box sx={{ width: '100%' }}>
      <FormControl sx={{ mb: 2 }}>
        <FormLabel>Controlled Highlighting</FormLabel>
        <ToggleButtonGroup
          value={getCurrentValue()}
          exclusive
          onChange={handleToggleChange}
          aria-label="highlight control"
          size="small"
        >
          <ToggleButton value="node-A" aria-label="highlight node A">
            Node A
          </ToggleButton>
          <ToggleButton value="node-C" aria-label="highlight node C">
            Node C
          </ToggleButton>
          <ToggleButton value="node-E" aria-label="highlight node E">
            Node E
          </ToggleButton>
          <ToggleButton value="link-A-C" aria-label="highlight link A to C">
            Link A→C
          </ToggleButton>
          <ToggleButton value="link-B-D" aria-label="highlight link B to D">
            Link B→D
          </ToggleButton>
        </ToggleButtonGroup>
      </FormControl>

      <SankeyChart
        series={{
          id: 'series-id',
          data: {
            nodes: [
              { id: 'A', label: 'Node A', color: '#3b82f6' },
              { id: 'B', label: 'Node B', color: '#10b981' },
              { id: 'C', label: 'Node C', color: '#f59e0b' },
              { id: 'D', label: 'Node D', color: '#ef4444' },
              { id: 'E', label: 'Node E', color: '#8b5cf6' },
            ],
            links: [
              { source: 'A', target: 'C', value: 30 },
              { source: 'A', target: 'D', value: 20 },
              { source: 'B', target: 'C', value: 25 },
              { source: 'B', target: 'D', value: 15 },
              { source: 'C', target: 'E', value: 35 },
              { source: 'D', target: 'E', value: 20 },
            ],
          },
          nodeOptions: {
            highlight: 'links',
            fade: 'global',
          },
          linkOptions: {
            highlight: 'nodes',
            fade: 'global',
          },
        }}
        height={300}
        highlightedItem={highlightedItem}
        onHighlightChange={handleHighlightChange}
      />
    </Box>
  );
}

툴팁 (Tooltip)

기본 Sankey 툴팁은 항목 기반(item-based)이에요. slot으로 커스터마이즈할 수 있습니다. 자세한 내용은 Tooltip을 참고하세요.

Sankey 패키지는 기본 툴팁과 그 콘텐츠를 재사용하거나 확장할 수 있도록 내보냅니다.

import { SankeyTooltip, SankeyTooltipContent } from '@mui/x-charts-pro/SankeyChart';

컴포지션 (Composition)

SankeyDataProvider를 사용해 컴포지션에 series prop을 제공하세요.

composition에서 사용할 수 있는 공유 차트 컴포넌트 외에 다음을 사용할 수 있어요.

  • 항목용: SankeyNodePlot, SankeyLinkPlot
  • 라벨용: SankeyNodeLabelPlot, SankeyLinkLabelPlot
  • 키보드 포커스용: FocusedSankeyNode, FocusedSankeyLink

Sankey 차트가 어떻게 구성되는지는 다음과 같아요.

<SankeyDataProvider series={series as SankeySeriesType[]} {...chartDataProviderProProps}>
  <ChartsWrapper {...chartsWrapperProps}>
    <ChartsSurface {...chartsSurfaceProps}>
      <SankeyLinkPlot onClick={onLinkClick} />
      <SankeyNodePlot onClick={onNodeClick} />

      <SankeyLinkLabelPlot />
      <SankeyNodeLabelPlot />

      <FocusedSankeyNode />
      <FocusedSankeyLink />

      <ChartsOverlay {...overlayProps} />
    </ChartsSurface>
    <ChartsTooltip trigger="item" />
  </ChartsWrapper>
</SankeyDataProvider>

더 알아보기 (Learn more)