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(insights): show percentages on lifecycle series (#60472)

Sam Pennington288e407d0497
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 211a1503aafd..6af2d9fa3127 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -484,6 +484,10 @@ snapshots:
hash: v1.k794b7964.a9bbe5488b1e8b8f3dd2fde96564a7472ef6c8b0c9a1ec70b7629886ed165b1e.uRnihlAOH_HQAHkOvWnWU2o8teXidFawDVHP0lXYar8
components-hogcharts-barchart--horizontal-grouped--light:
hash: v1.k794b7964.beb8d534a94663d944290398d7c2946b739d8d6ad9af6e7cd5b5fa86eb53d4d9.0pZ70Z9dzCO4WrZNoZmeVP0ISM0vy8_QvWUggLAs-6o
+ components-hogcharts-barchart--horizontal-wide-value-labels--dark:
+ hash: v1.k794b7964.de748c4ee5a5eefdd95047814f7116148c8f460de13decb3bdc023a4e5252f4c.ZZKmFWvCjv_YANsXJ5UHe7d3ny1Cfpi0X_n4UT5Jrlg
+ components-hogcharts-barchart--horizontal-wide-value-labels--light:
+ hash: v1.k794b7964.a5c6fd8f9d7fbbc9753e5fc9174ed32c0cc9be8f3413987743f5f757b4c22429.mCdlAsg4goJO4WlH2efiupI0b5igP3z2k9roDJtHNbY
components-hogcharts-barchart--incomplete-period--dark:
hash: v1.k794b7964.7d9ab6b6cc8c4937ae0db54e48fa9d49f38e653230aefeeb2e061285aa9e3c31.7A_9Vb8PAwK7BOANh_9R08598qOpiD3_BqCxBkOyPYI
components-hogcharts-barchart--incomplete-period--light:
@@ -2220,6 +2224,14 @@ snapshots:
hash: v1.k794b7964.34ee21c93cb09cc3cbd620bf960e4ea4553c38b56eca794f6f8ebe3fb645ba93.4sjTzpM-9CeL36Lb6yIbgNPV6jDX_sxBEU9IaMF8KIc
insights-trendslifecyclechart--stacked-with-legend--light:
hash: v1.k794b7964.60416255e840786210d0236e71ef9eb3771d0d1d73161355913bccbf72449afe.WVEhZOzCzFz_et6-07xYPEsrsNf64sF5BSPw8hASzYM
+ insights-trendslifecyclechart--stacked-with-percentages-on-series--dark:
+ hash: v1.k794b7964.066d840ca1e395d54a0cecd1a2d638e4c0f9f50a85e35d05943b8aab05ef3663.-CgSnE6BqasYjFHauHFmNe7NnuLrnXDhw639DriD93w
+ insights-trendslifecyclechart--stacked-with-percentages-on-series--light:
+ hash: v1.k794b7964.b93de16cc88441e583a80723ff9c5c94d48dd856fbbc14006df89b42d7d91346.IDcKZlFStpB5VZvD353kvZKpIuCiK-KRw2sIeb-zKHY
+ insights-trendslifecyclechart--stacked-with-percentages-only-on-series--dark:
+ hash: v1.k794b7964.c4f0153c157df124db42795257ee1672c6d8178d633709371f313d1141a29877.qMeHM6cGtOoXmyczxy8XuxUzTPFqkQkb3nqJfDQwl6A
+ insights-trendslifecyclechart--stacked-with-percentages-only-on-series--light:
+ hash: v1.k794b7964.219ee2db573c400c2aef857ed9de1838584b6e1d97d06955850efa2b4c0d40c3.UELtDSu_qZZqoBeINsxpiJ6Dwm1SwMG4VGWPLtDQU20
insights-trendslifecyclechart--stacked-with-values-on-series--dark:
hash: v1.k794b7964.bc4c1f78bb5bc68955a459d215fca4bd5d459ea3992b5eca13ad40ee39ee4366.OX1_Hj6tCAyTwV7c24Xu-mTkSDv6PE_e0CofnkyQETM
insights-trendslifecyclechart--stacked-with-values-on-series--light:
@@ -2232,6 +2244,10 @@ snapshots:
hash: v1.k794b7964.c97d90ab0c373436972e47b4f34ecaae07be8497c52bbf06717aae714399d251.-UDtNIEVgoDj4eP2ORpqfdI7mI4QOpETAGTbvsdouJY
insights-trendslifecyclechart--unstacked-with-legend--light:
hash: v1.k794b7964.4cb9e27ef90ccb219404af7ef3eeab2430fbf687b4b0eaf723d1e33509c70668.rPDT6IL8vTnQdAImKGwbivsRJmeYnIqhcPM-iixJPsk
+ insights-trendslifecyclechart--unstacked-with-percentages-on-series--dark:
+ hash: v1.k794b7964.7a72d80762095624805a88d26e79c7958d5ca70f25dfcc45ff4e96ec20f0f03f.xGyzAe5CvEkM154Hy0OttbI9OptKg8Ob_CHZeXdpqA8
+ insights-trendslifecyclechart--unstacked-with-percentages-on-series--light:
+ hash: v1.k794b7964.a966d2fc749238e67c4cdac66d61f39bd526101e87111e328cd5e5947f8abd52.ipbWS0qB-gKn6BUAonblaSR-pFfOCOIj6On4TheTDNg
insights-trendslifecyclechart--unstacked-with-values-on-series--dark:
hash: v1.k794b7964.d11ad52519f19f8f938e0419e78f5c98a6097fa501cfea43d2baa3ba8aea3948.F_NC7gkGfnvJ6y7t6_cvfdk-dqMjcfJvhSYyg_Bn5bg
insights-trendslifecyclechart--unstacked-with-values-on-series--light:
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
index 05fa3ad651a3..1c765d4aba0c 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
@@ -23,6 +23,7 @@ import { axisLabel } from 'scenes/insights/aggregationAxisFormat'
import { AxisLabelsFilter } from 'scenes/insights/EditorFilters/AxisLabelsFilter'
import { HideIncompleteConversionWindowPeriodsFilter } from 'scenes/insights/EditorFilters/HideIncompleteConversionWindowPeriodsFilter'
import { HideWeekendsFilter } from 'scenes/insights/EditorFilters/HideWeekendsFilter'
+import { LifecyclePercentagesFilter } from 'scenes/insights/EditorFilters/LifecyclePercentagesFilter'
import { LifecycleStackingFilter } from 'scenes/insights/EditorFilters/LifecycleStackingFilter'
import { PercentStackViewFilter } from 'scenes/insights/EditorFilters/PercentStackViewFilter'
import { ResultCustomizationByPicker } from 'scenes/insights/EditorFilters/ResultCustomizationByPicker'
@@ -143,9 +144,13 @@ export function InsightDisplayConfig(): JSX.Element {
const isLineGraph = isLineDisplay && !isCumulativeLineDisplay
const isLinearScale = !yAxisScaleType || yAxisScaleType === 'linear'
- const { showValuesOnSeries, mightContainFractionalNumbers, showConfidenceIntervals, showMovingAverage } = useValues(
- trendsDataLogic(insightProps)
- )
+ const {
+ showValuesOnSeries,
+ showPercentagesOnSeries,
+ mightContainFractionalNumbers,
+ showConfidenceIntervals,
+ showMovingAverage,
+ } = useValues(trendsDataLogic(insightProps))
const isBoxPlot = display === ChartDisplayType.BoxPlot
const advancedOptions: LemonMenuItems = [
@@ -211,6 +216,7 @@ export function InsightDisplayConfig(): JSX.Element {
: [
...(isLifecycle ? [{ label: () => <LifecycleStackingFilter /> }] : []),
...(supportsValueOnSeries ? [{ label: () => <ValueOnSeriesFilter /> }] : []),
+ ...(isLifecycle ? [{ label: () => <LifecyclePercentagesFilter /> }] : []),
...(supportsPercentStackView ? [{ label: () => <PercentStackViewFilter /> }] : []),
...(supportsBarValueStacking ? [{ label: () => <StackBreakdownFilter /> }] : []),
...(hasLegend ? [{ label: () => <ShowLegendFilter /> }] : []),
@@ -387,6 +393,7 @@ export function InsightDisplayConfig(): JSX.Element {
const advancedOptionsCount: number =
(showSmoothing && (trendsFilter?.smoothingIntervals ?? 1) !== 1 ? 1 : 0) +
(supportsValueOnSeries && showValuesOnSeries ? 1 : 0) +
+ (isLifecycle && showPercentagesOnSeries ? 1 : 0) +
(showPercentStackView ? 1 : 0) +
(!showPercentStackView &&
isTrends &&
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 026b09482531..4d03ebb10546 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -24352,6 +24352,10 @@
"default": false,
"type": "boolean"
},
+ "showPercentagesOnSeries": {
+ "description": "Append per-band percentage to each value label (e.g. `580 (42%)`). Requires `showValuesOnSeries` — on its own it has no visible effect.",
+ "type": "boolean"
+ },
"showValuesOnSeries": {
"type": "boolean"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 2cf8229db2be..e38bbc2fe375 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1933,6 +1933,9 @@ export type LifecycleFilterLegacy = Omit<LifecycleFilterType, keyof FilterType |
export type LifecycleFilter = {
showValuesOnSeries?: LifecycleFilterLegacy['show_values_on_series']
+ /** Append per-band percentage to each value label (e.g. `580 (42%)`). Requires
+ * `showValuesOnSeries` — on its own it has no visible effect. */
+ showPercentagesOnSeries?: boolean
toggledLifecycles?: LifecycleFilterLegacy['toggledLifecycles']
/** @default false */
showLegend?: LifecycleFilterLegacy['show_legend']
diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.ts
index eba8cf071135..3fc03052cdaa 100644
--- a/frontend/src/queries/utils.ts
+++ b/frontend/src/queries/utils.ts
@@ -602,6 +602,13 @@ export const getShowValuesOnSeries = (query: InsightQueryNode): boolean | undefi
return undefined
}
+export const getShowPercentagesOnSeries = (query: InsightQueryNode): boolean | undefined => {
+ if (isLifecycleQuery(query)) {
+ return query.lifecycleFilter?.showPercentagesOnSeries
+ }
+ return undefined
+}
+
export const getYAxisScaleType = (query: InsightQueryNode): string | undefined => {
if (isTrendsQuery(query)) {
return query.trendsFilter?.yAxisScaleType
diff --git a/frontend/src/scenes/insights/EditorFilters/LifecyclePercentagesFilter.tsx b/frontend/src/scenes/insights/EditorFilters/LifecyclePercentagesFilter.tsx
new file mode 100644
index 000000000000..556048764017
--- /dev/null
+++ b/frontend/src/scenes/insights/EditorFilters/LifecyclePercentagesFilter.tsx
@@ -0,0 +1,24 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+
+import { insightLogic } from '../insightLogic'
+
+export function LifecyclePercentagesFilter(): JSX.Element {
+ const { insightProps } = useValues(insightLogic)
+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))
+ const { showPercentagesOnSeries } = useValues(insightVizDataLogic(insightProps))
+
+ return (
+ <LemonCheckbox
+ className="p-1 px-2"
+ checked={!!showPercentagesOnSeries}
+ onChange={() => {
+ updateInsightFilter({ showPercentagesOnSeries: !showPercentagesOnSeries })
+ }}
+ label={<span className="font-normal">Show percentages on series</span>}
+ size="small"
+ />
+ )
+}
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.ts
index 5d1a82237338..8d1f760cc3a3 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts
@@ -74,6 +74,7 @@ import {
getShowLabelsOnSeries,
getShowLegend,
getShowMultipleYAxes,
+ getShowPercentagesOnSeries,
getShowPercentStackView,
getShowValuesOnSeries,
getYAxisScaleType,
@@ -269,6 +270,7 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
showAnnotations: [(s) => [s.querySource], (q) => (q ? getShowAnnotations(q) : null)],
showLegend: [(s) => [s.querySource], (q) => (q ? getShowLegend(q) : null)],
showValuesOnSeries: [(s) => [s.querySource], (q) => (q ? getShowValuesOnSeries(q) : null)],
+ showPercentagesOnSeries: [(s) => [s.querySource], (q) => (q ? getShowPercentagesOnSeries(q) : null)],
showLabelOnSeries: [(s) => [s.querySource], (q) => (q ? getShowLabelsOnSeries(q) : null)],
showPercentStackView: [(s) => [s.querySource], (q) => (q ? getShowPercentStackView(q) : null)],
yAxisScaleType: [(s) => [s.querySource], (q) => (q ? getYAxisScaleType(q) : null)],
diff --git a/frontend/src/scenes/trends/trendsDataLogic.ts b/frontend/src/scenes/trends/trendsDataLogic.ts
index 9fa6e81c39e6..aed5dcb38e3d 100644
--- a/frontend/src/scenes/trends/trendsDataLogic.ts
+++ b/frontend/src/scenes/trends/trendsDataLogic.ts
@@ -87,6 +87,7 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
'enabledIntervals',
'breakdownFilter',
'showValuesOnSeries',
+ 'showPercentagesOnSeries',
'showLabelOnSeries',
'showPercentStackView',
'supportsPercentStackView',
diff --git a/packages/quill/packages/charts/src/charts/utils/use-value-labels.ts b/packages/quill/packages/charts/src/charts/utils/use-value-labels.ts
index a6f9c7b64051..15dc98e505f9 100644
--- a/packages/quill/packages/charts/src/charts/utils/use-value-labels.ts
+++ b/packages/quill/packages/charts/src/charts/utils/use-value-labels.ts
@@ -1,10 +1,12 @@
import { useMemo } from 'react'
import type { Series } from '../../core/types'
+import type { ValueLabelFormatter } from '../../overlays/ValueLabels'
export interface ValueLabelsConfig {
seriesKeys?: string[]
- formatter?: (value: number) => string
+ /** Per-segment label text — see `ValueLabelFormatter` for the context and empty-string contract. */
+ formatter?: ValueLabelFormatter
}
export function resolveValueLabelsConfig(input: boolean | ValueLabelsConfig | undefined): ValueLabelsConfig | null {
diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.ts
index d6209cb9de64..2b3e24c7590f 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -102,7 +102,7 @@ export type {
ReferenceLineVariant,
} from './overlays/ReferenceLine'
export { ValueLabels } from './overlays/ValueLabels'
-export type { ValueLabelsProps } from './overlays/ValueLabels'
+export type { ValueLabelContext, ValueLabelFormatter, ValueLabelsProps } from './overlays/ValueLabels'
export { AxisTitles } from './overlays/AxisTitles'
export type { AxisTitlesProps } from './overlays/AxisTitles'
diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
index a61202c5c5d4..91fa44f78899 100644
--- a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
@@ -312,6 +312,65 @@ describe('ValueLabels', () => {
})
})
+ describe('formatter context', () => {
+ it('passes each segment the raw value and its band of stack-contributing values', () => {
+ // Two series, one negative — the formatter encodes rawValue and the band so we can
+ // assert the overlay surfaces the full band (incl. the negative) to the caller.
+ const series: ResolvedSeries[] = [
+ { key: 'a', label: 'A', color: '#a00', data: [30, 25] },
+ { key: 'b', label: 'B', color: '#0a0', data: [-10, 75] },
+ ]
+ const ctx = makeContext(series, { labels: ['Mon', 'Tue'] })
+ const { container } = renderInChart(
+ ctx,
+ <ValueLabels valueFormatter={(_v, _si, _di, c) => `${c.rawValue}|${c.bandValues.join(',')}`} />
+ )
+ expect(
+ labelDivs(container)
+ .map((d) => d.textContent)
+ .sort()
+ ).toEqual(['-10|30,-10', '25|25,75', '30|30,-10', '75|25,75'])
+ })
+
+ it('marks the context isPercent in percent layout and passes the segment fraction as value', () => {
+ const series: ResolvedSeries[] = [
+ { key: 'a', label: 'A', color: '#a00', data: [20, 60] },
+ { key: 'b', label: 'B', color: '#0a0', data: [80, 40] },
+ ]
+ const percentScales: ChartScales = {
+ x: xScale,
+ y: (v: number) => 368 - v * 352,
+ yTicks: () => [0, 0.5, 1],
+ }
+ const positionByKey: Record<string, number[]> = { a: [0.2, 0.6], b: [1.0, 1.0] }
+ const resolvePositionValue: ResolveValueFn = (s, i) => positionByKey[s.key]?.[i] ?? 0
+ const ctx = makeContext(series, {
+ isPercent: true,
+ labels: ['Mon', 'Tue'],
+ scales: percentScales,
+ resolvePositionValue,
+ })
+ const { container } = renderInChart(
+ ctx,
+ // Encode both `value` (the fraction) and `isPercent` so the assertion pins both, no branch.
+ <ValueLabels valueFormatter={(v, _si, _di, c) => `${(v * 100).toFixed(0)}%|${c.isPercent}`} />
+ )
+ expect(
+ labelDivs(container)
+ .map((d) => d.textContent)
+ .sort()
+ ).toEqual(['20%|true', '40%|true', '60%|true', '80%|true'])
+ })
+
+ it('skips labels whose formatter returns an empty string', () => {
+ const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [10, 20, 30] }]
+ const ctx = makeContext(series, { labels: ['Mon', 'Tue', 'Wed'] })
+ const textByValue: Record<number, string> = { 10: '10', 20: '', 30: '30' }
+ const { container } = renderInChart(ctx, <ValueLabels valueFormatter={(v) => textByValue[v]} />)
+ expect(labelDivs(container).map((d) => d.textContent)).toEqual(['10', '30'])
+ })
+ })
+
it('in percent layout, formatter receives each segment fraction (0..1), not raw data', () => {
// Both series have non-zero values in both bands so we exercise the `raw / total`
// division, not the trivial single-segment-per-band 100% path.
diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
index 378693e6be26..407c1f064934 100644
--- a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
@@ -8,9 +8,32 @@ import { getTextMeasureCtx } from '../utils/text-measure'
export type ValueLabelsMode = 'per-segment' | 'stack-total'
+/** Per-segment context handed to a value formatter so callers can compute labels that depend on
+ * the band (e.g. each segment's share of its band). Keeps band/stacking knowledge in the library
+ * while leaving the label text — values, percentages, units — entirely to the caller. */
+export interface ValueLabelContext {
+ /** Underlying value of this segment (the band total for stack-total labels). In percent layout
+ * the formatter's `value` arg is the segment's fraction (0..1); `rawValue` stays the original so
+ * callers can compute their own shares. */
+ rawValue: number
+ /** Finite values of every series contributing to this band's stack (non-excluded, not a fill
+ * lower-bound, not an overlay) at this dataIndex — the denominator set for share math. */
+ bandValues: number[]
+ /** True in normalized/percent layout, where `value` is already a fraction. */
+ isPercent: boolean
+}
+
+/** Returning an empty string skips the label entirely. */
+export type ValueLabelFormatter = (
+ value: number,
+ /** `-1` for stack-total labels. */
+ seriesIndex: number,
+ dataIndex: number,
+ context: ValueLabelContext
+) => string
+
export interface ValueLabelsProps {
- /** `seriesIndex` is `-1` for stack-total labels. */
- valueFormatter?: (value: number, seriesIndex: number, dataIndex: number) => string
+ valueFormatter?: ValueLabelFormatter
minGap?: number
mode?: ValueLabelsMode
}
@@ -94,6 +117,21 @@ function buildCandidates(args: BuildCandidatesArgs): Candidate[] {
return args.mode === 'stack-total' ? buildStackTotal(args, ctx) : buildPerSegment(args, ctx)
}
+function stackContributors(series: ResolvedSeries[]): ResolvedSeries[] {
+ return series.filter((s) => !s.visibility?.excluded && !s.fill?.lowerData && !s.overlay)
+}
+
+function bandValuesAt(contributors: ResolvedSeries[], dIdx: number): number[] {
+ const values: number[] = []
+ for (const s of contributors) {
+ const v = s.data[dIdx]
+ if (typeof v === 'number' && isFinite(v)) {
+ values.push(v)
+ }
+ }
+ return values
+}
+
function bandTotal(visible: ResolvedSeries[], dIdx: number): number | null {
let total = 0
let count = 0
@@ -140,6 +178,16 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
if (categoricalCoord == null || !isFinite(categoricalCoord) || !isFinite(valueCoord)) {
continue
}
+ // `visible` (label-eligible series) rather than all stack contributors, so `bandValues`
+ // sums to the `total` shown — `buildPerSegment` deliberately uses the wider contributor set.
+ const text = valueFormatter(total, -1, dIdx, {
+ rawValue: total,
+ bandValues: bandValuesAt(visible, dIdx),
+ isPercent,
+ })
+ if (text === '') {
+ continue
+ }
pushCandidate(
out,
ctx,
@@ -148,7 +196,7 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
-1,
dIdx,
barColorAt(topSeries, dIdx),
- valueFormatter(total, -1, dIdx),
+ text,
categoricalCoord,
valueCoord,
total >= 0
@@ -161,13 +209,12 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
const { series, labels, scales, resolvePositionValue, valueFormatter, isHorizontal, isPercent } = args
const out: Candidate[] = []
- // In percent layout each band sums to 1, so we need the band total to convert each segment's
- // raw value into the fraction d3 uses for placement (`raw / total`). Match the d3 stack's own
- // denominator — every non-excluded stacked series — even if some have `valueLabel: false`,
- // since those still contribute to the visual stack height.
- const visibleForTotal = isPercent
- ? series.filter((s) => !s.visibility?.excluded && !s.fill?.lowerData && !s.overlay)
- : []
+ // Stack denominator — for percent-layout fraction placement and for the `bandValues` handed to
+ // the formatter. Includes `valueLabel: false` series, which still contribute to stack height.
+ // The band depends only on `dIdx`, so compute it once per index instead of per segment.
+ const contributors = stackContributors(series)
+ const bandValuesByIndex = labels.map((_, dIdx) => bandValuesAt(contributors, dIdx))
+ const bandTotalByIndex = isPercent ? labels.map((_, dIdx) => bandTotal(contributors, dIdx)) : []
for (let sIdx = 0; sIdx < series.length; sIdx++) {
const s = series[sIdx]
@@ -191,7 +238,7 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
let above = isPercent ? false : yValue >= 0
if (isPercent) {
- const total = bandTotal(visibleForTotal, dIdx)
+ const total = bandTotalByIndex[dIdx]
if (total == null || total === 0) {
continue
}
@@ -209,6 +256,15 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
if (categoricalCoord == null || !isFinite(categoricalCoord) || !isFinite(valueCoord)) {
continue
}
+ const text = valueFormatter(displayValue, sIdx, dIdx, {
+ rawValue,
+ bandValues: bandValuesByIndex[dIdx],
+ isPercent,
+ })
+ if (text === '') {
+ continue
+ }
+
pushCandidate(
out,
ctx,
@@ -217,7 +273,7 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
sIdx,
dIdx,
barColorAt(s, dIdx),
- valueFormatter(displayValue, sIdx, dIdx),
+ text,
categoricalCoord,
valueCoord,
above,
diff --git a/posthog/schema.py b/posthog/schema.py
index 8fc444a8bc82..d013271e8954 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -7827,6 +7827,13 @@ class LifecycleFilter(BaseModel):
extra="forbid",
)
showLegend: bool | None = False
+ showPercentagesOnSeries: bool | None = Field(
+ default=None,
+ description=(
+ "Append per-band percentage to each value label (e.g. `580 (42%)`)."
+ " Requires `showValuesOnSeries` — on its own it has no visible effect."
+ ),
+ )
showValuesOnSeries: bool | None = None
stacked: bool | None = True
toggledLifecycles: list[LifecycleToggle] | None = None
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 6cbf4cbb2c40..3f398cc789a2 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -2876,6 +2876,8 @@ export const LifecycleToggleApi = {
export interface LifecycleFilterApi {
showLegend?: boolean | null
+ /** Append per-band percentage to each value label (e.g. `580 (42%)`). Requires `showValuesOnSeries` — on its own it has no visible effect. */
+ showPercentagesOnSeries?: boolean | null
showValuesOnSeries?: boolean | null
stacked?: boolean | null
toggledLifecycles?: LifecycleToggleApi[] | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 8b6ce16be23f..e8149adeda5d 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -2563,6 +2563,8 @@ export const LifecycleToggleApi = {
export interface LifecycleFilterApi {
showLegend?: boolean | null
+ /** Append per-band percentage to each value label (e.g. `580 (42%)`). Requires `showValuesOnSeries` — on its own it has no visible effect. */
+ showPercentagesOnSeries?: boolean | null
showValuesOnSeries?: boolean | null
stacked?: boolean | null
toggledLifecycles?: LifecycleToggleApi[] | null
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.stories.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.stories.tsx
index 85d181861387..d7ace7bba855 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.stories.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.stories.tsx
@@ -119,6 +119,7 @@ interface LifecycleInsightOpts {
shortId: string
name?: string
showValuesOnSeries?: boolean
+ showPercentagesOnSeries?: boolean
showLegend?: boolean
}
@@ -128,6 +129,7 @@ function lifecycleInsight({
shortId,
name,
showValuesOnSeries,
+ showPercentagesOnSeries,
showLegend,
}: LifecycleInsightOpts): object {
return {
@@ -165,7 +167,7 @@ function lifecycleInsight({
interval: 'day',
kind: 'LifecycleQuery',
series: [{ event: '$pageview', kind: 'EventsNode', math: 'total', name: '$pageview' }],
- lifecycleFilter: { stacked, showValuesOnSeries, showLegend },
+ lifecycleFilter: { stacked, showValuesOnSeries, showPercentagesOnSeries, showLegend },
version: 2,
},
full: true,
@@ -213,12 +215,57 @@ export const UnstackedWithValuesOnSeries: Story = {
),
}
-export const StackedWithLegend: Story = {
+export const StackedWithPercentagesOnSeries: Story = {
render: () => (
<LifecycleStory
insightFixture={lifecycleInsight({
stacked: true,
id: 304,
+ shortId: 'lifecycleStackedPercentages',
+ name: 'Lifecycle stacked (values + percentages on series)',
+ showValuesOnSeries: true,
+ showPercentagesOnSeries: true,
+ })}
+ />
+ ),
+}
+
+export const UnstackedWithPercentagesOnSeries: Story = {
+ render: () => (
+ <LifecycleStory
+ insightFixture={lifecycleInsight({
+ stacked: false,
+ id: 305,
+ shortId: 'lifecycleUnstackedPercentages',
+ name: 'Lifecycle unstacked (values + percentages on series)',
+ showValuesOnSeries: true,
+ showPercentagesOnSeries: true,
+ })}
+ />
+ ),
+}
+
+export const StackedWithPercentagesOnlyOnSeries: Story = {
+ render: () => (
+ <LifecycleStory
+ insightFixture={lifecycleInsight({
+ stacked: true,
+ id: 306,
+ shortId: 'lifecycleStackedPercentagesOnly',
+ name: 'Lifecycle stacked (percentages only on series)',
+ showValuesOnSeries: false,
+ showPercentagesOnSeries: true,
+ })}
+ />
+ ),
+}
+
+export const StackedWithLegend: Story = {
+ render: () => (
+ <LifecycleStory
+ insightFixture={lifecycleInsight({
+ stacked: true,
+ id: 307,
shortId: 'lifecycleStackedLegend',
name: 'Lifecycle stacked (with legend)',
showLegend: true,
@@ -232,7 +279,7 @@ export const UnstackedWithLegend: Story = {
<LifecycleStory
insightFixture={lifecycleInsight({
stacked: false,
- id: 305,
+ id: 308,
shortId: 'lifecycleUnstackedLegend',
name: 'Lifecycle unstacked (with legend)',
showLegend: true,
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
index bf0103a5c6ff..337aff67a63a 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
@@ -28,7 +28,7 @@ import {
} from '../shared/handleTrendsChartClick'
import { buildTrendsSeriesMeta, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'
import { TrendsTooltip } from '../shared/TrendsTooltip'
-import { buildLifecycleChartModel } from './trendsLifecycleChartTransforms'
+import { buildLifecycleChartModel, buildLifecycleValueLabelFormatter } from './trendsLifecycleChartTransforms'
interface TrendsLifecycleChartProps {
context?: QueryContext<InsightVizNode>
@@ -63,6 +63,7 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi
hasPersonsModal,
querySource,
showValuesOnSeries,
+ showPercentagesOnSeries,
showLegend,
} = useValues(trendsDataLogic(insightProps))
const { timezone, weekStartDay, baseCurrency } = useValues(teamLogic)
@@ -74,11 +75,20 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi
!!indexedResults[0].data &&
indexedResults.some((r: IndexedTrendResult) => r.count !== 0)
- const valueLabelFormatter = useCallback(
+ const formatValue = useCallback(
(value: number) => formatAggregationAxisValue(trendsFilter, value, baseCurrency),
[trendsFilter, baseCurrency]
)
+ const valueLabelFormatter = useMemo(
+ () =>
+ buildLifecycleValueLabelFormatter(formatValue, {
+ showValues: !!showValuesOnSeries,
+ showPercentages: !!showPercentagesOnSeries,
+ }),
+ [formatValue, showValuesOnSeries, showPercentagesOnSeries]
+ )
+
const { series, labels, config } = useMemo(
() =>
buildLifecycleChartModel<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {
@@ -92,7 +102,7 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi
interval,
timezone,
allDays: currentPeriodResult?.days ?? [],
- valueLabels: showValuesOnSeries ? { formatter: valueLabelFormatter } : false,
+ valueLabels: showValuesOnSeries || showPercentagesOnSeries ? { formatter: valueLabelFormatter } : false,
tooltip: LIFECYCLE_TOOLTIP_CONFIG,
}),
[
@@ -106,6 +116,7 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi
interval,
timezone,
showValuesOnSeries,
+ showPercentagesOnSeries,
valueLabelFormatter,
]
)
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts
index ed9841adb09c..572eea22f853 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.test.ts
@@ -1,4 +1,4 @@
-import type { TimeInterval } from '@posthog/quill-charts'
+import type { TimeInterval, ValueLabelContext } from '@posthog/quill-charts'
import type { CurrencyCode, TrendsFilter as SchemaTrendsFilter } from '~/queries/schema/schema-general'
import type { IntervalType } from '~/types'
@@ -6,6 +6,7 @@ import type { IntervalType } from '~/types'
import type { YFormatterFields } from '../shared/trendsChartDisplayOptions'
import {
buildLifecycleChartModel,
+ buildLifecycleValueLabelFormatter,
buildTrendsLifecycleConfig,
buildTrendsLifecycleSeries,
filterToggledLifecycleResults,
@@ -243,6 +244,36 @@ describe('buildTrendsLifecycleConfig', () => {
})
})
+describe('buildLifecycleValueLabelFormatter', () => {
+ const formatValue = (v: number): string => `${v}`
+ // Diverging band: positive new + negative dormant. abs total = 30, so 20 → 67%, -10 → 33%.
+ const band: ValueLabelContext = { rawValue: 20, bandValues: [20, -10], isPercent: false }
+
+ it.each([
+ { name: 'values only', showValues: true, showPercentages: false, expected: '20' },
+ { name: 'values + percentages', showValues: true, showPercentages: true, expected: '20 (67%)' },
+ { name: 'percentages only', showValues: false, showPercentages: true, expected: '67%' },
+ ])('renders $name as "$expected"', ({ showValues, showPercentages, expected }) => {
+ const formatter = buildLifecycleValueLabelFormatter(formatValue, { showValues, showPercentages })
+ expect(formatter(20, 0, 0, band)).toBe(expected)
+ })
+
+ it('uses absolute values so the negative dormant segment gets a sensible share', () => {
+ const formatter = buildLifecycleValueLabelFormatter(formatValue, { showValues: false, showPercentages: true })
+ expect(formatter(-10, 1, 0, { rawValue: -10, bandValues: [20, -10], isPercent: false })).toBe('33%')
+ })
+
+ it('returns an empty string (skip) for percentages-only when the band has no total', () => {
+ const formatter = buildLifecycleValueLabelFormatter(formatValue, { showValues: false, showPercentages: true })
+ expect(formatter(0, 0, 0, { rawValue: 0, bandValues: [0, 0], isPercent: false })).toBe('')
+ })
+
+ it('does not append percentages in percent layout (labels already express fractions)', () => {
+ const formatter = buildLifecycleValueLabelFormatter(formatValue, { showValues: true, showPercentages: true })
+ expect(formatter(0.2, 0, 0, { rawValue: 20, bandValues: [20, 80], isPercent: true })).toBe('0.2')
+ })
+})
+
describe('shortenLifecycleLabel', () => {
it.each([
{ input: 'Pageview - new', expected: 'New' },
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts
index fa5ef66bccea..302e9079ec42 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts
@@ -1,4 +1,4 @@
-import type { Series, TimeInterval, TimeSeriesBarChartConfig } from '@posthog/quill-charts'
+import type { Series, TimeInterval, TimeSeriesBarChartConfig, ValueLabelFormatter } from '@posthog/quill-charts'
import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'
import type { YFormatterFields } from '../shared/trendsChartDisplayOptions'
@@ -25,6 +25,31 @@ function lifecycleStatusOrder(status: string | undefined): number {
return i === -1 ? LIFECYCLE_STATUS_ORDER.length : i
}
+export interface LifecycleValueLabelOptions {
+ showValues: boolean
+ showPercentages: boolean
+}
+
+// Each segment's percentage is its share of the band's absolute total — `abs` so the negative
+// dormant series contributes a sensible denominator instead of cancelling the positives.
+export function buildLifecycleValueLabelFormatter(
+ formatValue: (value: number) => string,
+ { showValues, showPercentages }: LifecycleValueLabelOptions
+): ValueLabelFormatter {
+ return (value, _seriesIndex, _dataIndex, context) => {
+ const valueText = showValues ? formatValue(value) : ''
+ if (!showPercentages || context.isPercent) {
+ return valueText
+ }
+ const absTotal = context.bandValues.reduce((sum, v) => sum + Math.abs(v), 0)
+ if (absTotal === 0) {
+ return valueText
+ }
+ const pct = Math.round((Math.abs(context.rawValue) / absTotal) * 100)
+ return showValues ? `${valueText} (${pct}%)` : `${pct}%`
+ }
+}
+
/** Drops rows whose lifecycle status is toggled off — mirrors the main app's legend toggles, which
* the MCP host honors from the query (the web chart toggles interactively instead). With no toggle
* set every row passes; once a toggle is active, a row without a status is dropped. */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1e795adf4bc4..804a99d1155e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2893,6 +2893,8 @@ export namespace Schemas {
export interface LifecycleFilter {
showLegend?: boolean | null;
+ /** Append per-band percentage to each value label (e.g. `580 (42%)`). Requires `showValuesOnSeries` — on its own it has no visible effect. */
+ showPercentagesOnSeries?: boolean | null;
showValuesOnSeries?: boolean | null;
stacked?: boolean | null;
toggledLifecycles?: LifecycleToggle[] | null;