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

Charts - 스파크라인

원문 보기 위키 갱신

Charts - 스파크라인 (Sparkline)

스파크라인을 사용해 축이나 좌표 없이 컴팩트한 차트로 값의 추세를 보여줄 수 있어요. 작은 공간에서 데이터의 흐름을 직관적으로 전달하고 싶을 때 아주 유용하죠.

출처: MUI X documentation

본문

개요

스파크라인은 축 없는 작은 차트로 값의 시퀀스를 그려요. 컴팩트하게 유지되므로 인라인으로 배치할 수 있어요(예: 테이블 셀, 대시보드 위젯, 텍스트 옆). 곡선이나 막대 모양이 스케일이나 라벨 없이 추세를 전달해요.

아래 데모는 npm이 패키지의 주간 다운로드 추세를 스파크라인으로 표시하는 방식을 보여줘요.

import * as React from 'react';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { SparkLineChart, SparkLineChartProps } from '@mui/x-charts/SparkLineChart';
import { lineClasses } from '@mui/x-charts/LineChart';
import { chartsAxisHighlightClasses } from '@mui/x-charts/ChartsAxisHighlight';
import Box from '@mui/material/Box';
import data from './weekly-downloads.json';

const downloads = data.map((item) => item.downloads);
const weeks = data.map((item) => `${item.start} to ${item.end}`);

const settings: SparkLineChartProps = {
  data: downloads,
  baseline: 'min',
  margin: { bottom: 0, top: 5, left: 4, right: 0 },
  xAxis: { id: 'week-axis', data: weeks },
  yAxis: {
    domainLimit: (_, maxValue) => ({
      min: -maxValue / 6, //  Hack to add 5px bellow 0 like npm.
      max: maxValue,
    }),
  },
  sx: {
    [`& .${lineClasses.area}`]: { opacity: 0.2 },
    [`& .${lineClasses.line}`]: { strokeWidth: 3 },
    [`& .${chartsAxisHighlightClasses.root}`]: {
      stroke: 'rgb(137, 86, 255)',
      strokeDasharray: 'none',
      strokeWidth: 2,
    },
  },
  slotProps: {
    lineHighlight: { r: 4 }, // Reduce the radius of the axis highlight.
  },
  clipAreaOffset: { top: 2, bottom: 2 },
  axisHighlight: { x: 'line' },
};

export default function NpmSparkLine() {
  const [weekIndex, setWeekIndex] = React.useState<null | number>(null);

  return (
    <Box
      onKeyDown={(event) => {
        switch (event.key) {
          case 'ArrowLeft':
            setWeekIndex((p) =>
              p === null ? weeks.length - 1 : (weeks.length + p - 1) % weeks.length,
            );
            break;
          case 'ArrowRight':
            setWeekIndex((p) => (p === null ? 0 : (p + 1) % weeks.length));
            break;
          default:
        }
      }}
      onFocus={() => {
        setWeekIndex((p) => (p === null ? 0 : p));
      }}
      role="button"
      aria-label="Showing weekly downloads"
      tabIndex={0}
      sx={{
        width: '100%',
        height: '100%',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <Stack direction="column" sx={{ width: 300 }}>
        <Typography
          sx={{
            color: 'rgb(117, 117, 117)',
            fontWeight: 500,
            fontSize: '0.9rem',
            pt: 1,
          }}
        >
          <DownloadIcon
            fill="rgb(117, 117, 117)"
            width="8px"
            height="12px"
            style={{ marginRight: 8 }}
          />
          {weekIndex === null ? 'Weekly Downloads' : weeks[weekIndex]}
        </Typography>
        <Stack
          direction="row"
          sx={{
            justifyContent: 'space-between',
            alignItems: 'flex-end',
            borderBottom: 'solid 2px rgba(137, 86, 255, 0.2)',
          }}
        >
          <Typography sx={{ fontSize: '1.25rem', fontWeight: 500 }}>
            {downloads[weekIndex ?? downloads.length - 1].toLocaleString()}
          </Typography>

          <SparkLineChart
            height={40}
            width={195}
            area
            showHighlight
            color="rgb(137, 86, 255)"
            onHighlightedAxisChange={(axisItems) => {
              setWeekIndex(axisItems[0]?.dataIndex ?? null);
            }}
            highlightedAxis={
              weekIndex === null
                ? []
                : [{ axisId: 'week-axis', dataIndex: weekIndex }]
            }
            {...settings}
          />
        </Stack>
      </Stack>
    </Box>
  );
}

function DownloadIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 7.22 11.76" aria-hidden="true" {...props}>
      <title>Downloads</title>
      <g>
        <polygon
          points="4.59 4.94 4.59 0 2.62 0 2.62 4.94 0 4.94 3.28 9.53 7.22 4.94 4.59 4.94"
          aria-label="Downloads icon"
        />
        <rect x="0.11" y="10.76" width="7" height="1" />
      </g>
    </svg>
  );
}

기초(Basics)

SparkLineChart는 숫자 배열인 data prop만 필요해요. plotType을 "bar"로 설정하면 선 차트에서 막대 차트로 전환할 수 있어요.

import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';

export default function BasicSparkLine() {
  return (
    <Stack
      direction="row"
      sx={{
        width: '100%',
        gap: 2,

        // For the examples page
        ['@container (width < 600px)']: {
          flexWrap: 'wrap',
          maxWidth: '70%',
        },
      }}
    >
      <Box sx={{ flexGrow: 1 }}>
        <SparkLineChart data={[1, 4, 2, 5, 7, 2, 4, 6]} height={100} />
      </Box>
      <Box sx={{ flexGrow: 1 }}>
        <SparkLineChart
          plotType="bar"
          data={[1, 4, 2, 5, 7, 2, 4, 6]}
          height={100}
        />
      </Box>
    </Stack>
  );
}

선 커스터마이징

area prop을 설정하면 곡선 아래 영역을 채워요. curve prop을 사용해 점 사이에서 선이 보간되는 방식을 바꿀 수 있어요. 커브 옵션은 Lines—Interpolation을 참고하세요.

import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';

export default function AreaSparkLine() {
  return (
    <Stack direction="row" sx={{ width: '100%' }}>
      <Box sx={{ flexGrow: 1 }}>
        <SparkLineChart data={[3, -10, -2, 5, 7, -2, 4, 6]} height={100} area />
      </Box>
      <Box sx={{ flexGrow: 1 }}>
        <SparkLineChart
          data={[3, -10, -2, 5, 7, -2, 4, 6]}
          height={100}
          curve="natural"
          area
        />
      </Box>
    </Stack>
  );
}

상호작용

showTooltip과 showHighlight prop을 사용해 기본 툴팁과 하이라이트를 활성화해요.

더 많은 제어가 필요하면 tooltip과 highlight slots에 커스텀 prop을 전달하세요. 자세한 내용은 Tooltip을 참고하세요.

import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import FormControlLabel from '@mui/material/FormControlLabel';
import Switch from '@mui/material/Switch';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';

export default function BasicSparkLineCustomization() {
  const [showHighlight, setShowHighlight] = React.useState(true);
  const [showTooltip, setShowTooltip] = React.useState(true);

  const handleHighlightChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setShowHighlight(event.target.checked);
  };

  const handleTooltipChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setShowTooltip(event.target.checked);
  };

  return (
    <Stack direction="column" sx={{ width: '100%' }}>
      <Stack direction="row">
        <FormControlLabel
          value="end"
          control={
            <Switch
              color="primary"
              checked={showHighlight}
              onChange={handleHighlightChange}
            />
          }
          label="showHighlight"
          labelPlacement="end"
        />
        <FormControlLabel
          value="end"
          control={
            <Switch
              color="primary"
              checked={showTooltip}
              onChange={handleTooltipChange}
            />
          }
          label="showTooltip"
          labelPlacement="end"
        />
      </Stack>
      <Stack direction="row" sx={{ width: '100%' }}>
        <Box sx={{ flexGrow: 1 }}>
          <SparkLineChart
            data={[1, 4, 2, 5, 7, 2, 4, 6]}
            height={100}
            showHighlight={showHighlight}
            showTooltip={showTooltip}
          />
        </Box>
        <Box sx={{ flexGrow: 1 }}>
          <SparkLineChart
            plotType="bar"
            data={[1, 4, 2, 5, 7, 2, 4, 6]}
            height={100}
            showHighlight={showHighlight}
            showTooltip={showTooltip}
          />
        </Box>
      </Stack>
    </Stack>
  );
}

축 관리

X축 데이터

기본적으로 스파크라인은 x축에 0에서 시작하는 오름차순 정수 시퀀스(0, 1, 2, …)를 사용해요. 이 값들은 툴팁에서 숨겨져 있어요. 데이터 포인트가 균등하게 배치되지 않거나 커스텀 라벨이 필요한 경우 xAxis prop을 사용하세요.

스파크라인은 단일 축을 가지므로 xAxis는 배열이 아니라 축 설정 객체 하나를 받아요.

<SparkLineChart data={[1, 4, 2, 5, 7, 2, 4, 6]} xAxis={{ scaleType, data }} />
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';

export default function CustomAxis() {
  return (
    <Stack direction="row" sx={{ width: '100%' }}>
      <Box sx={{ flexGrow: 1 }}>
        <SparkLineChart
          data={[1, 4, 2, 5, 7, 2, 4, 6]}
          xAxis={{
            scaleType: 'time',
            data: [
              new Date(2022, 5, 1),
              new Date(2022, 5, 2),
              new Date(2022, 5, 5),
              new Date(2022, 5, 6),
              new Date(2022, 5, 7),
              new Date(2022, 5, 8),
              new Date(2022, 5, 11),
              new Date(2022, 5, 12),
            ],
            valueFormatter: (value) => value.toISOString().slice(0, 10),
          }}
          height={100}
          showTooltip
          showHighlight
        />
      </Box>
      <Box sx={{ flexGrow: 1 }}>
        <SparkLineChart
          plotType="bar"
          data={[1, 4, 2, 5, 7, 2, 4, 6]}
          height={100}
          showTooltip
          showHighlight
          xAxis={{
            scaleType: 'band',
            data: [
              new Date(2016, 0, 1),
              new Date(2017, 0, 1),
              new Date(2018, 0, 1),
              new Date(2019, 0, 1),
              new Date(2020, 0, 1),
              new Date(2021, 0, 1),
              new Date(2022, 0, 1),
              new Date(2023, 0, 1),
            ],
            valueFormatter: (value) => value.getFullYear(),
          }}
        />
      </Box>
    </Stack>
  );
}

Y축 범위

yAxis 설정에 min과 max를 설정해 y축 범위를 고정할 수 있어요.

아래 데모는 값 스케일이 다른 두 스파크라인을 보여줘요: 첫 번째 행은 기본 y축을, 두 번째 행은 0에서 100으로 고정된 범위를 사용해요.

import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';

const settings = {
  valueFormatter: (value: number | null) => `${value}%`,
  height: 100,
  showTooltip: true,
  showHighlight: true,
} as const;

const smallValues = [0, 2, 3, 4, 6, 8, 7, 9, 15, 6, 8, 7, 12];
const largeValues = [60, 65, 66, 68, 87, 82, 83, 89, 92, 75, 76, 77, 91];
export default function CustomYAxis() {
  return (
    <Stack sx={{ width: '100%' }}>
      <Typography>Without fixed y-range</Typography>
      <Stack sx={{ width: '100%', mb: 2 }} direction="row" spacing={2}>
        <Box sx={{ flexGrow: 1 }}>
          <SparkLineChart data={smallValues} color="red" {...settings} />
        </Box>
        <Box sx={{ flexGrow: 1 }}>
          <SparkLineChart data={largeValues} {...settings} />
        </Box>
      </Stack>
      <Typography>With y-range fixed to [0, 100]</Typography>
      <Stack sx={{ width: '100%' }} direction="row" spacing={2}>
        <Box sx={{ flexGrow: 1 }}>
          <SparkLineChart
            data={smallValues}
            yAxis={{
              min: 0,
              max: 100,
            }}
            color="red"
            {...settings}
          />
        </Box>
        <Box sx={{ flexGrow: 1 }}>
          <SparkLineChart
            data={largeValues}
            yAxis={{
              min: 0,
              max: 100,
            }}
            {...settings}
          />
        </Box>
      </Stack>
    </Stack>
  );
}

yAxis 설정의 domainLimit 옵션을 사용해 데이터에 상대적으로 y축 범위를 조정할 수 있어요. 자세한 내용은 Axis—Relative axis subdomain을 참고하세요.

아래 데모는 서로 다른 domainLimit 설정으로 같은 데이터(-15에서 92까지의 값)를 사용해요.

import * as React from 'react';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { Theme } from '@mui/material/styles';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';
import type { NumberValue } from '@mui/x-charts/models';

const settings = {
  valueFormatter: (value: number | null) => `${value}%`,
  height: 100,
  showTooltip: true,
  showHighlight: true,
  data: [60, -15, 66, 68, 87, 82, 83, 85, 92, 75, 76, 50, 91],
  margin: { top: 10, bottom: 20, left: 5, right: 5 },
  sx: (theme: Theme) => ({
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: theme.palette.divider,
  }),
};

// 값을 step의 배수에 맞도록 확장
function extend(value: number, step: number) {
  if (value > 0) {
    // 0보다 크면 다음 step으로
    return step * Math.ceil(value / step);
  }
  // 0보다 작으면 이전 step으로
  return step * Math.floor(value / step);
}

const yRange = {
  nice: '-100, 100',
  strict: '-15, 92',
  function: '-20, 100',
};
export default function CustomDomainYAxis() {
  const [domainLimitKey, setDomainLimitKey] = React.useState<
    'nice' | 'strict' | 'function'
  >('nice');

  const domainLimit =
    domainLimitKey === 'function'
      ? (min: NumberValue, max: NumberValue) => ({
          min: extend(min.valueOf(), 10),
          max: extend(max.valueOf(), 10),
        })
      : domainLimitKey;
  return (
    <Box
      sx={{
        width: '100%',
      }}
    >
      <Stack
        direction="row"
        sx={{ alignItems: 'baseline', justifyContent: 'space-between' }}
      >
        <TextField
          select
          value={domainLimitKey}
          onChange={(event) =>
            setDomainLimitKey(event.target.value as 'nice' | 'strict' | 'function')
          }
          label="domain limit"
          sx={{ minWidth: 150, mb: 2 }}
        >
          <MenuItem value="nice">nice</MenuItem>
          <MenuItem value="strict">strict</MenuItem>
          <MenuItem value="function">function</MenuItem>
        </TextField>
        <Typography>y-axis range: {yRange[domainLimitKey]}</Typography>
      </Stack>
      <Stack
        sx={{
          width: '100%',
        }}
        direction="row"
        spacing={2}
      >
        <Box sx={{ flexGrow: 1 }}>
          <SparkLineChart {...settings} yAxis={{ domainLimit }} />
        </Box>
        <Box sx={{ flexGrow: 1 }}>
          <SparkLineChart plotType="bar" {...settings} yAxis={{ domainLimit }} />
        </Box>
      </Stack>
    </Box>
  );
}

색상 커스터마이징

color prop에 색상을 전달해 스파크라인 색상을 설정할 수 있어요.

import Stack from '@mui/material/Stack';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';

const settings = {
  height: 100,
  yAxis: { min: 0, max: 20 },
} as const;

const values = [0, 2, 3, 4, 6, 8, 7, 9, 15, 6, 8, 7, 12];

export default function ColorCustomization() {
  return (
    <Stack sx={{ width: '100%', maxWidth: 300 }}>
      <SparkLineChart data={values} color="green" {...settings} />
    </Stack>
  );
}

color prop은 모드('light' 또는 'dark')를 받는 함수도 받아들여요. 그래서 현재 테마에 맞춰 색상을 바꿀 수 있어요.

아래 데모는 다크 모드에서 흰색 선을, 라이트 모드에서 검은색 선을 사용해요.

import * as React from 'react';
import { createTheme, useTheme, ThemeProvider } from '@mui/material/styles';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Brightness4Icon from '@mui/icons-material/Brightness4';
import Brightness7Icon from '@mui/icons-material/Brightness7';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';
import Paper from '@mui/material/Paper';

const settings = {
  height: 100,
  yAxis: { min: 0, max: 20 },
} as const;

const values = [0, 2, 3, 4, 6, 8, 7, 9, 15, 6, 8, 7, 12];

export default function ColorCustomizationMode() {
  return (
    <DarkModeWrapper>
      <SparkLineChart
        data={values}
        color={(mode) => (mode === 'light' ? 'black' : 'white')}
        {...settings}
      />
    </DarkModeWrapper>
  );
}

function DarkModeWrapper(props: React.PropsWithChildren) {
  const theme = useTheme();
  const [colorMode, setColorMode] = React.useState(theme.palette.mode);

  const newTheme = createTheme({ palette: { mode: colorMode } });
  return (
    <ThemeProvider theme={newTheme}>
      <Stack sx={{ width: '100%', alignItems: 'center' }}>
        <Button
          onClick={() =>
            setColorMode((prev) => (prev === 'light' ? 'dark' : 'light'))
          }
          color="inherit"
          endIcon={colorMode === 'dark' ? <Brightness7Icon /> : <Brightness4Icon />}
        >
          {colorMode} mode
        </Button>
        <Paper sx={{ p: 2, width: '100%', maxWidth: 300 }}>{props.children}</Paper>
      </Stack>
    </ThemeProvider>
  );
}

선 두께

스파크라인 선의 기본 stroke 폭은 2px예요. 클리핑이 활성화되면 차트 가장자리에 그려진 선이 일부 잘릴 수 있어요.

클리핑은 기본적으로 켜져 있어요. clipAreaOffset은 기본값 1로 보이는 클리핑을 줄여요. 클리핑을 끄려면 disableClipping을 true로 설정하세요.

아래 데모는 stroke 폭, disableClipping, clipAreaOffset이 결과에 어떤 영향을 주는지 보여줘요.

import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import { SparkLineChart, SparkLineChartProps } from '@mui/x-charts/SparkLineChart';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import Slider from '@mui/material/Slider';

const values = [8, 7, 9, 0, 0, 5, 20, 20, 7];

const settings = {
  data: values,
  height: 100,
  showHighlight: true,
  showTooltip: true,
} satisfies Partial<SparkLineChartProps>;

export default function SparklineLineWidth() {
  const [strokeWidth, setStrokeWidth] = React.useState<number>(2);
  const [disableClipping, setDisableClipping] = React.useState(false);
  const [clipAreaOffset, setClipAreaOffset] = React.useState<number>(1);

  return (
    <Stack direction="column" sx={{ gap: 1, width: '100%' }}>
      <Stack direction="row">
        <FormControlLabel
          checked={disableClipping}
          control={
            <Checkbox
              onChange={(event) => setDisableClipping(event.target.checked)}
            />
          }
          label="Disable Clipping"
          labelPlacement="end"
        />
        <FormControlLabel
          value={strokeWidth}
          control={
            <Slider
              aria-label="Stroke Width"
              valueLabelDisplay="auto"
              step={1}
              marks
              min={1}
              max={5}
              onChange={(event, value) => setStrokeWidth(value)}
            />
          }
          label="Stroke Width"
          labelPlacement="top"
        />

        <FormControlLabel
          value={clipAreaOffset}
          disabled={disableClipping}
          control={
            <Slider
              aria-label="Clip Area Offset"
              valueLabelDisplay="auto"
              disabled={disableClipping}
              step={1}
              marks
              min={0}
              max={5}
              onChange={(event, value) => setClipAreaOffset(value)}
            />
          }
          label="Clip Area Offset"
          labelPlacement="top"
        />
      </Stack>
      <Box sx={{ flexGrow: 1 }}>
        <SparkLineChart
          {...settings}
          yAxis={{ min: 0 }}
          disableClipping={disableClipping}
          clipAreaOffset={{
            top: clipAreaOffset,
            bottom: clipAreaOffset,
            left: clipAreaOffset,
            right: clipAreaOffset,
          }}
          slotProps={{
            line: { strokeWidth },
          }}
        />
      </Box>
    </Stack>
  );
}

더 알아보기 (Learn more)