Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-viz): percent-stack support for combo charts; remove last SQL chart fallback (#67440)

Sam Penningtonc41720586bd8
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
index 90bfd36e178f..192ba8c8c03d 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
@@ -229,7 +229,25 @@ describe('sqlLineGraphAdapter', () => {
)
})
- it('falls back for percent-stacked bars (unsupported by ComboChart)', () => {
+ it('renders natively for percent-stacked bars when the line is on the right axis', () => {
+ const yData = [
+ ySeries('a', [1], { display: { displayType: 'line', yAxisPosition: 'right' } }),
+ ySeries('b', [2], { display: { displayType: 'bar' } }),
+ ]
+ expect(
+ canRenderSqlComboGraph(
+ baseProps({
+ visualizationType: ChartDisplayType.ActionsStackedBar,
+ yData,
+ chartSettings: { stackBars100: true },
+ })
+ )
+ ).toBe(true)
+ })
+
+ it("falls back for percent-stacked bars when a line shares the bars' axis", () => {
+ // The bars' axis clamps to [0, 1] in percent mode — a line on the same (default/left)
+ // axis has no way to plot its raw values there, so the combo path is unavailable.
expect(
canRenderSqlComboGraph(
baseProps({
@@ -244,11 +262,17 @@ describe('sqlLineGraphAdapter', () => {
describe('comboBarLayoutForDisplay', () => {
it.each([
- ['stacked for a stacked bar graph', ChartDisplayType.ActionsStackedBar, 'stacked'],
- ['grouped for a bar graph', ChartDisplayType.ActionsBar, 'grouped'],
- ['grouped for a line graph', ChartDisplayType.ActionsLineGraph, 'grouped'],
- ])('returns %s', (_name, visualizationType, expected) => {
- expect(comboBarLayoutForDisplay(visualizationType)).toBe(expected)
+ ['stacked for a stacked bar graph', ChartDisplayType.ActionsStackedBar, {}, 'stacked'],
+ ['grouped for a bar graph', ChartDisplayType.ActionsBar, {}, 'grouped'],
+ ['grouped for a line graph', ChartDisplayType.ActionsLineGraph, {}, 'grouped'],
+ [
+ 'percent for a stacked bar graph when stackBars100 is on',
+ ChartDisplayType.ActionsStackedBar,
+ { stackBars100: true },
+ 'percent',
+ ],
+ ])('returns %s', (_name, visualizationType, chartSettings, expected) => {
+ expect(comboBarLayoutForDisplay(visualizationType, chartSettings as ChartSettings)).toBe(expected)
})
})
@@ -807,6 +831,18 @@ describe('sqlLineGraphAdapter', () => {
expect('trendLines' in config).toBe(true)
})
+ it('skips trend lines for percent-stacked bars, where they would render off-scale', () => {
+ const ySeriesData = [ySeries('a', [1, 2], { display: { trendLine: true } })]
+ const config = buildComboChartConfig({
+ xData: dateXData,
+ chartSettings: { stackBars100: true },
+ timezone: 'UTC',
+ visualizationType: ChartDisplayType.ActionsStackedBar,
+ ySeriesData,
+ })
+ expect(config.trendLines).toEqual([])
+ })
+
it('honors leftYAxisSettings for the single y-axis', () => {
const chartSettings: ChartSettings = {
leftYAxisSettings: { label: 'Combo Left', scale: 'logarithmic', showGridLines: false },
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
index 29347b817682..8bb8e4663c53 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
@@ -140,9 +140,9 @@ export function canRenderSqlBarGraph(props: LineGraphProps): boolean {
}
/**
- * Mixed bar + line/area series render on quill's {@link TimeSeriesComboChart}. Trend lines and
- * percent-stacked layouts (unsupported by ComboChart) and right y-axis series (a single tick
- * formatter can't honor a second gutter's settings yet) still fall back to legacy chart.js.
+ * Mixed bar + line/area series render on quill's {@link TimeSeriesComboChart}. Percent-stacked
+ * bars are supported as long as every line/area series is routed to the right axis — one sharing
+ * the bars' axis can't be reconciled with the bars' [0, 1] percent scale, so that case falls back.
*/
export function canRenderSqlComboGraph(props: LineGraphProps): boolean {
const { visualizationType, yData, chartSettings } = props
@@ -158,8 +158,16 @@ export function canRenderSqlComboGraph(props: LineGraphProps): boolean {
if (!yData || !hasMixedSeriesTypes(yData, visualizationType)) {
return false
}
- // ComboChart supports only stacked/grouped bars, not percent (stackBars100).
- if (barLayoutForDisplay(visualizationType, chartSettings) === 'percent') {
+ // Percent-stacked bars clamp their axis to [0, 1] — a line/area series sharing that same axis
+ // would plot its raw values off-scale with no way to reconcile the two domains. Only allow a
+ // percent-stack combo when every non-bar series is routed to the right axis instead.
+ if (
+ visualizationType === ChartDisplayType.ActionsStackedBar &&
+ chartSettings.stackBars100 &&
+ yData.some(
+ (series) => seriesDisplayType(visualizationType, series.settings) !== 'bar' && !isRightAxisSeries(series)
+ )
+ ) {
return false
}
return true
@@ -175,12 +183,15 @@ export function barLayoutForDisplay(
return 'grouped'
}
-/** Bar layout for the combo path — stacked for stacked-bar charts, grouped otherwise. ComboChart
- * doesn't support percent, so {@link canRenderSqlComboGraph} keeps stackBars100 on the legacy path. */
+/** Bar layout for the combo path. */
export function comboBarLayoutForDisplay(
- visualizationType: ChartDisplayType
+ visualizationType: ChartDisplayType,
+ chartSettings: ChartSettings
): NonNullable<TimeSeriesComboChartConfig['barLayout']> {
- return visualizationType === ChartDisplayType.ActionsStackedBar ? 'stacked' : 'grouped'
+ if (visualizationType === ChartDisplayType.ActionsStackedBar) {
+ return chartSettings.stackBars100 ? 'percent' : 'stacked'
+ }
+ return 'grouped'
}
/** Returns true when {@link MAX_SERIES} is exceeded and the user should be warned (not on dashboards). */
@@ -470,6 +481,8 @@ export function buildComboChartConfig({
const leftSeries = seriesForAxis(ySeriesData, 'left')
const rightSeries = seriesForAxis(ySeriesData, 'right')
+ const barLayout = comboBarLayoutForDisplay(visualizationType, chartSettings)
+ const isPercent = barLayout === 'percent'
return {
xAxis: buildXAxisConfig(xData, chartSettings, timezone),
@@ -479,16 +492,22 @@ export function buildComboChartConfig({
buildYAxisConfig(chartSettings.leftYAxisSettings, leftSeries, chartSettings.yAxisAtZero, {
id: 'left',
position: 'left',
+ forceLinear: isPercent,
}),
buildYAxisConfig(chartSettings.rightYAxisSettings, rightSeries, chartSettings.yAxisAtZero, {
id: 'right',
position: 'right',
+ forceLinear: isPercent,
}),
]
- : buildYAxisConfig(chartSettings.leftYAxisSettings, leftSeries, chartSettings.yAxisAtZero),
+ : buildYAxisConfig(chartSettings.leftYAxisSettings, leftSeries, chartSettings.yAxisAtZero, {
+ forceLinear: isPercent,
+ }),
goalLines: schemaGoalLinesToConfigs(goalLines),
- barLayout: comboBarLayoutForDisplay(visualizationType),
- trendLines: buildTrendLineConfigs(ySeriesData),
+ barLayout,
+ // Percent bars scale against a [0, 1] domain; trend lines plot raw series values, so they'd
+ // render off-scale and invisible.
+ trendLines: isPercent ? [] : buildTrendLineConfigs(ySeriesData),
legend: buildLegendConfig(chartSettings),
valueLabels: buildValueLabelsConfig(chartSettings, ySeriesData),
tooltip: {
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index a91afe797ef8..f9a382fce787 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -4,19 +4,19 @@ Quick-reference for AI agents using `@posthog/quill-charts`. Canvas-rendered cha
## Choosing a chart
-| Chart | Use when |
-| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| LineChart | Categorical x-axis trends; area fills, fill-between (confidence ribbons) |
-| BarChart | Categorical comparisons — `barLayout: 'stacked' \| 'grouped' \| 'percent'`, `axisOrientation: 'horizontal'` for horizontal bars |
-| ComboChart | Mixed bar/line/area series on one band x-axis — set `Series.type`; vertical-only, `barLayout: 'stacked' \| 'grouped'` |
-| TimeSeriesLineChart | Time-indexed labels (ISO strings) with timezone/interval-aware x-axis |
-| TimeSeriesBarChart | Same x-axis handling, bar rendering; supports per-series `yAxisId` axes |
-| TimeSeriesComboChart | Mixed bar + line/area on a time x-axis — `ComboChart` plus the time-series chrome (date x-axis, goal lines, legend, value labels) |
-| PieChart | Part-of-whole, one value per series; `innerRadiusRatio` for donut + `centerLabel`; on-slice labels via `showLabelOnSlice`/`showValueOnSlice`, positioned with `labelRadiusRatio` (0=center, 1=rim) and gated by `minSlicePercentForLabel` |
-| BoxPlot | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label |
-| Sparkline | Tiny inline trend from a flat `number[]` — no axes, no series structure |
-| MetricCard | Headline number + sparkline + change pill (dashboard stat tiles) |
-| SlopeChart | Change between two points (slopegraph) — one line per series, left "before" → right "after"; `data: [start, end]` |
+| Chart | Use when |
+| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| LineChart | Categorical x-axis trends; area fills, fill-between (confidence ribbons) |
+| BarChart | Categorical comparisons — `barLayout: 'stacked' \| 'grouped' \| 'percent'`, `axisOrientation: 'horizontal'` for horizontal bars |
+| ComboChart | Mixed bar/line/area series on one band x-axis — set `Series.type`; vertical-only, `barLayout: 'stacked' \| 'grouped' \| 'percent'` (percent stacks bar series to 100%; a line/area series needs its own `yAxisId: 'right'` axis — one sharing the bars' axis can't plot raw values against their [0,1] scale) |
+| TimeSeriesLineChart | Time-indexed labels (ISO strings) with timezone/interval-aware x-axis |
+| TimeSeriesBarChart | Same x-axis handling, bar rendering; supports per-series `yAxisId` axes |
+| TimeSeriesComboChart | Mixed bar + line/area on a time x-axis — `ComboChart` plus the time-series chrome (date x-axis, goal lines, legend, value labels) |
+| PieChart | Part-of-whole, one value per series; `innerRadiusRatio` for donut + `centerLabel`; on-slice labels via `showLabelOnSlice`/`showValueOnSlice`, positioned with `labelRadiusRatio` (0=center, 1=rim) and gated by `minSlicePercentForLabel` |
+| BoxPlot | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label |
+| Sparkline | Tiny inline trend from a flat `number[]` — no axes, no series structure |
+| MetricCard | Headline number + sparkline + change pill (dashboard stat tiles) |
+| SlopeChart | Change between two points (slopegraph) — one line per series, left "before" → right "after"; `data: [start, end]` |
## Theme wiring
@@ -77,7 +77,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order) and formats values with `valueFormatter` so they match the on-chart labels' units; pass your own `tooltip` to override. (`DefaultTooltip` itself takes an optional `valueFormatter` for the same reason — without it values fall back to `toLocaleString`.) Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`; `sparklineDashedFromIndex` dashes the sparkline from that index onward (e.g. an in-progress trailing period). `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point). `changeTooltip` shows a styled hover tooltip (floating-ui, using the host's tooltip surface tokens with chart-surface fallbacks) on the change pill (e.g. to spell out what the resting comparison is).
- The composable form of `MetricCard` lives one layer up as `Metric` in `@posthog/quill-components` (it needs `Card`/`Badge` from primitives, which charts can't depend on). It's built on `Sparkline` plus the headless metric helpers this package exports — `resolveDelta` / `computeFallbackChangePercent` (delta math), `useAnimatedNumber` (count-up headline), `useHoverIntent` (hover dwell) — and the `MetricChange` / `ResolvedDelta` types. Reach for `Metric` when you need a custom layout; use the monolithic `MetricCard` here for the default self-contained tile.
-- `TimeSeriesComboChart` wraps `ComboChart` the way `TimeSeriesLineChart`/`TimeSeriesBarChart` wrap their base charts: `config.xAxis`/`config.yAxis` (date tick formatter, y-format, scale, grid), `config.goalLines` (off-scale targets stretch the value axis via `ComboChart`'s `valueDomain`), `config.legend` (click-to-toggle), and `config.valueLabels`. Per-series `type` (`'bar' | 'line' | 'area'`) drives rendering; `barLayout` (`'stacked' | 'grouped'`) and right-axis series (`yAxisId: 'right'`) carry over from `ComboChart`. `ComboChart` itself now also honors `valueDomain` (primary axis only) and `showAxisLines`.
+- `TimeSeriesComboChart` wraps `ComboChart` the way `TimeSeriesLineChart`/`TimeSeriesBarChart` wrap their base charts: `config.xAxis`/`config.yAxis` (date tick formatter, y-format, scale, grid), `config.goalLines` (off-scale targets stretch the value axis via `ComboChart`'s `valueDomain`), `config.legend` (click-to-toggle), and `config.valueLabels`. Per-series `type` (`'bar' | 'line' | 'area'`) drives rendering; `barLayout` (`'stacked' | 'grouped' | 'percent'`) and right-axis series (`yAxisId: 'right'`) carry over from `ComboChart`. `ComboChart` itself now also honors `valueDomain` (primary axis only) and `showAxisLines`.
- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.
- y-axis baseline: defaults to clamping a non-negative axis down to 0 (matching the classic insight axis). To float the axis to its data range instead — zooming in on the variation — set `yAxis.startAtZero: false` on `TimeSeriesLineChart`, or `config.floatBaseline: true` on the lower-level `LineChart`. Ignored on a log scale (no zero baseline) and applied to the primary axis only. Bar charts always draw from a zero baseline, so the flag is a no-op there.
- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. More than two axes work too (trends `showMultipleYAxes`): they stack outward per side and alternate sides. Each entry's `label` renders that axis's title at its own gutter — every axis is titled the same way (a single-object `yAxis`/scalar `yAxisLabel` is just the one left axis), driven by the shared `computeYAxisGutters` layout that `AxisLabels` (ticks) and `AxisTitles` (titles) both read so the two can't drift. `TimeSeriesBarChart`/`ComboChart` already render per-`yAxisId` axes but share one tick formatter across gutters.
diff --git a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.test.tsx b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.test.tsx
index 2967324e0543..af029b1fe4fb 100644
--- a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.test.tsx
@@ -67,6 +67,29 @@ describe('ComboChart', () => {
expect(chart.yRightTicks().length).toBeGreaterThan(0)
})
+ describe('percent barLayout', () => {
+ it('applies a default percent formatter when the consumer omits one', () => {
+ const { chart } = renderHogChart(
+ <ComboChart series={BAR_AND_LINE} labels={LABELS} theme={THEME} config={{ barLayout: 'percent' }} />
+ )
+ expect(chart.yTicks().some((t) => /\d+%/.test(t))).toBe(true)
+ })
+
+ it('renders a custom percent formatter when the consumer supplies one', () => {
+ const formatter = jest.fn((v: number) => `${Math.round(v * 1000) / 10}‰`)
+ const { chart } = renderHogChart(
+ <ComboChart
+ series={BAR_AND_LINE}
+ labels={LABELS}
+ theme={THEME}
+ config={{ barLayout: 'percent', yTickFormatter: formatter }}
+ />
+ )
+ expect(formatter).toHaveBeenCalled()
+ expect(chart.yTicks().some((t) => t.endsWith('‰'))).toBe(true)
+ })
+ })
+
describe('hover & tooltip', () => {
it('lists every visible series at the hovered x', async () => {
const { chart } = renderHogChart(<ComboChart series={BAR_AND_LINE} labels={LABELS} theme={THEME} />)
diff --git a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx
index 511ae001aa90..90e76975d988 100644
--- a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx
+++ b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx
@@ -21,6 +21,7 @@ import {
buildSegmentResolveValue,
buildStackedBottomValue,
buildStackedPositionValue,
+ computePercentStackData,
computeStackData,
computeTopStackedKeyByAxis,
resolveYScaleForSeries,
@@ -98,21 +99,23 @@ function ComboChartInner<Meta = unknown>({
// Stack only bar series together. Lines/areas are explicitly excluded so a line doesn't get a
// bottom-of-stack offset and bars don't widen the line's drawn baseline.
const barStackedData = useMemo<Map<string, StackedBand> | undefined>(() => {
- if (barLayout !== 'stacked') {
+ if (barLayout !== 'stacked' && barLayout !== 'percent') {
return undefined
}
const barSeries = series.filter((s) => seriesTypeOf(s) === 'bar')
if (barSeries.length === 0) {
return undefined
}
- return computeStackData(barSeries, labels)
+ return barLayout === 'percent'
+ ? computePercentStackData(barSeries, labels)
+ : computeStackData(barSeries, labels)
}, [barLayout, series, labels, seriesTypeOf])
// Per-axis topmost bar — only bar layers below the cap forgo corner rounding. Non-bar series are
// skipped so lines/areas don't take part in bar stacking. Shares BarChart's helper.
const topStackedKeyByAxis = useMemo<Map<string, string>>(
() =>
- barLayout !== 'stacked'
+ barLayout !== 'stacked' && barLayout !== 'percent'
? new Map()
: computeTopStackedKeyByAxis(series, { skip: (s) => seriesTypeOf(s) !== 'bar' }),
[barLayout, series, seriesTypeOf]
@@ -318,11 +321,24 @@ function ComboChartInner<Meta = unknown>({
const resolvePositionValue = useMemo(() => buildStackedPositionValue(barStackedData), [barStackedData])
const resolveBottomValue = useMemo(() => buildStackedBottomValue(barStackedData), [barStackedData])
+ // Mirrors BarChart: flag the axis context as percent (drives ValueLabels' 0-1 fraction
+ // handling) and default the y-tick formatter to a percentage unless the caller overrides it.
+ const chartConfig = useMemo<ComboChartConfig>(() => {
+ const base = { ...config, isPercent: barLayout === 'percent' }
+ if (barLayout !== 'percent' || config?.yTickFormatter) {
+ return base
+ }
+ return {
+ ...base,
+ yTickFormatter: (v: number) => `${Math.round(v * 100)}%`,
+ }
+ }, [config, barLayout])
+
return (
<Chart
series={series}
labels={labels}
- config={config}
+ config={chartConfig}
theme={theme}
createScales={createScales}
drawStatic={drawStatic}
diff --git a/packages/quill/packages/charts/src/core/combo-scales.test.ts b/packages/quill/packages/charts/src/core/combo-scales.test.ts
index 8a4c0c74f2a9..3031cd36c9b1 100644
--- a/packages/quill/packages/charts/src/core/combo-scales.test.ts
+++ b/packages/quill/packages/charts/src/core/combo-scales.test.ts
@@ -1,7 +1,7 @@
import { dimensions, makeSeries } from '../testing'
import { computeBarAtIndex } from './bar-layout'
import { createComboScales, isLineLike, partitionByType, resolveSeriesType } from './combo-scales'
-import { computeStackData } from './scales'
+import { computePercentStackData, computeStackData } from './scales'
import type { Series, SeriesType } from './types'
import { DEFAULT_Y_AXIS_ID } from './types'
@@ -244,6 +244,52 @@ describe('combo-scales', () => {
})
})
+ describe('createComboScales — percent-stack barLayout', () => {
+ it('clamps the y-scale domain to [0, 1] when barLayout is percent', () => {
+ const bar1 = makeSeries({ key: 'b1', data: [300], type: 'bar' })
+ const bar2 = makeSeries({ key: 'b2', data: [700], type: 'bar' })
+ const barStackedData = computePercentStackData([bar1, bar2], ['a'])
+ const scales = createComboScales([bar1, bar2], ['a'], dimensions, {
+ barLayout: 'percent',
+ seriesTypeOf: typeOfWithDefault('line'),
+ barStackedData,
+ })
+ const [domainMin, domainMax] = scales.y.domain()
+ expect(domainMin).toBeCloseTo(0, 1)
+ expect(domainMax).toBeCloseTo(1, 1)
+ })
+
+ it('bar series percent tops sum to 1 across the stack', () => {
+ const bar1 = makeSeries({ key: 'b1', data: [300], type: 'bar' })
+ const bar2 = makeSeries({ key: 'b2', data: [700], type: 'bar' })
+ const barStackedData = computePercentStackData([bar1, bar2], ['a'])
+ // b2 is the topmost bar — its cumulative top should be 1.0
+ expect(barStackedData.get('b2')?.top[0]).toBeCloseTo(1, 5)
+ })
+
+ it('does not clamp a line-only secondary axis to [0, 1] when the primary axis is percent-stacked', () => {
+ // Regression guard: percentStack must only clamp axes that actually carry bar series —
+ // a line explicitly routed to the right axis needs its own data-derived scale, not the
+ // bars' [0, 1] domain, or it renders off-plot.
+ const bar1 = makeSeries({ key: 'b1', data: [300], type: 'bar' })
+ const bar2 = makeSeries({ key: 'b2', data: [700], type: 'bar' })
+ const rightLine = makeSeries({ key: 'l1', data: [5000], type: 'line', yAxisId: 'right' })
+ const series = [bar1, bar2, rightLine]
+ const barStackedData = computePercentStackData([bar1, bar2], ['a'])
+ const scales = createComboScales(series, ['a'], dimensions, {
+ barLayout: 'percent',
+ seriesTypeOf: typeOfWithDefault('line'),
+ barStackedData,
+ })
+ const [leftMin, leftMax] = scales.yAxes[DEFAULT_Y_AXIS_ID].scale.domain()
+ expect(leftMin).toBeCloseTo(0, 1)
+ expect(leftMax).toBeCloseTo(1, 1)
+ const [, rightMax] = scales.yAxes.right.scale.domain()
+ expect(rightMax).toBeGreaterThan(1)
+ expect(scales.yAxes.right.scale(5000)).not.toBeCloseTo(scales.yAxes.right.scale(0), 0)
+ })
+ })
+
describe('createComboScales — per-series type defaulting from config', () => {
it('treats series without explicit type as the configured default', () => {
const untyped = makeSeries({ key: 'u', data: [50] })
diff --git a/packages/quill/packages/charts/src/core/combo-scales.ts b/packages/quill/packages/charts/src/core/combo-scales.ts
index c5573f6ab122..aa359da226ba 100644
--- a/packages/quill/packages/charts/src/core/combo-scales.ts
+++ b/packages/quill/packages/charts/src/core/combo-scales.ts
@@ -30,7 +30,7 @@ export interface ComboChartPrivate {
export interface CreateComboScalesOptions {
scaleType?: 'linear' | 'log'
- barLayout?: 'stacked' | 'grouped'
+ barLayout?: 'stacked' | 'grouped' | 'percent'
bandPadding?: number
groupPadding?: number
seriesTypeOf: (series: Series) => SeriesType
@@ -96,15 +96,19 @@ export function createComboScales(
// otherwise; lines/areas always contribute raw. The value scale spans the union.
const axisValueSeries: Series[] = axisSeries.map((s) => {
const stacked = barStackedData?.get(s.key)
- if (seriesTypeOf(s) === 'bar' && barLayout === 'stacked' && stacked) {
+ if (seriesTypeOf(s) === 'bar' && (barLayout === 'stacked' || barLayout === 'percent') && stacked) {
return { ...s, data: stacked.top }
}
return s
})
// `createYScale` applies the shared overlay baseline clamp, degenerate `min === max`
// guard, log fallback, and `{ include }` goal-line domain extension — primary axis only.
+ // Percent-clamp only axes that actually carry bar series — a line/area-only axis (e.g. a
+ // series explicitly routed to the right axis) keeps its own data-derived scale instead of
+ // being forced onto [0, 1].
const scale = createYScale(axisValueSeries, dimensions, {
scaleType,
+ percentStack: barLayout === 'percent' && axisSeries.some((s) => seriesTypeOf(s) === 'bar'),
valueDomain: axisId === primaryAxisId ? valueDomain : undefined,
})
yAxes[axisId] = { scale, position }
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index ee05a5b803b7..02d157b835fe 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -406,15 +406,13 @@ export interface LineChartConfig extends ChartConfig {
}
/** Config for {@link ComboChart}, which draws bar, line, and area series together. `axisOrientation`
- * is omitted on purpose — bars require a band x-axis, so combo charts are vertical-only. Percent
- * layout is also unsupported: stack-as-percent is only meaningful when every series participates,
- * but lines/areas draw unstacked. */
+ * is omitted on purpose — bars require a band x-axis, so combo charts are vertical-only. */
export interface ComboChartConfig extends Omit<ChartConfig, 'axisOrientation'> {
/** Type used for series that don't set {@link Series.type}. Defaults to `'line'`. */
defaultSeriesType?: SeriesType
/** Layout applied to *bar* series only — lines and areas never stack or group. Defaults to
- * `'stacked'`. */
- barLayout?: 'stacked' | 'grouped'
+ * `'stacked'`. `'percent'` stacks bars to 100%; line/area series still plot at raw values. */
+ barLayout?: 'stacked' | 'grouped' | 'percent'
/** Corner radius for the cap of bar segments. Stacked bars only round the topmost segment. */
barCornerRadius?: number
/** Value-axis domain control for the primary axis — omit for data-derived auto-scaling. Used