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

Charts - 막대 차트 데모

원문 보기 위키 갱신

막대 차트 데모와 예시를 둘러봐요.

출처: MUI X documentation

본문

TinyBarChart

import { ChartsContainer } from '@mui/x-charts/ChartsContainer';
import { BarPlot } from '@mui/x-charts/BarChart';

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 TinyBarChart() {
  return (
    <ChartsContainer
      width={500}
      height={300}
      series={[{ data: uData, label: 'uv', type: 'bar' }]}
      xAxis={[{ scaleType: 'band', data: xLabels }]}
    >
      <BarPlot />
    </ChartsContainer>
  );
}

SimpleBarChart

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

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 SimpleBarChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <BarChart
        series={[
          { data: pData, label: 'pv', id: 'pvId' },
          { data: uData, label: 'uv', id: 'uvId' },
        ]}
        xAxis={[{ data: xLabels, height: 28 }]}
        yAxis={[{ width: 50 }]}
      />
    </Box>
  );
}

StackedBarChart

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

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 StackedBarChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <BarChart
        series={[
          { data: pData, label: 'pv', id: 'pvId', stack: 'total' },
          { data: uData, label: 'uv', id: 'uvId', stack: 'total' },
        ]}
        xAxis={[{ data: xLabels, height: 28 }]}
        yAxis={[{ width: 50 }]}
      />
    </Box>
  );
}

MixedBarChart

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

const uData = [4000, 3000, 2000, 2780, 1890, 2390, 3490];
const pData = [2400, 1398, 9800, 3908, 4800, 3800, 4300];
const amtData = [2400, 2210, 2290, 2000, 2181, 2500, 2100];

const xLabels = [
  'Page A',
  'Page B',
  'Page C',
  'Page D',
  'Page E',
  'Page F',
  'Page G',
];

export default function MixedBarChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <BarChart
        series={[
          { data: pData, label: 'pv', stack: 'stack1' },
          { data: amtData, label: 'amt' },
          { data: uData, label: 'uv', stack: 'stack1' },
        ]}
        xAxis={[{ data: xLabels, height: 28 }]}
        yAxis={[{ width: 50 }]}
      />
    </Box>
  );
}

PositiveAndNegativeBarChart

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

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 PositiveAndNegativeBarChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <BarChart
        series={[
          { data: pData, label: 'pv' },
          { data: uData, label: 'uv' },
        ]}
        xAxis={[{ data: xLabels, height: 28 }]}
        yAxis={[{ width: 60, max: 10000 }]}
      />
    </Box>
  );
}

BarChartStackedBySign

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

const pData = [2400, 1398, -9800, 3908, 4800, -3800, 4300];
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 BarChartStackedBySign() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <BarChart
        series={[
          { data: pData, label: 'pv', id: 'pvId', stack: 'stack1' },
          { data: uData, label: 'uv', id: 'uvId', stack: 'stack1' },
        ]}
        xAxis={[{ data: xLabels, height: 28 }]}
        yAxis={[{ width: 60 }]}
      />
    </Box>
  );
}

BiaxialBarChart

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

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 BiaxialBarChart() {
  return (
    <Box sx={{ width: '100%', height: 300 }}>
      <BarChart
        series={[
          {
            data: pData,
            label: 'pv',
            id: 'pvId',

            yAxisId: 'leftAxisId',
          },
          {
            data: uData,
            label: 'uv',
            id: 'uvId',
            yAxisId: 'rightAxisId',
          },
        ]}
        xAxis={[{ data: xLabels, height: 28 }]}
        yAxis={[
          { id: 'leftAxisId', width: 50 },
          { id: 'rightAxisId', position: 'right' },
        ]}
      />
    </Box>
  );
}

인구 피라미드 (Population pyramid)

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

const ageGroups = [
  '100+ yrs',
  '95-99 yrs',
  '90-94 yrs',
  '85-89 yrs',
  '80-84 yrs',
  '75-79 yrs',
  '70-74 yrs',
  '65-69 yrs',
  '60-64 yrs',
  '55-59 yrs',
  '50-54 yrs',
  '45-49 yrs',
  '40-44 yrs',
  '35-39 yrs',
  '30-34 yrs',
  '25-29 yrs',
  '20-24 yrs',
  '15-19 yrs',
  '10-14 yrs',
  '5-9 yrs',
  '0-4 yrs',
];

const male = [
  1139, 8291, 50323, 201240, 476263, 696606, 1012668, 1478069, 2042614, 2068112,
  2258061, 2061862, 2067075, 1808706, 1796779, 1933726, 1620461, 1183580, 1189663,
  1097221, 766227,
];

const female = [
  5770, 36739, 168603, 445118, 762492, 899933, 1152098, 1585781, 2105499, 2045845,
  2231491, 2000130, 1967944, 1673805, 1593655, 1695058, 1484776, 1104293, 1122176,
  1044863, 727814,
];

const numberFormatter = Intl.NumberFormat('en-US', {
  useGrouping: true,
});
const numberWithSuffixFormatter = new Intl.NumberFormat('en-US', {
  notation: 'compact',
});
const valueFormatter = (population: number | null) =>
  population ? `${numberFormatter.format(Math.abs(population))}` : '';

export default function PopulationPyramidBarChart() {
  return (
    <Stack sx={{ width: '100%', height: 550, mx: [0, 4] }}>
      <Typography
        variant="h6"
        component="span"
        data-hide-overview
        sx={{ textAlign: 'center' }}
      >
        South Korea Population Pyramid - 2022
      </Typography>
      <BarChart
        layout="horizontal"
        margin={{ right: 0, left: 0 }}
        series={[
          {
            data: male.map((population) => -population),
            label: 'Male',
            type: 'bar',
            valueFormatter,
            stack: 'stack',
          },
          {
            data: female,
            label: 'Female',
            type: 'bar',
            valueFormatter,
            stack: 'stack',
          },
        ]}
        yAxis={[
          {
            data: ageGroups,
            width: 60,
            tickLabelInterval: (value, index) => index % 2 === 0,
            disableLine: true,
            disableTicks: true,
          },
        ]}
        xAxis={[
          {
            valueFormatter: (population: number) =>
              numberWithSuffixFormatter.format(Math.abs(population)),
            disableLine: true,
            disableTicks: true,
            domainLimit(min, max) {
              const extremum = Math.max(-min.valueOf(), max.valueOf());
              const roundedExtremum = Math.ceil(extremum / 100_000) * 100_000;
              return { min: -roundedExtremum, max: roundedExtremum };
            },
          },
        ]}
        grid={{ vertical: true }}
      />
      <Typography variant="caption">Source: KOSIS</Typography>
    </Stack>
  );
}

워터폴 차트 (Waterfall chart)

다음 데모는 범위 막대 차트(range bar chart)로 만든 워터폴 차트를 보여 줘요.

import * as React from 'react';
import { useTheme } from '@mui/system';
import { rainbowSurgePalette } from '@mui/x-charts/colorPalettes';
import { BarChartPremium } from '@mui/x-charts-premium/BarChartPremium';

const dollarFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  compactDisplay: 'short',
  currency: 'USD',
  maximumFractionDigits: 0,
});

export default function WaterfallChart() {
  const theme = useTheme();
  const palette = rainbowSurgePalette(theme.palette.mode);
  const blue = palette[0];
  const red = palette[2];
  const green = palette[4];

  return (
    <BarChartPremium
      xAxis={[
        {
          data: [
            'Revenue',
            'Product\nSales',
            'Services\nRevenue',
            'Cost of\nGoods Sold',
            'Marketing\nExpenses',
            'Operating\nExpenses',
            'Tax',
            'Net Profit',
          ],
        },
      ]}
      yAxis={[
        {
          width: 72,
          valueFormatter: (value: number) => dollarFormatter.format(value),
        },
      ]}
      series={[
        {
          type: 'rangeBar',
          data: [
            [0, 500_000],
            [500_000, 650_000],
            [650_000, 730_000],
            [730_000, 530_000],
            [530_000, 455_000],
            [455_000, 335_000],
            [335_000, 280_000],
            [0, 280_000],
          ],
          valueFormatter: (value) =>
            value === null ? null : dollarFormatter.format(value[1] - value[0]),
          colorGetter: (data) => {
            const value = data?.value;

            if (value == null || value[0] === 0) {
              return blue;
            }

            return value[1] - value[0] >= 0 ? green : red;
          },
        },
      ]}
      height={300}
    />
  );
}

히스토그램 (Histogram)

히스토그램은 숫자 변수의 분포를 보여 줘요. Bar Chart에는 내장 히스토그램이 없으므로, 먼저 데이터 집합을 동일한 폭의 빈(bin)으로 나눈 다음(데모에는 시작점으로 쓸 computeBins 헬퍼가 포함되어 있어요) 그 빈도를 그리면 돼요.

categoryGapRatio와 barGapRatio를 0으로 설정한 band x축을 사용하면 인접한 막대가 서로 붙어서 히스토그램답게 읽힐 수 있어요. 막대 사이에 생기는 아티팩트를 피하려면 막대의 shape-rendering을 'crispEdges'로 설정하세요.

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

type Bin = { x0: number; x1: number; count: number };

/**
 * Split `values` into `binCount` equal-width bins.
 * Each bin reports its [x0, x1) range and how many values fall into it.
 *
 * Feed the returned array to a BarChart whose x-axis uses
 * `scaleType: 'band'` and zero gaps, so adjacent bars touch like a histogram.
 */
function computeBins(values: number[], binCount: number): Bin[] {
  const min = Math.min(...values);
  const max = Math.max(...values);
  const step = (max - min) / binCount;
  const bins: Bin[] = Array.from({ length: binCount }, (_, i) => ({
    x0: min + i * step,
    x1: min + (i + 1) * step,
    count: 0,
  }));
  for (const value of values) {
    const index = Math.min(Math.floor((value - min) / step), binCount - 1);
    bins[index].count += 1;
  }
  return bins;
}

// ---------------------------------------------------------------------------
// Replace this section with your own data source — an array of numbers from
// your API, file, or calculation. Anything `computeBins` can iterate over.
//
// The demo synthesizes 1,000 samples from a normal distribution (μ=50, σ=12)
// with a seeded random generator so the chart is deterministic across SSR
// and client hydration.
function createSeededRandom(seed: number) {
  let state = seed;
  return () => {
    state = (state * 1664525 + 1013904223) % 4294967296;
    return state / 4294967296;
  };
}

const random = createSeededRandom(42);
const data = Array.from({ length: 1000 }, () => {
  const u = 1 - random();
  const v = random();
  return 50 + 12 * Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
});
// ---------------------------------------------------------------------------

export default function HistogramBarChart() {
  const [binCount, setBinCount] = React.useState(20);

  const dataset = React.useMemo(
    () =>
      computeBins(data, binCount).map((bin) => ({
        bin: `${bin.x0.toFixed(1)}–${bin.x1.toFixed(1)}`,
        count: bin.count,
      })),
    [binCount],
  );

  return (
    <Box sx={{ width: '100%' }}>
      <BarChart
        dataset={dataset}
        xAxis={[
          {
            dataKey: 'bin',
            scaleType: 'band',
            categoryGapRatio: 0,
            barGapRatio: 0,
            tickLabelStyle: { fontSize: 10 },
          },
        ]}
        yAxis={[{ label: 'count', width: 50 }]}
        series={[{ dataKey: 'count', label: 'Frequency' }]}
        height={300}
        sx={{ [`& .${barClasses.root}`]: { shapeRendering: 'crispEdges' } }}
      />
      <Typography id="histogram-bin-count" gutterBottom>
        Bin count
      </Typography>
      <Slider
        value={binCount}
        onChange={(event, value) => setBinCount(value as number)}
        valueLabelDisplay="auto"
        min={5}
        max={60}
        aria-labelledby="histogram-bin-count"
      />
    </Box>
  );
}

더 알아보기

더 자세한 내용은 MUI X Charts 문서를 참고하세요.