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

Highcharts 차트 종류 바꾸기Switch Highcharts chart types

같은 Highcharts 어댑터로 막대·가로 막대·꺾은선·영역·원을 바꿔 가며 그려요. Highcharts는 단추를 누를 때만 공식 CDN에서 불러와요.The same Highcharts adapter draws column, bar, line, area and pie charts. Highcharts loads from the official CDN only when you press the button.

심화Advanced
직접 써 보기Live previewHighcharts 차트 종류 바꾸기Switch Highcharts chart types

코드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">
    <button type="button" id="load">Highcharts 불러오기</button>
    <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="clear">지우기</button>
  </div>
  <div id="grid" style="height: 320px"></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('load').addEventListener('click', () => actions.load(api));
document.getElementById('chartType').addEventListener('change', (event) => actions.chartType(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(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 HC_VERSION = '13.1.1';
const HC_URL = `https://code.highcharts.com/${HC_VERSION}/highcharts.js`;
const HC_SRI = 'sha384-FXT8Mj1JsVEsCNEB3qjrU1JPYJ94Ku7uMe0eopjumL2jEkPl1O9YeAZJn+qsOFVW';
const hc = () => window.Highcharts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el, dark) {
  const css = getComputedStyle(el);
  const read = (name, fallback) => css.getPropertyValue(name).trim() || fallback;
  const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
  const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
  const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
  const text = { style: { color: fg } };
  return {
    chart: { backgroundColor: bg },
    title: text,
    legend: { itemStyle: { color: fg }, itemHoverStyle: { color: read('--mxg-accent', fg) } },
    xAxis: { labels: text, lineColor: line, tickColor: line },
    yAxis: { labels: text, gridLineColor: line, title: text },
    tooltip: { backgroundColor: bg, style: { color: fg } },
    plotOptions: {
      pie: { borderColor: bg, dataLabels: { style: { color: fg, textOutline: 'none' } } },
    },
  };
}
/** Our ChartData -> Highcharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type, data) {
  if (type === 'pie') {
    const first = data.series[0];
    return [
      {
        type: 'pie',
        name: first?.name ?? '',
        data: data.categories.map((name, i) => ({ name, y: first?.values[i] ?? null })),
      },
    ];
  }
  return data.series.map((s) => ({ type, name: s.name, data: s.values }));
}
function loadHighcharts(onReady, onError) {
  if (hc() !== undefined)
    return onReady();
  let script = document.querySelector('script[data-highcharts]');
  if (script === null) {
    script = document.createElement('script');
    script.src = HC_URL;
    script.integrity = HC_SRI; // the pinned file must match, or the browser refuses it
    script.crossOrigin = 'anonymous';
    script.dataset.highcharts = '1';
    document.head.append(script);
  }
  script.addEventListener('load', onReady, { once: true });
  script.addEventListener('error', () => {
    script?.remove(); // allow another try
    onError();
  }, { once: true });
}
const highchartsAdapter = {
  create(ctx) {
    const Highcharts = hc();
    if (Highcharts === undefined) {
      ctx.container.textContent = 'Highcharts를 아직 불러오지 않았어요.';
      return { update() { }, destroy: () => ctx.container.replaceChildren() };
    }
    const opts = (ctx.options ?? {});
    const dark = ctx.theme === 'dark';
    const label = (d) => `${opts.title ?? '차트'}: ${d.categories.length} 분류, ${d.series.length} 계열`;
    // Without the Highcharts accessibility module the chart has no description of its own: describe the container instead.
    ctx.container.setAttribute('role', 'img');
    const first = ctx.getData();
    ctx.container.setAttribute('aria-label', label(first));
    const base = (d) => ({
      chart: { type: ctx.type },
      title: { text: opts.title ?? '' },
      xAxis: { categories: d.categories },
      yAxis: { title: { text: undefined } },
      series: seriesOf(ctx.type, d),
      accessibility: { enabled: false },
      ...(opts.valueFormat
        ? { tooltip: { pointFormat: `{series.name}: <b>${opts.valueFormat}</b><br/>` } }
        : {}),
    });
    const chart = Highcharts.chart(ctx.container, merge(base(first), themeOptions(ctx.container, dark), opts.highcharts));
    // Follow the grid theme when it changes later.
    const retheme = () => chart.update(themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark'));
    const watcher = new MutationObserver(retheme);
    watcher.observe(document.documentElement, {
      attributes: true,
      subtree: true,
      attributeFilter: ['data-mxg-theme'],
    });
    return {
      update(d) {
        ctx.container.setAttribute('aria-label', label(d));
        chart.update({ xAxis: { categories: d.categories }, series: seriesOf(ctx.type, d) }, true, true);
      },
      destroy() {
        watcher.disconnect();
        chart.destroy();
        ctx.container.removeAttribute('role');
        ctx.container.removeAttribute('aria-label');
      },
      resize: () => chart.reflow(),
    };
  },
};
/** Small deep merge for plain option objects. */
function merge(...parts) {
  const out = {};
  for (const part of parts) {
    for (const [key, value] of Object.entries(part ?? {})) {
      const prev = out[key];
      const plain = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
      out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
    }
  }
  return out;
}
export const options = {
  rowKey: 'id',
  columns,
  rows,
  cellSelection: 'multiple',
  selection: 'multiple',
  ariaLabel: '지역별 분기 매출',
  chartAdapter: highchartsAdapter,
};
let host = null;
let notice = null;
let status = null;
let chart = null;
let loaded = false;
function ensureHost() {
  if (host !== null)
    return host;
  const first = document.getElementById('grid');
  notice = document.createElement('div');
  notice.style.cssText =
    'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
  const text = document.createElement('p');
  text.style.margin = '0 0 6px';
  text.textContent =
    'Highcharts는 별도의 상용 라이브러리예요. 상업적으로 쓰려면 자체 라이선스가 필요하고, 맥스그리드에는 들어 있지 않아요. 아래 단추를 누르면 공식 CDN(code.highcharts.com)에서 불러와요.';
  status = document.createElement('p');
  status.style.margin = '0';
  status.setAttribute('role', 'status');
  status.textContent =
    '아직 불러오지 않았어요. 단추를 누르기 전에는 외부로 아무것도 요청하지 않아요.';
  notice.append(text, status);
  host = document.createElement('div');
  host.id = 'chart-host';
  host.style.cssText = 'height:260px;margin-top:10px';
  if (first !== null)
    first.after(notice, host);
  else
    document.body.append(notice, host);
  return host;
}
function cleanup() {
  chart?.destroy();
  chart = null;
}
function showStatus(message) {
  ensureHost();
  if (status !== null)
    status.textContent = message;
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api, type) {
  if (api.getSelectedCells().length === 0)
    api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
  return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: '지역별 분기 매출', valueFormat: '{point.y:,.0f}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log, then) {
  ensureHost();
  if (loaded || window.Highcharts !== undefined) {
    loaded = true;
    showStatus('Highcharts를 불러왔어요.');
    then?.();
    return;
  }
  showStatus('Highcharts를 불러오는 중이에요…');
  loadHighcharts(() => {
    loaded = true;
    showStatus('Highcharts를 불러왔어요.');
    log({ ko: 'Highcharts 13.1.1을 불러왔어요.', en: 'Highcharts 13.1.1 loaded.' });
    then?.();
  }, () => {
    showStatus('Highcharts를 불러오지 못했어요. 인터넷 연결이나 보안 정책(CSP)을 확인하고 다시 눌러 보세요.');
    log({
      ko: 'Highcharts를 불러오지 못했어요(오프라인이거나 막혔어요).',
      en: 'Could not load Highcharts (offline or blocked).',
    });
  });
}
const needLoad = (log) => {
  if (loaded)
    return false;
  showStatus('먼저 "Highcharts 불러오기"를 눌러 주세요.');
  log({ ko: '먼저 "Highcharts 불러오기"를 눌러 주세요.', en: 'Press "Load Highcharts" first.' });
  return true;
};
let say = () => { };
let currentType = 'column';
function rebuild(api) {
  if (needLoad(say))
    return;
  cleanup();
  chart = fromSelection(api, currentType);
}
export function setup(api, log) {
  say = log;
  loaded = false;
  currentType = 'column';
  ensureHost();
  const offCreated = api.on('chartCreated', ({ type }) => {
    log({ ko: `차트를 만들었어요: ${type}`, en: `Chart created: ${type}` });
  });
  log({
    ko: '먼저 "Highcharts 불러오기"를 누르고, 종류를 바꿔 보세요.',
    en: 'Press "Load Highcharts", then switch the type.',
  });
  return () => {
    offCreated();
    cleanup();
    notice?.remove();
    host?.remove();
    notice = null;
    status = null;
    host = null;
  };
}
export const actions = {
  load: (api) => load(say, () => rebuild(api)),
  chartType: (api, value) => {
    currentType = value ?? 'column';
    rebuild(api);
  },
  clear: () => {
    cleanup();
  },
};

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">
    <button type="button" id="load">Load Highcharts</button>
    <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="clear">Clear</button>
  </div>
  <div id="grid" style="height: 320px"></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('load').addEventListener('click', () => actions.load(api));
document.getElementById('chartType').addEventListener('change', (event) => actions.chartType(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(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 HC_VERSION = '13.1.1';
const HC_URL = `https://code.highcharts.com/${HC_VERSION}/highcharts.js`;
const HC_SRI = 'sha384-FXT8Mj1JsVEsCNEB3qjrU1JPYJ94Ku7uMe0eopjumL2jEkPl1O9YeAZJn+qsOFVW';
const hc = () => window.Highcharts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el, dark) {
  const css = getComputedStyle(el);
  const read = (name, fallback) => css.getPropertyValue(name).trim() || fallback;
  const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
  const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
  const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
  const text = { style: { color: fg } };
  return {
    chart: { backgroundColor: bg },
    title: text,
    legend: { itemStyle: { color: fg }, itemHoverStyle: { color: read('--mxg-accent', fg) } },
    xAxis: { labels: text, lineColor: line, tickColor: line },
    yAxis: { labels: text, gridLineColor: line, title: text },
    tooltip: { backgroundColor: bg, style: { color: fg } },
    plotOptions: {
      pie: { borderColor: bg, dataLabels: { style: { color: fg, textOutline: 'none' } } },
    },
  };
}
/** Our ChartData -> Highcharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type, data) {
  if (type === 'pie') {
    const first = data.series[0];
    return [
      {
        type: 'pie',
        name: first?.name ?? '',
        data: data.categories.map((name, i) => ({ name, y: first?.values[i] ?? null })),
      },
    ];
  }
  return data.series.map((s) => ({ type, name: s.name, data: s.values }));
}
function loadHighcharts(onReady, onError) {
  if (hc() !== undefined)
    return onReady();
  let script = document.querySelector('script[data-highcharts]');
  if (script === null) {
    script = document.createElement('script');
    script.src = HC_URL;
    script.integrity = HC_SRI; // the pinned file must match, or the browser refuses it
    script.crossOrigin = 'anonymous';
    script.dataset.highcharts = '1';
    document.head.append(script);
  }
  script.addEventListener('load', onReady, { once: true });
  script.addEventListener('error', () => {
    script?.remove(); // allow another try
    onError();
  }, { once: true });
}
const highchartsAdapter = {
  create(ctx) {
    const Highcharts = hc();
    if (Highcharts === undefined) {
      ctx.container.textContent = 'Highcharts is not loaded yet.';
      return { update() { }, destroy: () => ctx.container.replaceChildren() };
    }
    const opts = (ctx.options ?? {});
    const dark = ctx.theme === 'dark';
    const label = (d) => `${opts.title ?? 'Chart'}: ${d.categories.length} categories, ${d.series.length} series`;
    // Without the Highcharts accessibility module the chart has no description of its own: describe the container instead.
    ctx.container.setAttribute('role', 'img');
    const first = ctx.getData();
    ctx.container.setAttribute('aria-label', label(first));
    const base = (d) => ({
      chart: { type: ctx.type },
      title: { text: opts.title ?? '' },
      xAxis: { categories: d.categories },
      yAxis: { title: { text: undefined } },
      series: seriesOf(ctx.type, d),
      accessibility: { enabled: false },
      ...(opts.valueFormat
        ? { tooltip: { pointFormat: `{series.name}: <b>${opts.valueFormat}</b><br/>` } }
        : {}),
    });
    const chart = Highcharts.chart(ctx.container, merge(base(first), themeOptions(ctx.container, dark), opts.highcharts));
    // Follow the grid theme when it changes later.
    const retheme = () => chart.update(themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark'));
    const watcher = new MutationObserver(retheme);
    watcher.observe(document.documentElement, {
      attributes: true,
      subtree: true,
      attributeFilter: ['data-mxg-theme'],
    });
    return {
      update(d) {
        ctx.container.setAttribute('aria-label', label(d));
        chart.update({ xAxis: { categories: d.categories }, series: seriesOf(ctx.type, d) }, true, true);
      },
      destroy() {
        watcher.disconnect();
        chart.destroy();
        ctx.container.removeAttribute('role');
        ctx.container.removeAttribute('aria-label');
      },
      resize: () => chart.reflow(),
    };
  },
};
/** Small deep merge for plain option objects. */
function merge(...parts) {
  const out = {};
  for (const part of parts) {
    for (const [key, value] of Object.entries(part ?? {})) {
      const prev = out[key];
      const plain = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
      out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
    }
  }
  return out;
}
export const options = {
  rowKey: 'id',
  columns,
  rows,
  cellSelection: 'multiple',
  selection: 'multiple',
  ariaLabel: 'Regional sales by quarter',
  chartAdapter: highchartsAdapter,
};
let host = null;
let notice = null;
let status = null;
let chart = null;
let loaded = false;
function ensureHost() {
  if (host !== null)
    return host;
  const first = document.getElementById('grid');
  notice = document.createElement('div');
  notice.style.cssText =
    'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
  const text = document.createElement('p');
  text.style.margin = '0 0 6px';
  text.textContent =
    'Highcharts is a separate commercial library that needs its own license for commercial use; MaxGrid does not include it. The button below loads it from the official CDN (code.highcharts.com).';
  status = document.createElement('p');
  status.style.margin = '0';
  status.setAttribute('role', 'status');
  status.textContent =
    'Not loaded yet. Nothing is requested from the network until you press the button.';
  notice.append(text, status);
  host = document.createElement('div');
  host.id = 'chart-host';
  host.style.cssText = 'height:260px;margin-top:10px';
  if (first !== null)
    first.after(notice, host);
  else
    document.body.append(notice, host);
  return host;
}
function cleanup() {
  chart?.destroy();
  chart = null;
}
function showStatus(message) {
  ensureHost();
  if (status !== null)
    status.textContent = message;
}
// If nothing is selected, select the first four rows (region to Q3) so a chart appears at once.
function fromSelection(api, type) {
  if (api.getSelectedCells().length === 0)
    api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
  return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: 'Regional sales by quarter', valueFormat: '{point.y:,.0f}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log, then) {
  ensureHost();
  if (loaded || window.Highcharts !== undefined) {
    loaded = true;
    showStatus('Highcharts is loaded.');
    then?.();
    return;
  }
  showStatus('Loading Highcharts…');
  loadHighcharts(() => {
    loaded = true;
    showStatus('Highcharts is loaded.');
    log('Highcharts 13.1.1 loaded.');
    then?.();
  }, () => {
    showStatus('Could not load Highcharts. Check your connection or Content Security Policy and press the button again.');
    log('Could not load Highcharts (offline or blocked).');
  });
}
const needLoad = (log) => {
  if (loaded)
    return false;
  showStatus('Press "Load Highcharts" first.');
  log('Press "Load Highcharts" first.');
  return true;
};
let say = () => { };
let currentType = 'column';
function rebuild(api) {
  if (needLoad(say))
    return;
  cleanup();
  chart = fromSelection(api, currentType);
}
export function setup(api, log) {
  say = log;
  loaded = false;
  currentType = 'column';
  ensureHost();
  const offCreated = api.on('chartCreated', ({ type }) => {
    log(`Chart created: ${type}`);
  });
  log('Press "Load Highcharts", then switch the type.');
  return () => {
    offCreated();
    cleanup();
    notice?.remove();
    host?.remove();
    notice = null;
    status = null;
    host = null;
  };
}
export const actions = {
  load: (api) => load(say, () => rebuild(api)),
  chartType: (api, value) => {
    currentType = value ?? 'column';
    rebuild(api);
  },
  clear: () => {
    cleanup();
  },
};