: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(insights): render negative values on SQL combo charts and fix stacked tooltip sign (#70423)
Sam Pennington1b907e5ec400
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 44c05a1ef161..9f274ac72978 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -636,6 +636,10 @@ snapshots:hash: v1.k794b7964.2c24142bf0dcb6fa211ecf90a0376170006861061546ffc5fd66b7fe796dce4c.HBgbgdLit0-gs8WaX4skHdbK16P-EL0XVxF75QJLEmccomponents-hogcharts-combochart--bar-and-line--light:hash: v1.k794b7964.36ffba656428dfb67a84646e127df5c8af170c42655614b65c030c795464227c.dT9RoIihAlR2IYyBkbkyF9hW7-O3w72AftC8QTPfLNs+ components-hogcharts-combochart--diverging-stacked-bars-and-line--dark:+ hash: v1.k794b7964.c0dc1d567070aa2ead68125067b406f4ad704aecf64a18a54f2e5a90d37e1b82.xZcSWaw-21hRuL_yN4t3MYYM0E7wViaBje1ne2KjN7g+ components-hogcharts-combochart--diverging-stacked-bars-and-line--light:+ hash: v1.k794b7964.f19bec8c6396cf02562cd1b1f407b44d64bb96522cee356334762d2a30488bba.VanTOpQNNWWPSsljjEaUf_Leu1--iifOrZjHc1H8DBwcomponents-hogcharts-combochart--dual-y-axis-bar-and-line--dark:hash: v1.k794b7964.56a5e9cb9c602bc7340d990d2bb50ecedb0d2e12c261f911cad8d9434265fa38.twmudtXz0pbGRtgJS9NNL8PSURZCaHwumhcH_SToYFccomponents-hogcharts-combochart--dual-y-axis-bar-and-line--light:diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsxindex 2804457fad85..4ee8c9a868ad 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx@@ -9,8 +9,8 @@ import { useChartTheme } from 'lib/charts/hooks'import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'-import { formatDataWithSettings } from '../../dataVisualizationLogic'import { LineGraphProps } from './LineGraph'+import { formatSqlSeriesValue } from './sqlLineGraphAdapter'import { buildPieSeries, buildPieSlices, formatPieSliceCount } from './sqlPieGraphAdapter'const handleChartError = makeChartErrorHandler('sql-pie-chart')@@ -44,7 +44,7 @@ export const SqlPieGraph = ({const asPercent = (chartSettings.pie?.valueDisplay ?? 'absolute') === 'percentage'const absoluteFormatter = useCallback(- (value: number) => String(formatDataWithSettings(value, formattingSettings) ?? value),+ (value: number) => formatSqlSeriesValue(value, formattingSettings),[formattingSettings])diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.tsindex b38586a7fd0a..de2657446785 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts@@ -11,7 +11,7 @@ import { compactNumber } from 'lib/utils/numbers'import { ChartSettings, GoalLine } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'-import { AxisSeries } from '../../dataVisualizationLogic'+import { AxisSeries, AxisSeriesSettings } from '../../dataVisualizationLogic'import { AxisBreakdownSeries } from '../seriesBreakdownLogic'import { LineGraphProps } from './LineGraph'import {@@ -329,6 +329,15 @@ describe('sqlLineGraphAdapter', () => {expect(series.data).toEqual([1, NaN, 3])})+ it('keeps percent-styled columns out of the tooltip total, leaving other columns summable', () => {+ const [percent, plain] = buildSeries(+ [ySeries('growth', [2.4], { formatting: { style: 'percent' } }), ySeries('count', [10])],+ ChartDisplayType.ActionsLineGraph+ )+ expect(percent.visibility).toEqual({ total: false })+ expect(plain.visibility).toBeUndefined()+ })+it('only pins an explicit color, leaving palette assignment to quill otherwise', () => {const [withColor, withoutColor] = buildSeries([ySeries('a', [1], { display: { color: '#abcdef' } }), ySeries('b', [2])],@@ -483,6 +492,27 @@ describe('sqlLineGraphAdapter', () => {it('falls back to the raw value when formatting yields null', () => {expect(formatSqlSeriesValue(NaN)).toBe('NaN')})++ it.each<[string, number, AxisSeriesSettings | undefined, string]>([+ ['caps an unformatted float at 3 fraction digits', 22.222222222222, undefined, '22.222'],+ ['keeps unformatted integers untouched', 1234567, undefined, '1234567'],+ ['trims trailing zeros after capping', 0.30000000000000004, undefined, '0.3'],+ [+ 'caps a prefix-only column too (prefix does not round)',+ 22.222222222222,+ { formatting: { prefix: '$' } },+ '$22.222',+ ],+ [+ 'leaves rounding to an explicit decimalPlaces',+ 22.222222222222,+ { formatting: { decimalPlaces: 5 } },+ '22.22222',+ ],+ ['honors an explicit zero decimalPlaces', 22.222222222222, { formatting: { decimalPlaces: 0 } }, '22'],+ ])('%s', (_name, value, settings, expected) => {+ expect(formatSqlSeriesValue(value, settings)).toBe(expected)+ })})describe('hasAxisTickFormatting', () => {@@ -534,6 +564,16 @@ describe('sqlLineGraphAdapter', () => {const formatTotal = config.totalFormatter!expect(formatTotal(5000)).toBe('$5000')})++ it('formats the total with the first non-percent column, not a leading percent column', () => {+ // A percent column is excluded from the total sum, so borrowing its style would render+ // a sum of counts as e.g. "15,061.4%".+ const config = buildSqlTooltipConfig({}, [+ ySeries('growth', [2.4], { formatting: { style: 'percent' } }),+ ySeries('revenue', [1], { formatting: { prefix: '$' } }),+ ])+ expect(config.totalFormatter!(15059)).toBe('$15059')+ })})describe('buildLineChartConfig', () => {@@ -875,6 +915,31 @@ describe('sqlLineGraphAdapter', () => {expect(config.barLayout).toBe(expected)})+ it.each<[string, ChartDisplayType, ChartSettings, boolean]>([+ [+ 'enables divergingStack for stacked bars so negatives render below zero',+ ChartDisplayType.ActionsStackedBar,+ {},+ true,+ ],+ [+ 'disables divergingStack for percent-stacked bars',+ ChartDisplayType.ActionsStackedBar,+ { stackBars100: true },+ false,+ ],+ ['disables divergingStack for grouped bars', ChartDisplayType.ActionsBar, {}, false],+ ])('%s', (_name, visualizationType, chartSettings, expected) => {+ const config = buildComboChartConfig({+ xData: dateXData,+ chartSettings,+ timezone: 'UTC',+ visualizationType,+ ySeriesData: [ySeries('a', [1, -2])],+ })+ expect(config.divergingStack).toBe(expected)+ })+it('maps the axis-border toggles to per-edge showAxisLines for combo', () => {const config = buildComboChartConfig({xData: dateXData,diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.tsindex 0c260c816c40..e36a3667ec46 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts@@ -234,6 +234,9 @@ export function buildSeries(yData: SqlLineYSeries[], visualizationType: ChartDismeta: { settings },// Per-series type; ignored by the single-type line/bar charts, read by ComboChart.type,+ // A percent-styled column doesn't sum meaningfully with the other columns, so keep it+ // out of the tooltip's total row (matches the legacy renderer).+ ...(settings?.formatting?.style === 'percent' ? { visibility: { total: false } } : {}),// Only pin an explicit color; otherwise let quill assign palette colors by index....(color ? { color } : {}),...(settings?.display?.yAxisPosition === 'right' ? { yAxisId: 'right' } : {}),@@ -244,9 +247,20 @@ export function buildSeries(yData: SqlLineYSeries[], visualizationType: ChartDis})}-/** Formats a tooltip value with a column's display settings. */+/** Formats a chart display value (tooltip rows/total, value labels, custom axis ticks) with a+ * column's display settings. Values without an explicit style or decimal-place count are capped+ * at 3 fraction digits — a computed column (e.g. a ratio) otherwise renders with full float+ * precision (`22.222222222222`). The results table keeps full precision on purpose; this rounding+ * is chart-display only. */export function formatSqlSeriesValue(value: number, settings?: AxisSeriesSettings): string {- return String(formatDataWithSettings(value, settings) ?? value)+ const formatting = settings?.formatting+ // Styled values round inside formatDataWithSettings. Unstyled values are capped here — at the+ // column's explicit decimalPlaces when set (formatDataWithSettings skips a falsy 0, so a+ // zero-decimal column would otherwise keep its fraction digits), else at 3. Prefix/suffix+ // don't round, so they don't opt out.+ const hasStyle = !!formatting && (formatting.style ?? 'none') !== 'none'+ const display = hasStyle || !Number.isFinite(value) ? value : Number(value.toFixed(formatting?.decimalPlaces ?? 3))+ return String(formatDataWithSettings(display, settings) ?? display)}const isRightAxisSeries = (series: SqlLineYSeries): boolean => series.settings?.display?.yAxisPosition === 'right'@@ -280,7 +294,11 @@ export function buildSqlTooltipConfig(chartSettings: ChartSettings,ySeriesData?: SqlLineYSeries[] | null): TooltipConfig {- const totalSettings = ySeriesData?.[0]?.settings+ // The total sums the non-percent columns (percent columns are excluded via+ // `visibility.total` in buildSeries), so it must format with a column that's actually in the+ // sum — a blind `[0]` borrows a percent column's style and renders a sum of counts as+ // "15,061.4%". Matches the legacy renderer's first-summable-column choice.+ const totalSettings = ySeriesData?.find((series) => series.settings?.formatting?.style !== 'percent')?.settingsreturn {enabled: true,pinnable: true,@@ -523,6 +541,9 @@ export function buildComboChartConfig({goalLines: schemaGoalLinesToConfigs(goalLines),showAxisLines: buildAxisLinesConfig(chartSettings),barLayout,+ // Stacked bars must preserve negative values (SQL results can be negative) so they render+ // below the zero baseline instead of being clamped to 0 — mirrors buildBarChartConfig.+ divergingStack: barLayout === 'stacked',// 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),diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.tsindex cf7425c60773..62f4cf16f291 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.ts@@ -4,9 +4,10 @@ import { getSeriesColor } from 'lib/colors'import { ChartDisplayType } from '~/types'-import { AxisSeries, AxisSeriesSettings, formatDataWithSettings } from '../../dataVisualizationLogic'+import { AxisSeries, AxisSeriesSettings } from '../../dataVisualizationLogic'import { AxisBreakdownSeries } from '../seriesBreakdownLogic'import { LineGraphProps } from './LineGraph'+import { formatSqlSeriesValue } from './sqlLineGraphAdapter'export interface PieSlice {label: string@@ -100,7 +101,7 @@ export const formatPieSliceCount = (settings?: AxisSeriesSettings,asPercent = false): string => {- const formatted = String(formatDataWithSettings(value, settings) ?? value)+ const formatted = formatSqlSeriesValue(value, settings)const shareOfTotal = total ? parseFloat(((value / total) * 100).toFixed(1)) : 0if (asPercent) {// Lead with the share, keep the absolute value as a secondary detaildiff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 46439f28d4d4..e5d208373c63 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -70,7 +70,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`, `TrendLineOverlay`, `HighlightedRange`) compose as children.- `HighlightedRange` draws a translucent box spanning an x-axis range — pass `start`/`end` as data indices or labels (e.g. straight from `onDateRangeZoom`'s `startIndex`/`endIndex`). Use it to mirror an external selection (the rows visible in a paired virtualized list, a picked time window) onto the chart. On band (bar) charts the box covers the endpoints' full bands; on point (line) charts it runs point to point. `color`, `fillOpacity`, and `borderOpacity` tune the look (`borderOpacity: 0` drops the edge border); it clamps to the plot area and renders null when an endpoint doesn't resolve.-- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `labelFormatter`, `labelRenderer`, `showHeader`, `showTotal`, `totalLabel`, `totalFormatter`, `sortedByValue`, `hideZeroRows`, `onRowClick`, and `footer`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration); it may return a node, not just a string (e.g. a property-formatted value). `labelFormatter` transforms the raw x-axis label shown in the tooltip header (e.g. convert an ISO datetime string to "Jun 24, 10:00"); on time-series charts with `xAxis.timezone` + `interval` set it defaults to an interval-aware date formatter that includes the weekday for single-day buckets ("Sat, Jun 6, 2026", "Sat, Jun 6, 14:00"; week/month buckets span days, so "Jun 1, 2026", "Jun 2026"), so the header matches the auto-formatted axis ticks — an explicit `labelFormatter` still wins. `labelRenderer` overrides how each row's label renders (defaults to the series label) — use for richer labels than a plain string, e.g. breakdown-value pills. `showHeader` (default true) toggles the header label row — pass false for charts without a meaningful header (pie slices, aggregated single-column bars). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) from the sum and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. `sortedByValue` sorts rows by value descending so the highest value appears first. `hideZeroRows` drops rows whose value is exactly `0` (e.g. lifecycle statuses absent for a period), so the tooltip lists only series with data at the hovered point. `onRowClick` makes each series row clickable (firing with the row's `seriesData` entry) — the tooltip must be pinned for clicks to land, since an unpinned tooltip is `pointer-events: none`; use it to open a per-series drill-down (e.g. the persons modal). `footer` renders arbitrary content below all rows (with a divider) — useful for "click to inspect" hints. A formatter taking only `value` stays compatible — the extra arg is ignored.+- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `labelFormatter`, `labelRenderer`, `showHeader`, `showTotal`, `totalLabel`, `totalFormatter`, `sortedByValue`, `hideZeroRows`, `onRowClick`, and `footer`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration); it may return a node, not just a string (e.g. a property-formatted value). `labelFormatter` transforms the raw x-axis label shown in the tooltip header (e.g. convert an ISO datetime string to "Jun 24, 10:00"); on time-series charts with `xAxis.timezone` + `interval` set it defaults to an interval-aware date formatter that includes the weekday for single-day buckets ("Sat, Jun 6, 2026", "Sat, Jun 6, 14:00"; week/month buckets span days, so "Jun 1, 2026", "Jun 2026"), so the header matches the auto-formatted axis ticks — an explicit `labelFormatter` still wins. `labelRenderer` overrides how each row's label renders (defaults to the series label) — use for richer labels than a plain string, e.g. breakdown-value pills. `showHeader` (default true) toggles the header label row — pass false for charts without a meaningful header (pie slices, aggregated single-column bars). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) and series with `visibility.total: false` (values that don't sum meaningfully with the rest, e.g. a percentage column alongside counts — the row itself still renders) from the sum, and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. `sortedByValue` sorts rows by value descending so the highest value appears first. `hideZeroRows` drops rows whose value is exactly `0` (e.g. lifecycle statuses absent for a period), so the tooltip lists only series with data at the hovered point. `onRowClick` makes each series row clickable (firing with the row's `seriesData` entry) — the tooltip must be pinned for clicks to land, since an unpinned tooltip is `pointer-events: none`; use it to open a per-series drill-down (e.g. the persons modal). `footer` renders arbitrary content below all rows (with a divider) — useful for "click to inspect" hints. A formatter taking only `value` stays compatible — the extra arg is ignored.- BarChart sets `TooltipContext.hoveredSeriesKey` — the key of the bar/segment under the cursor (stacked: the visible segment; grouped: the band-slot hit). Stacked `seriesData` keeps every segment in declaration order, so a custom tooltip that describes a single segment (e.g. a funnel breakdown) must select by `hoveredSeriesKey`, not `seriesData[0]`. It may reference a series hidden from `seriesData` via `visibility.tooltip: false` (e.g. a drop-off filler), and is `undefined` on other chart types and pinned rebuilds without a cursor.- To tune the built-in tooltip **without writing a render prop**, put those same fields on `config.tooltip` (`{ enabled, pinnable, resolveClickToNearestSeries, placement, valueFormatter, labelFormatter, showTotal, totalLabel, totalFormatter, sortedByValue }`). When no `tooltip` render prop is supplied, the chart renders `DefaultTooltip` with them applied; a render prop, if given, owns content entirely and these are ignored. Prefer config for "format each row / add a total" cases (e.g. SQL insights pass per-column formatters this way) and reach for the render prop only for genuinely custom tooltip markup (e.g. adding a `footer` hint). `resolveClickToNearestSeries` (default false) changes what a click on a `pinnable` multi-series chart does: instead of always pinning first (letting the user then click a specific row), it resolves the series nearest the cursor and fires `onPointClick` for it directly — skip pinning only where a click's target series is visually unambiguous by position (e.g. funnel breakdown areas, one per breakdown value); leave it off where series overlap closely and a wrong guess is costly (e.g. trend lines).- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).@@ -81,7 +81,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' | 'percent'`) 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'`), `divergingStack` (stacked only — negative bar values stack below the zero baseline instead of being clamped to 0, same semantics as `BarsConfig.divergingStack`), 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. `hide` and `startAtZero` are honored per entry (bar-series axes keep their zero baseline). 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`/`TimeSeriesComboChart` take the same `yAxis` array; a sole axis pinned `right` renders on the right on every chart type.diff --git a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.stories.tsx b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.stories.tsxindex 0b8dec83929e..cfb149ad2c3e 100644--- a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.stories.tsx+++ b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.stories.tsx@@ -60,6 +60,26 @@ export const StackedBarsAndLine: Story = {},}+/** Stacked bars with negative values stack below the zero baseline (`divergingStack`) instead of+ * being clamped to 0 — e.g. a SQL insight plotting an upvote count against a negated downvote+ * count, with a ratio line on top. */+export const DivergingStackedBarsAndLine: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series[] = [+ { key: 'high', label: 'High ratings', color: '', data: [22, 24, 28, 26, 30, 32, 31], type: 'bar' },+ { key: 'low', label: 'Low ratings', color: '', data: [-8, -6, -9, -5, -7, -4, -6], type: 'bar' },+ { key: 'ratio', label: 'Bad rating share', color: '', data: [27, 20, 24, 16, 19, 11, 16], type: 'line' },+ ]+ const config: ComboChartConfig = { showGrid: true, barLayout: 'stacked', divergingStack: true }+ return (+ <Stage>+ <ComboChart series={series} labels={DAYS} config={config} theme={theme} />+ </Stage>+ )+ },+}+export const GroupedBarsAndLine: Story = {render: () => {const theme = useReactiveTheme()diff --git a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.test.tsx b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.test.tsxindex af029b1fe4fb..4819f6e8330b 100644--- a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.test.tsx@@ -154,6 +154,30 @@ describe('ComboChart', () => {expect(tooltip.series.b.value).toBe(15)expect(tooltip.series.l.value).toBe(60)})++ it('divergingStack keeps negative bar values signed in the tooltip', async () => {+ // Without divergingStack the negative series is clamped to 0 (no bar, tooltip 0);+ // with it, the bar stacks below zero and the tooltip must show the raw negative —+ // not the positive segment height.+ const series: Series[] = [+ { key: 'pos', label: 'Pos', data: [40, 60, 50], type: 'bar' },+ { key: 'neg', label: 'Neg', data: [-20, -30, -10], type: 'bar' },+ { key: 'l', label: 'L', data: [5, 10, 15], type: 'line' },+ ]+ const { chart } = renderHogChart(+ <ComboChart+ series={series}+ labels={LABELS}+ theme={THEME}+ config={{ barLayout: 'stacked', divergingStack: true }}+ />+ )+ chart.hoverAtIndex(1)+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.series.pos.value).toBe(60)+ expect(tooltip.series.neg.value).toBe(-30)+ expect(tooltip.series.l.value).toBe(10)+ })})describe('children & error boundary', () => {diff --git a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsxindex 552031283d14..11a69bb7f8f5 100644--- a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx+++ b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx@@ -30,6 +30,7 @@ import {buildSegmentResolveValue,buildStackedBottomValue,buildStackedPositionValue,+ computeDivergingStackData,computePercentStackData,computeStackData,computeTopStackedKeyByAxis,@@ -94,6 +95,7 @@ function ComboChartInner<Meta = unknown>({showGrid = false,showAxisLines = false,barLayout = 'stacked',+ divergingStack = false,barCornerRadius = DEFAULT_BAR_CORNER_RADIUS,defaultSeriesType = DEFAULT_SERIES_TYPE,xTickFormatter,@@ -120,10 +122,13 @@ function ComboChartInner<Meta = unknown>({if (barSeries.length === 0) {return undefined}- return barLayout === 'percent'- ? computePercentStackData(barSeries, labels)+ if (barLayout === 'percent') {+ return computePercentStackData(barSeries, labels)+ }+ return divergingStack+ ? computeDivergingStackData(barSeries, labels): computeStackData(barSeries, labels)- }, [barLayout, series, labels, seriesTypeOf])+ }, [barLayout, divergingStack, 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.diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsxindex c47d2fd2c285..1b6dd826992c 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx@@ -33,6 +33,9 @@ export interface TimeSeriesComboChartConfig {/** Layout applied to *bar* series only — lines and areas never stack or group. Defaults to* `'stacked'`. */barLayout?: ComboChartConfig['barLayout']+ /** Stacked layout only — stack negative bar values below the zero baseline instead of+ * clamping them to 0. See {@link ComboChartConfig.divergingStack}. */+ divergingStack?: boolean/** Stacked bars only round the topmost segment. */barCornerRadius?: number/** Show a vertical crosshair line that follows the cursor. */@@ -89,6 +92,7 @@ export function TimeSeriesComboChart<Meta = unknown>({goalLines,defaultSeriesType,barLayout,+ divergingStack,barCornerRadius,showCrosshair,showGrid,@@ -131,6 +135,7 @@ export function TimeSeriesComboChart<Meta = unknown>({showCrosshair,defaultSeriesType,barLayout,+ divergingStack,barCornerRadius,tooltip: timeSeriesTooltipConfig,valueDomain,diff --git a/packages/quill/packages/charts/src/core/combo-scales.test.ts b/packages/quill/packages/charts/src/core/combo-scales.test.tsindex f2c65230ca98..7164ddbf24bc 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 { computePercentStackData, computeStackData } from './scales'+import { computeDivergingStackData, computePercentStackData, computeStackData } from './scales'import type { Series, SeriesType } from './types'import { DEFAULT_Y_AXIS_ID } from './types'@@ -130,6 +130,21 @@ describe('combo-scales', () => {expect(domainMax).toBeGreaterThanOrEqual(60)})+ it('extends the domain below zero for a diverging stack (bottoms count too)', () => {+ // A diverging stack's negative segments live in `bottom` — if only tops fed the+ // domain, negative bars would render outside the plot.+ const pos = makeSeries({ key: 'pos', data: [10, 20, 30], type: 'bar' })+ const neg = makeSeries({ key: 'neg', data: [-40, -20, -10], type: 'bar' })+ const scales = createComboScales([pos, neg], ['a', 'b', 'c'], dimensions, {+ barLayout: 'stacked',+ seriesTypeOf: typeOfWithDefault('line'),+ barStackedData: computeDivergingStackData([pos, neg], ['a', 'b', 'c']),+ })+ const [domainMin, domainMax] = scales.y.domain()+ expect(domainMin).toBeLessThanOrEqual(-40)+ expect(domainMax).toBeGreaterThanOrEqual(30)+ })+it('keeps bar and line on the same axis under one value scale', () => {const bar = makeSeries({ key: 'b', data: [100], type: 'bar' })const line = makeSeries({ key: 'l', data: [200], type: 'line' })diff --git a/packages/quill/packages/charts/src/core/combo-scales.ts b/packages/quill/packages/charts/src/core/combo-scales.tsindex 295c99b97f29..53d218598d45 100644--- a/packages/quill/packages/charts/src/core/combo-scales.ts+++ b/packages/quill/packages/charts/src/core/combo-scales.ts@@ -100,14 +100,20 @@ export function createComboScales(const yAxes: ComboScaleSet['yAxes'] = {}for (const { axisId, position } of axisPositions) {const axisSeries = seriesByAxis.get(axisId) ?? []- // Per-axis contributions: bars contribute their stacked-top values when stacked, raw- // otherwise; lines/areas always contribute raw. The value scale spans the union.- const axisValueSeries: Series[] = axisSeries.map((s) => {+ // Per-axis contributions: bars contribute their stacked-band edges when stacked, raw+ // otherwise; lines/areas always contribute raw. The value scale spans the union. Both+ // band edges count: tops extend the domain upward, bottoms extend it below zero for+ // diverging stacks (a non-diverging bottom never leaves [0, top], so including it is+ // harmless there).+ const axisValueSeries: Series[] = axisSeries.flatMap((s) => {const stacked = barStackedData?.get(s.key)if (seriesTypeOf(s) === 'bar' && (barLayout === 'stacked' || barLayout === 'percent') && stacked) {- return { ...s, data: stacked.top }+ return [+ { ...s, data: stacked.top },+ { ...s, key: `${s.key}__bottom`, data: stacked.bottom },+ ]}- return s+ return [s]})// `createYScale` applies the shared overlay baseline clamp, degenerate `min === max`// guard, log fallback, and `{ include }` goal-line domain extension — primary axis only.diff --git a/packages/quill/packages/charts/src/core/scales.test.ts b/packages/quill/packages/charts/src/core/scales.test.tsindex d7718434668f..537cdecc69c8 100644--- a/packages/quill/packages/charts/src/core/scales.test.ts+++ b/packages/quill/packages/charts/src/core/scales.test.ts@@ -801,6 +801,17 @@ describe('hog-charts scales', () => {expect(resolve(negSeries, 1)).toBe(0)})+ it('keeps the sign of a negative segment in a diverging stack', () => {+ // stackOffsetDiverging lays a -50 segment out as [bottom = -50, top = 0] — the same+ // top > bottom ordering as a positive segment — so `top - bottom` alone would report+ // +50 in the tooltip for a bar drawn below zero.+ const pos = makeSeries({ key: 'pos', data: [10, 20] })+ const neg = makeSeries({ key: 'neg', data: [-5, -50] })+ const resolve = buildSegmentResolveValue(computeDivergingStackData([pos, neg], ['x', 'y']))!+ expect(resolve(pos, 1)).toBe(20)+ expect(resolve(neg, 1)).toBe(-50)+ })+it('returns each series own fraction for a percent stack, not the cumulative fraction', () => {// a=20, b=15 at index 1 → total 35. b sits on top of a, so b's cumulative top is 1.0,// but its own fraction is 15/35 — that segment is what the tooltip must report.diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.tsindex 50791c2da4ab..07f9aa36a5c0 100644--- a/packages/quill/packages/charts/src/core/scales.ts+++ b/packages/quill/packages/charts/src/core/scales.ts@@ -481,14 +481,18 @@ export function buildSegmentResolveValue(}return (s, dataIndex) => {const band = stackedData.get(s.key)+ const raw = s.data[dataIndex]if (band) {const top = band.top[dataIndex]const bottom = band.bottom[dataIndex]if (Number.isFinite(top) && Number.isFinite(bottom)) {- return top - bottom+ const size = top - bottom+ // A diverging stack lays a negative segment out as [bottom = cumulative,+ // top = previous] with top > bottom — the same ordering as a positive segment —+ // so `top - bottom` alone loses the sign. Restore it from the raw value.+ return typeof raw === 'number' && raw < 0 && size > 0 ? -size : size}}- const raw = s.data[dataIndex]return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0}}diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex a2bad77b85ec..52038f447042 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -125,6 +125,10 @@ export interface Series<Meta = unknown> {excluded?: boolean/** Whether the series appears in the tooltip's seriesData. Defaults to true. */tooltip?: boolean+ /** Whether the series' value counts toward the built-in tooltip's total row — its own row+ * still renders. Use for series whose values don't sum meaningfully with the rest (e.g. a+ * percentage column alongside counts). Defaults to true. */+ total?: boolean/** Whether the ValueLabels overlay draws a label for this series. Defaults to true. */valueLabel?: boolean}@@ -466,6 +470,10 @@ export interface ComboChartConfig extends Omit<ChartConfig, 'axisOrientation'> {/** Layout applied to *bar* series only — lines and areas never stack or group. Defaults to* `'stacked'`. `'percent'` stacks bars to 100%; line/area series still plot at raw values. */barLayout?: 'stacked' | 'grouped' | 'percent'+ /** Stacked layout only — use d3.stackOffsetDiverging so negative bar values stack below the+ * zero baseline (positives above). Default `false` clamps negatives to 0. Mirrors+ * {@link BarsConfig.divergingStack}. */+ divergingStack?: boolean/** 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. Useddiff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsxindex 862d21f0ddb3..cd84d5bdd393 100644--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.test.tsx@@ -129,6 +129,22 @@ describe('DefaultTooltip', () => {expect(screen.queryByText((1035).toLocaleString())).toBeNull()})+ it('excludes visibility.total: false series from the sum but still renders its row', () => {+ // A percentage column alongside counts: its 2.4 must not leak into the counts' total.+ const withPercent: TooltipContext['seriesData'] = [+ ...TWO_SERIES,+ {+ series: { key: 'pct', label: 'Rate', data: [], visibility: { total: false } },+ value: 2.4,+ color: '#222',+ },+ ]+ renderTooltip({ showTotal: true }, withPercent)+ expect(screen.getAllByText('Rate').length).toBeGreaterThan(0)+ screen.getByText((35).toLocaleString())+ expect(screen.queryByText((37.4).toLocaleString())).toBeNull()+ })+it('is suppressed when only one non-overlay series remains', () => {const oneRealOneOverlay: TooltipContext['seriesData'] = [{ series: { key: 'a', label: 'A', data: [] }, value: 10, color: '#000' },diff --git a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsxindex 408a30ffafa9..a9248ab103ce 100644--- a/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx+++ b/packages/quill/packages/charts/src/overlays/DefaultTooltip.tsx@@ -26,8 +26,10 @@ export interface DefaultTooltipProps<Meta = unknown> extends TooltipContext<Meta* header (e.g. pie slices, aggregated single-column bars). */showHeader?: boolean/** Append a footer row summing the visible series at the hovered point. `overlay` series- * (e.g. goal lines) are excluded from the sum, and the row is suppressed when fewer than two- * summable series remain — a single-series total would just restate the one row. */+ * (e.g. goal lines) and series with `visibility.total: false` (values that don't sum+ * meaningfully, e.g. a percentage alongside counts) are excluded from the sum, and the row is+ * suppressed when fewer than two summable series remain — a single-series total would just+ * restate the one row. */showTotal?: boolean/** Label for the total row. Defaults to 'Total'. */totalLabel?: string@@ -69,7 +71,7 @@ export function DefaultTooltip<Meta = unknown>({: visible[0]?.yPixel != null? [...visible].sort((a, b) => (a.yPixel ?? Infinity) - (b.yPixel ?? Infinity)): visible- const summable = rows.filter((s) => !s.series.overlay)+ const summable = rows.filter((s) => !s.series.overlay && s.series.visibility?.total !== false)const closestKey =hoverPosition != null && rows.length > 1 ? findClosestSeriesKey(rows, hoverPosition.y) : nullconst renderTotal = showTotal && summable.length > 1diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.test.tsxindex 67a5e36dd5dc..d1f7ea953085 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.test.tsx@@ -100,7 +100,9 @@ describe('TrendsLifecycleChart', () => {expect(tooltip.row('New')).toBeTruthy()expect(tooltip.row('Returning')).toBeTruthy()expect(tooltip.row('Resurrecting')).toBeTruthy()- expect(tooltip.row('Dormant')).toBeTruthy()+ // Dormant data is emitted negative (-2 at this index) so it stacks below zero, but the+ // tooltip shows the magnitude — the "Dormant" label carries the direction.+ expect(tooltip.row('Dormant')).toBe('2')// "Users" is the group type label.expect(tooltip.element.textContent).toMatch(/Users/)})diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsxindex 917eb8693986..21c5fe28ff05 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx@@ -96,6 +96,10 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi[trendsFilter, baseCurrency])+ // Dormant counts are emitted negative so they stack below the zero baseline, but the tooltip+ // shows the magnitude — the "Dormant" label already carries the direction.+ const renderTooltipCount = useCallback((value: number) => formatValue(Math.abs(value)), [formatValue])+const valueLabelFormatter = useMemo(() =>buildLifecycleValueLabelFormatter(formatValue, {@@ -198,6 +202,7 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLibaseCurrency,groupTypeLabel: 'Users' as const,renderSeriesOverride: renderLifecycleSeriesLabel,+ renderCount: renderTooltipCount,}const onRowClick = canHandleClick? (datum: SeriesDatum) => {@@ -219,6 +224,7 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLitrendsFilter,formula,baseCurrency,+ renderTooltipCount,quillTooltipEnabled,canHandleClick,clickDeps,