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

Charts - 영역(Area) 차트 데모

원문 보기 위키 갱신

Charts - 영역(Area) 차트 데모 (Charts - Areas demos)

이 페이지에서는 영역 차트(area chart)를 사용한 데모들을 모아뒀어요.

출처: MUI X documentation

본문

SimpleAreaChart

import { LineChart, lineClasses } from '@mui/x-charts/LineChart';
import Box from '@mui/material/Box';

const margin = { right: 24 };
const uData = [4000, 3000, 2000, 2780, 1890, 2390, 3490];
const xLabels = [
  'Page A',
  'Page B',
  'Page C',
  'Page D',
  'Page E',
  'Page F',
  'Page G',
];

export default function SimpleAreaChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <LineChart
        series={[{ data: uData, label: 'uv', area: true }]}
        xAxis={[{ scaleType: 'point', data: xLabels, height: 28 }]}
        sx={{
          [`& .${lineClasses.line}`]: {
            display: 'none',
          },
        }}
        margin={margin}
      />
    </Box>
  );
}

StackedAreaChart

import { LineChart, lineClasses } from '@mui/x-charts/LineChart';
import Box from '@mui/material/Box';

const margin = { right: 24 };
const uData = [4000, 3000, 2000, 2780, 1890, 2390, 3490];
const pData = [2400, 1398, 9800, 3908, 4800, 3800, 4300];
const amtData = [2400, 2210, 0, 2000, 2181, 2500, 2100];
const xLabels = [
  'Page A',
  'Page B',
  'Page C',
  'Page D',
  'Page E',
  'Page F',
  'Page G',
];

export default function StackedAreaChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <LineChart
        series={[
          { data: uData, label: 'uv', area: true, stack: 'total' },
          { data: pData, label: 'pv', area: true, stack: 'total' },
          {
            data: amtData,
            label: 'amt',
            area: true,
            stack: 'total',
          },
        ]}
        xAxis={[{ scaleType: 'point', data: xLabels, height: 28 }]}
        yAxis={[{ width: 50 }]}
        sx={{
          [`& .${lineClasses.line}`]: {
            display: 'none',
          },
        }}
        margin={margin}
      />
    </Box>
  );
}

TinyAreaChart

import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { AreaPlot } from '@mui/x-charts/LineChart';

const uData = [4000, 3000, 2000, 2780, 1890, 2390, 3490];
const xLabels = [
  'Page A',
  'Page B',
  'Page C',
  'Page D',
  'Page E',
  'Page F',
  'Page G',
];

export default function TinyAreaChart() {
  return (
    <ChartsContainer
      width={500}
      height={300}
      series={[
        {
          data: uData,
          type: 'line',
          label: 'uv',
          area: true,
          stack: 'total',
        },
      ]}
      xAxis={[{ scaleType: 'point', data: xLabels }]}
    >
      <AreaPlot />
    </ChartsContainer>
  );
}

PercentAreaChart

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

const time = [
  new Date(2015, 1, 0),
  new Date(2015, 2, 0),
  new Date(2015, 3, 0),
  new Date(2015, 4, 0),
  new Date(2015, 5, 0),
  new Date(2015, 6, 0),
  new Date(2015, 7, 0),
];
const a = [4000, 3000, 2000, 2780, 1890, 2390, 3490];
const b = [2400, 1398, 9800, 3908, 4800, 3800, 4300];
const c = [2400, 2210, 2290, 2000, 2181, 2500, 2100];

const getPercents = (array: number[]) =>
  array.map((v, index) => (100 * v) / (a[index] + b[index] + c[index]));

export default function PercentAreaChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <LineChart
        series={[
          {
            data: getPercents(a),
            type: 'line',
            label: 'a',
            area: true,
            stack: 'total',
          },
          {
            data: getPercents(b),
            type: 'line',
            label: 'b',
            area: true,
            stack: 'total',
          },
          {
            data: getPercents(c),
            type: 'line',
            label: 'c',
            area: true,
            stack: 'total',
          },
        ]}
        xAxis={[
          {
            scaleType: 'time',
            data: time,
            min: time[0].getTime(),
            max: time[time.length - 1].getTime(),
            height: 28,
          },
        ]}
      />
    </Box>
  );
}

AreaChartConnectNulls

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

const data = [4000, 3000, 2000, null, 1890, 2390, 3490];
const xData = ['Page A', 'Page B', 'Page C', 'Page D', 'Page E', 'Page F', 'Page G'];
const margin = { right: 24 };

export default function AreaChartConnectNulls() {
  return (
    <Stack sx={{ width: '100%', height: 400 }}>
      <LineChart
        xAxis={[{ data: xData, scaleType: 'point', height: 28 }]}
        series={[{ data, area: true }]}
        margin={margin}
      />
      <LineChart
        xAxis={[{ data: xData, scaleType: 'point', height: 28 }]}
        series={[{ data, area: true, connectNulls: true }]}
        margin={margin}
      />
    </Stack>
  );
}

AreaChartFillByValue

영역 안에 여러 색상을 표시하려면 영역을 채우는 그라디언트를 지정하면 돼요 (같은 방법을 다른 SVG 컴포넌트에도 적용할 수 있어요).

이 그라디언트 정의를 <LineChart />의 자식으로 전달하고, sx로 영역의 fill 속성을 재정의할 수 있어요. 이때 <linearGradient />와 <stop /> SVG 요소를 사용해야 해요.

먼저 SVG의 전체 높이를 구해야 해요. useDrawingArea() 훅으로 구할 수 있어요. <linearGradient />를 SVG 컨테이너의 위쪽에서 아래쪽으로 가는 벡터로 정의하는 데 유용해요.

그런 다음 그라디언트가 한 색에서 다른 색으로 전환되는 위치를 정의하려면, useYScale() 훅으로 값 0의 y 좌표를 구하면 돼요.

:::info <stop />의 offset은 그라디언트 벡터의 비율이에요. 그래서 좌표를 SVG 높이로 나눠야 해요. :::

import { ScaleLinear } from '@mui/x-charts-vendor/d3-scale';
import { green, red } from '@mui/material/colors';
import Stack from '@mui/material/Stack';
import { useYScale, useDrawingArea } from '@mui/x-charts/hooks';
import { LineChart, lineClasses } from '@mui/x-charts/LineChart';

const margin = { right: 24, bottom: 0 };
const data = [4000, 3000, -1000, 500, -2100, -250, 3490];
const xData = ['Page A', 'Page B', 'Page C', 'Page D', 'Page E', 'Page F', 'Page G'];

type ColorSwitchProps = {
  threshold: number;
  color1: string;
  color2: string;
  id: string;
};

function ColorSwitch({ threshold, color1, color2, id }: ColorSwitchProps) {
  const { top, height, bottom } = useDrawingArea();
  const svgHeight = top + bottom + height;

  const scale = useYScale() as ScaleLinear<number, number>; // You can provide the axis Id if you have multiple ones
  const y0 = scale(threshold); // The coordinate of the origin
  const off = y0 !== undefined ? y0 / svgHeight : 0;

  return (
    <defs>
      <linearGradient
        id={id}
        x1="0"
        x2="0"
        y1="0"
        y2={`${svgHeight}px`}
        gradientUnits="userSpaceOnUse" // Use the SVG coordinate instead of the component ones.
      >
        <stop offset={off} stopColor={color1} stopOpacity={1} />
        <stop offset={off} stopColor={color2} stopOpacity={1} />
      </linearGradient>
    </defs>
  );
}

export default function AreaChartFillByValue() {
  return (
    <Stack direction="column" spacing={1} sx={{ width: '100%' }}>
      <LineChart
        xAxis={[{ data: xData, scaleType: 'point' }]}
        yAxis={[{ min: -3000, max: 4000, width: 50 }]}
        series={[{ data, area: true }]}
        height={200}
        margin={margin}
        sx={{
          [`& .${lineClasses.area}`]: {
            fill: 'url(#switch-color-id-1)',
            filter: 'none', // Remove the default filter.
          },
        }}
      >
        <ColorSwitch
          color1="#11B678" // green
          color2="#FF3143" // red
          threshold={0}
          id="switch-color-id-1"
        />
        <rect x={0} y={0} width={5} height="100%" fill="url(#switch-color-id-1)" />
      </LineChart>
      <LineChart
        xAxis={[{ data: xData, scaleType: 'point' }]}
        yAxis={[{ min: -3000, max: 4000, width: 50 }]}
        series={[{ data, area: true }]}
        height={200}
        margin={margin}
        sx={{
          [`& .${lineClasses.area}`]: {
            fill: 'url(#switch-color-id-2)',
            filter: 'none', // Remove the default filter.
          },
        }}
      >
        <ColorPalette id="switch-color-id-2" />

        <rect x={0} y={0} width={5} height="100%" fill="url(#switch-color-id-2)" />
      </LineChart>
    </Stack>
  );
}

function ColorPalette({ id }: { id: string }) {
  const { top, height, bottom } = useDrawingArea();
  const svgHeight = top + bottom + height;

  const scale = useYScale() as ScaleLinear<number, number>; // You can provide the axis Id if you have multiple ones

  return (
    <defs>
      <linearGradient
        id={id}
        x1="0"
        x2="0"
        y1="0"
        y2={`${svgHeight}px`}
        gradientUnits="userSpaceOnUse" // Use the SVG coordinate instead of the component ones.
      >
        <stop
          offset={scale(5000) / svgHeight}
          stopColor={green[400]}
          stopOpacity={1}
        />
        <stop
          offset={scale(4000) / svgHeight}
          stopColor={green[400]}
          stopOpacity={1}
        />
        <stop
          offset={scale(4000) / svgHeight}
          stopColor={green[300]}
          stopOpacity={1}
        />
        <stop
          offset={scale(3000) / svgHeight}
          stopColor={green[300]}
          stopOpacity={1}
        />
        <stop
          offset={scale(3000) / svgHeight}
          stopColor={green[200]}
          stopOpacity={1}
        />
        <stop
          offset={scale(2000) / svgHeight}
          stopColor={green[200]}
          stopOpacity={1}
        />
        <stop
          offset={scale(2000) / svgHeight}
          stopColor={green[100]}
          stopOpacity={1}
        />
        <stop
          offset={scale(1000) / svgHeight}
          stopColor={green[100]}
          stopOpacity={1}
        />
        <stop
          offset={scale(1000) / svgHeight}
          stopColor={green[50]}
          stopOpacity={1}
        />
        <stop offset={scale(0) / svgHeight} stopColor={green[50]} stopOpacity={1} />
        <stop offset={scale(0) / svgHeight} stopColor={red[100]} stopOpacity={1} />
        <stop
          offset={scale(-1000) / svgHeight}
          stopColor={red[100]}
          stopOpacity={1}
        />
        <stop
          offset={scale(-1000) / svgHeight}
          stopColor={red[200]}
          stopOpacity={1}
        />
        <stop
          offset={scale(-2000) / svgHeight}
          stopColor={red[200]}
          stopOpacity={1}
        />
        <stop
          offset={scale(-3000) / svgHeight}
          stopColor={red[300]}
          stopOpacity={1}
        />
      </linearGradient>
    </defs>
  );
}

더 알아보기 (Learn more)