본문으로 건너뛰기Skip to content
예제 첫화면Examples home

필터에 따라 바뀌는 차트A chart that follows the filter

createChart의 source를 'visible'로 두면 지금 보이는 행만 차트가 돼요. 필터 행에 지역을 입력하면 차트가 바로 따라가요.With source 'visible' in createChart the chart shows only the rows currently visible. Type a region in the filter row and the chart follows at once.

활용Intermediate
직접 써 보기Live preview필터에 따라 바뀌는 차트A chart that follows the filter

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="종류" id="chartType">
      <option value="column" selected>막대</option>
      <option value="bar">가로 막대</option>
      <option value="line">꺾은선</option>
      <option value="area">영역</option>
      <option value="pie">원</option>
    </select>
    <button type="button" id="limitThree">3행만</button>
  </div>
  <div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('chartType').addEventListener('change', (event) => actions.chartType(api, event.target.value));
document.getElementById('limitThree').addEventListener('click', () => actions.limitThree(api));
example.js
const rows = [
  { id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
  { id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
  { id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
  { id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
  { id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
  { id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
  { id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
  { id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns = [
  { id: 'region', title: '지역', width: 110 },
  { id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
  { id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
  { id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
  { id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
  { id: 'note', title: '메모', editable: true, width: 110 },
];
const palette = ['#4e79a7', '#f28e2b', '#59a14f', '#e15759', '#b07aa1'];
const colorOf = (i) => palette[i % palette.length] ?? '#4e79a7';
const NS = 'http://www.w3.org/2000/svg';
function el(name, attrs, text) {
  const node = document.createElementNS(NS, name);
  for (const [k, v] of Object.entries(attrs))
    node.setAttribute(k, v);
  if (text !== undefined)
    node.textContent = text;
  return node;
}
// An adapter must draw every ChartType: column (vertical bars), bar (HORIZONTAL bars), line, area, pie.
// 'bar' is not a second name for column; when a type falls through to column, the popup's type select looks broken.
const svgAdapter = {
  create(ctx) {
    const { container, type } = ctx;
    const ink = ctx.theme === 'dark' ? '#c9cdd4' : '#555';
    const grid = ctx.theme === 'dark' ? '#3a3f48' : '#ddd';
    const svg = el('svg', { width: '100%', height: '100%', style: 'display:block;direction:ltr' }); // 1 unit = 1 px: the viewBox follows the box, so the text stays readable on a phone
    container.append(svg);
    const short = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
    const text = (x, y, s, a = {}, max = 99) => {
      const t = el('text', { x: String(x), y: String(y), 'font-size': '9', fill: ink, ...a }, short(s, max));
      t.append(el('title', {}, s)); // the full label on hover
      svg.append(t);
    };
    const legend = (names, H) => names.forEach((n, i) => {
      svg.append(el('rect', {
        x: String(8 + i * 78),
        y: String(H - 9),
        width: '8',
        height: '8',
        fill: colorOf(i),
      }));
      text(20 + i * 78, H - 1, n, {}, 10);
    });
    const nice = (max) => {
      const step = 10 ** Math.floor(Math.log10(max));
      return Math.ceil(max / step) * step;
    };
    let last = ctx.getData();
    const draw = (data) => {
      last = data;
      const W = Math.max(240, container.clientWidth || 400);
      const H = Math.max(150, container.clientHeight || 200);
      svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
      svg.replaceChildren();
      const n = Math.max(1, data.categories.length);
      const m = data.series.length || 1;
      if (type === 'pie') {
        const vals = (data.series[0]?.values ?? []).map((v) => Math.max(0, v ?? 0));
        const sum = vals.reduce((a, b) => a + b, 0) || 1;
        let angle = -Math.PI / 2;
        const r = Math.min(80, (H - 24) / 2, W / 4);
        const cx = r + 12;
        const cy = H / 2;
        const p = (a) => `${cx + r * Math.cos(a)} ${cy + r * Math.sin(a)}`;
        vals.forEach((v, i) => {
          const next = angle + (v / sum) * Math.PI * 2;
          const slice = vals.filter((x) => x > 0).length === 1
            ? el('circle', { cx: String(cx), cy: String(cy), r: String(r), fill: colorOf(i) })
            : el('path', {
              d: `M${cx} ${cy} L${p(angle)} A${r} ${r} 0 ${next - angle > Math.PI ? 1 : 0} 1 ${p(next)} Z`,
              fill: colorOf(i),
            });
          if (v > 0)
            svg.append(slice);
          svg.append(el('rect', {
            x: String(2 * r + 30),
            y: String(14 + i * 14),
            width: '8',
            height: '8',
            fill: colorOf(i),
          }));
          text(2 * r + 42, 21 + i * 14, `${data.categories[i] ?? ''} ${v}`, {}, 18);
          angle = next;
        });
        return;
      }
      const all = data.series.flatMap((s) => s.values.map((v) => v ?? 0));
      const top = nice(Math.max(1, ...all));
      const horizontal = type === 'bar';
      // plot box: left room for labels (wide on a horizontal chart), bottom room for labels and legend
      const x0 = horizontal ? 62 : 34;
      const x1 = W - 8;
      const y0 = 8;
      const y1 = H - 32;
      const val = (v) => horizontal ? x0 + (v / top) * (x1 - x0) : y1 - (v / top) * (y1 - y0);
      for (let k = 0; k <= 4; k++) {
        const v = (top / 4) * k;
        if (horizontal) {
          svg.append(el('line', {
            x1: String(val(v)),
            y1: String(y0),
            x2: String(val(v)),
            y2: String(y1),
            stroke: grid,
          }));
          text(val(v), y1 + 11, String(v), { 'text-anchor': 'middle' });
        }
        else {
          svg.append(el('line', {
            x1: String(x0),
            y1: String(val(v)),
            x2: String(x1),
            y2: String(val(v)),
            stroke: grid,
          }));
          text(x0 - 4, val(v) + 3, String(v), { 'text-anchor': 'end' });
        }
      }
      const cell = (horizontal ? y1 - y0 : x1 - x0) / n; // room of one category
      const mid = (i) => (horizontal ? y0 : x0) + cell * i + cell / 2;
      data.categories.forEach((c, i) => horizontal
        ? text(x0 - 5, mid(i) + 3, c, { 'text-anchor': 'end' }, 9)
        : text(mid(i), y1 + 11, c, { 'text-anchor': 'middle' }, Math.max(3, Math.floor(cell / 5))));
      data.series.forEach((s, si) => {
        const color = colorOf(si);
        const pts = s.values.map((v, i) => ({ c: mid(i), v: val(v ?? 0), n: v ?? 0 }));
        if (type === 'line' || type === 'area') {
          const line = pts.map((q) => `${q.c},${q.v}`).join(' ');
          if (type === 'area' && pts.length > 0)
            svg.append(el('polygon', {
              points: `${pts[0]?.c},${y1} ${line} ${pts[pts.length - 1]?.c},${y1}`,
              fill: color,
              'fill-opacity': '0.3',
            }));
          svg.append(el('polyline', { points: line, fill: 'none', stroke: color, 'stroke-width': '2' }));
          for (const q of pts)
            svg.append(el('circle', { cx: String(q.c), cy: String(q.v), r: '2.5', fill: color }));
          return;
        }
        const bw = (cell * 0.8) / m; // bars of one category sit side by side
        pts.forEach((q, i) => {
          const at = mid(i) - (cell * 0.8) / 2 + si * bw;
          const rect = horizontal
            ? { x: x0, y: at, width: q.v - x0, height: bw * 0.92 }
            : { x: at, y: q.v, width: bw * 0.92, height: y1 - q.v };
          const r = el('rect', {
            ...Object.fromEntries(Object.entries(rect).map(([k, v]) => [k, String(v)])),
            fill: color,
            'data-i': String(i),
          });
          r.append(el('title', {}, `${data.categories[i] ?? ''} · ${s.name}: ${q.n}`));
          svg.append(r);
        });
      });
      legend(data.series.map((s) => s.name), H);
    };
    draw(last);
    return { update: draw, destroy: () => svg.remove(), resize: () => draw(last) };
  },
};
export const options = {
  rowKey: 'id',
  columns,
  rows,
  cellSelection: 'multiple',
  selection: 'multiple',
  ariaLabel: '지역별 분기 매출',
  chartAdapter: svgAdapter,
  filterRow: true,
};
let host = null;
let chart = null;
function ensureHost() {
  if (host !== null)
    return host;
  const first = document.getElementById('grid');
  host = document.createElement('div');
  host.id = 'chart-host';
  host.style.cssText = 'height:220px;margin-top:10px';
  if (first !== null)
    first.after(host);
  else
    document.body.append(host);
  return host;
}
function cleanup() {
  chart?.destroy();
  chart = null;
}
let currentType = 'column';
function rebuild(api, limit) {
  cleanup();
  chart = api.createChart(ensureHost(), {
    source: 'visible',
    type: currentType,
    ...(limit === undefined ? {} : { limit }),
  });
}
export function setup(api, log) {
  const offCreated = api.on('chartCreated', ({ categories }) => {
    log({
      ko: `차트를 만들었어요. 분류 ${categories}개`,
      en: `Chart created with ${categories} categories`,
    });
  });
  const offUpdated = api.on('chartUpdated', ({ categories }) => {
    log({
      ko: `차트를 갱신했어요. 분류 ${categories}개`,
      en: `Chart updated with ${categories} categories`,
    });
  });
  rebuild(api);
  log({
    ko: '필터 행에 지역 이름을 입력하면 차트가 따라가요.',
    en: 'Type a region name in the filter row and the chart follows.',
  });
  return () => {
    offCreated();
    offUpdated();
    cleanup();
    host?.remove();
    host = null;
  };
}
export const actions = {
  chartType: (api, value) => {
    currentType = value ?? 'column';
    rebuild(api);
  },
  limitThree: (api) => {
    rebuild(api, 3);
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="Type" id="chartType">
      <option value="column" selected>Column</option>
      <option value="bar">Bar</option>
      <option value="line">Line</option>
      <option value="area">Area</option>
      <option value="pie">Pie</option>
    </select>
    <button type="button" id="limitThree">First 3 rows</button>
  </div>
  <div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('chartType').addEventListener('change', (event) => actions.chartType(api, event.target.value));
document.getElementById('limitThree').addEventListener('click', () => actions.limitThree(api));
example.js
const rows = [
  { id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
  { id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
  { id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
  { id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
  { id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
  { id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
  { id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
  { id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns = [
  { id: 'region', title: 'Region', width: 110 },
  { id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
  { id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
  { id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
  { id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
  { id: 'note', title: 'Note', editable: true, width: 110 },
];
const palette = ['#4e79a7', '#f28e2b', '#59a14f', '#e15759', '#b07aa1'];
const colorOf = (i) => palette[i % palette.length] ?? '#4e79a7';
const NS = 'http://www.w3.org/2000/svg';
function el(name, attrs, text) {
  const node = document.createElementNS(NS, name);
  for (const [k, v] of Object.entries(attrs))
    node.setAttribute(k, v);
  if (text !== undefined)
    node.textContent = text;
  return node;
}
// An adapter must draw every ChartType: column (vertical bars), bar (HORIZONTAL bars), line, area, pie.
// 'bar' is not a second name for column; when a type falls through to column, the popup's type select looks broken.
const svgAdapter = {
  create(ctx) {
    const { container, type } = ctx;
    const ink = ctx.theme === 'dark' ? '#c9cdd4' : '#555';
    const grid = ctx.theme === 'dark' ? '#3a3f48' : '#ddd';
    const svg = el('svg', { width: '100%', height: '100%', style: 'display:block;direction:ltr' }); // 1 unit = 1 px: the viewBox follows the box, so the text stays readable on a phone
    container.append(svg);
    const short = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
    const text = (x, y, s, a = {}, max = 99) => {
      const t = el('text', { x: String(x), y: String(y), 'font-size': '9', fill: ink, ...a }, short(s, max));
      t.append(el('title', {}, s)); // the full label on hover
      svg.append(t);
    };
    const legend = (names, H) => names.forEach((n, i) => {
      svg.append(el('rect', {
        x: String(8 + i * 78),
        y: String(H - 9),
        width: '8',
        height: '8',
        fill: colorOf(i),
      }));
      text(20 + i * 78, H - 1, n, {}, 10);
    });
    const nice = (max) => {
      const step = 10 ** Math.floor(Math.log10(max));
      return Math.ceil(max / step) * step;
    };
    let last = ctx.getData();
    const draw = (data) => {
      last = data;
      const W = Math.max(240, container.clientWidth || 400);
      const H = Math.max(150, container.clientHeight || 200);
      svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
      svg.replaceChildren();
      const n = Math.max(1, data.categories.length);
      const m = data.series.length || 1;
      if (type === 'pie') {
        const vals = (data.series[0]?.values ?? []).map((v) => Math.max(0, v ?? 0));
        const sum = vals.reduce((a, b) => a + b, 0) || 1;
        let angle = -Math.PI / 2;
        const r = Math.min(80, (H - 24) / 2, W / 4);
        const cx = r + 12;
        const cy = H / 2;
        const p = (a) => `${cx + r * Math.cos(a)} ${cy + r * Math.sin(a)}`;
        vals.forEach((v, i) => {
          const next = angle + (v / sum) * Math.PI * 2;
          const slice = vals.filter((x) => x > 0).length === 1
            ? el('circle', { cx: String(cx), cy: String(cy), r: String(r), fill: colorOf(i) })
            : el('path', {
              d: `M${cx} ${cy} L${p(angle)} A${r} ${r} 0 ${next - angle > Math.PI ? 1 : 0} 1 ${p(next)} Z`,
              fill: colorOf(i),
            });
          if (v > 0)
            svg.append(slice);
          svg.append(el('rect', {
            x: String(2 * r + 30),
            y: String(14 + i * 14),
            width: '8',
            height: '8',
            fill: colorOf(i),
          }));
          text(2 * r + 42, 21 + i * 14, `${data.categories[i] ?? ''} ${v}`, {}, 18);
          angle = next;
        });
        return;
      }
      const all = data.series.flatMap((s) => s.values.map((v) => v ?? 0));
      const top = nice(Math.max(1, ...all));
      const horizontal = type === 'bar';
      // plot box: left room for labels (wide on a horizontal chart), bottom room for labels and legend
      const x0 = horizontal ? 62 : 34;
      const x1 = W - 8;
      const y0 = 8;
      const y1 = H - 32;
      const val = (v) => horizontal ? x0 + (v / top) * (x1 - x0) : y1 - (v / top) * (y1 - y0);
      for (let k = 0; k <= 4; k++) {
        const v = (top / 4) * k;
        if (horizontal) {
          svg.append(el('line', {
            x1: String(val(v)),
            y1: String(y0),
            x2: String(val(v)),
            y2: String(y1),
            stroke: grid,
          }));
          text(val(v), y1 + 11, String(v), { 'text-anchor': 'middle' });
        }
        else {
          svg.append(el('line', {
            x1: String(x0),
            y1: String(val(v)),
            x2: String(x1),
            y2: String(val(v)),
            stroke: grid,
          }));
          text(x0 - 4, val(v) + 3, String(v), { 'text-anchor': 'end' });
        }
      }
      const cell = (horizontal ? y1 - y0 : x1 - x0) / n; // room of one category
      const mid = (i) => (horizontal ? y0 : x0) + cell * i + cell / 2;
      data.categories.forEach((c, i) => horizontal
        ? text(x0 - 5, mid(i) + 3, c, { 'text-anchor': 'end' }, 9)
        : text(mid(i), y1 + 11, c, { 'text-anchor': 'middle' }, Math.max(3, Math.floor(cell / 5))));
      data.series.forEach((s, si) => {
        const color = colorOf(si);
        const pts = s.values.map((v, i) => ({ c: mid(i), v: val(v ?? 0), n: v ?? 0 }));
        if (type === 'line' || type === 'area') {
          const line = pts.map((q) => `${q.c},${q.v}`).join(' ');
          if (type === 'area' && pts.length > 0)
            svg.append(el('polygon', {
              points: `${pts[0]?.c},${y1} ${line} ${pts[pts.length - 1]?.c},${y1}`,
              fill: color,
              'fill-opacity': '0.3',
            }));
          svg.append(el('polyline', { points: line, fill: 'none', stroke: color, 'stroke-width': '2' }));
          for (const q of pts)
            svg.append(el('circle', { cx: String(q.c), cy: String(q.v), r: '2.5', fill: color }));
          return;
        }
        const bw = (cell * 0.8) / m; // bars of one category sit side by side
        pts.forEach((q, i) => {
          const at = mid(i) - (cell * 0.8) / 2 + si * bw;
          const rect = horizontal
            ? { x: x0, y: at, width: q.v - x0, height: bw * 0.92 }
            : { x: at, y: q.v, width: bw * 0.92, height: y1 - q.v };
          const r = el('rect', {
            ...Object.fromEntries(Object.entries(rect).map(([k, v]) => [k, String(v)])),
            fill: color,
            'data-i': String(i),
          });
          r.append(el('title', {}, `${data.categories[i] ?? ''} · ${s.name}: ${q.n}`));
          svg.append(r);
        });
      });
      legend(data.series.map((s) => s.name), H);
    };
    draw(last);
    return { update: draw, destroy: () => svg.remove(), resize: () => draw(last) };
  },
};
export const options = {
  rowKey: 'id',
  columns,
  rows,
  cellSelection: 'multiple',
  selection: 'multiple',
  ariaLabel: 'Regional sales by quarter',
  chartAdapter: svgAdapter,
  filterRow: true,
};
let host = null;
let chart = null;
function ensureHost() {
  if (host !== null)
    return host;
  const first = document.getElementById('grid');
  host = document.createElement('div');
  host.id = 'chart-host';
  host.style.cssText = 'height:220px;margin-top:10px';
  if (first !== null)
    first.after(host);
  else
    document.body.append(host);
  return host;
}
function cleanup() {
  chart?.destroy();
  chart = null;
}
let currentType = 'column';
function rebuild(api, limit) {
  cleanup();
  chart = api.createChart(ensureHost(), {
    source: 'visible',
    type: currentType,
    ...(limit === undefined ? {} : { limit }),
  });
}
export function setup(api, log) {
  const offCreated = api.on('chartCreated', ({ categories }) => {
    log(`Chart created with ${categories} categories`);
  });
  const offUpdated = api.on('chartUpdated', ({ categories }) => {
    log(`Chart updated with ${categories} categories`);
  });
  rebuild(api);
  log('Type a region name in the filter row and the chart follows.');
  return () => {
    offCreated();
    offUpdated();
    cleanup();
    host?.remove();
    host = null;
  };
}
export const actions = {
  chartType: (api, value) => {
    currentType = value ?? 'column';
    rebuild(api);
  },
  limitThree: (api) => {
    rebuild(api, 3);
  },
};