Skip to content

Stacked bars

Series stack when they share a stack id from seriesStacks. With exactly one stack configured, every series joins it automatically — declaring the stack is the only wiring needed.

Open in demo ↗

Animate the data and watch the stack move as one unit: each segment's baseline follows the tweened top of the segment below it, so the stack never shows gaps mid-transition (see staged animation).

ts
// With exactly one entry in seriesStacks, every series defaults its
// `stack` to that stack's id — no per-series wiring needed.
import type { MochartInputConfig } from '@mochart/core';

export const config: MochartInputConfig = {
  version: '1.0.0',
  title: { text: 'Revenue by Product' },
  categoryAxis: { property: 'quarter', type: 'string', scale: 'ordinal' },
  seriesDefaults: { renderer: 'bar' },
  series: [
    { property: 'starter', title: 'Starter' },
    { property: 'pro', title: 'Pro' },
    { property: 'enterprise', title: 'Enterprise' }
  ],
  seriesStacks: [{ id: 'revenue' }]
};

export const data = [
  { quarter: 'Q1', starter: 10, pro: 14, enterprise: 8 },
  { quarter: 'Q2', starter: 12, pro: 18, enterprise: 11 },
  { quarter: 'Q3', starter: 11, pro: 22, enterprise: 16 },
  { quarter: 'Q4', starter: 13, pro: 25, enterprise: 22 }
];

export const altData = [
  { quarter: 'Q1', starter: 14, pro: 10, enterprise: 12 },
  { quarter: 'Q2', starter: 9, pro: 24, enterprise: 8 },
  { quarter: 'Q3', starter: 16, pro: 15, enterprise: 21 },
  { quarter: 'Q4', starter: 11, pro: 30, enterprise: 14 }
];

Variations

  • Opt a series out of the stack with stack: null — handy for overlaying a line on stacked bars.
  • Cap only the outer end of the whole stack with outerCapType — see the bar caps recipe.
  • Side-by-side (grouped) bars instead of stacked: declare a seriesGroups entry rather than a stack — series default into a sole group the same way.
  • Series with negative values stack downward from the same zero base — see positive and negative values.

Released under the BSD-3-Clause License.