: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): share y-axes between trend series of similar magnitude (#94037)
Sam Pennington866c5181b2e9
diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.ts b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.tsindex b2bf18bfe191..4885093269f1 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.test.ts@@ -147,11 +147,16 @@ describe('stickinessChartTransforms', () => {expect(series.map((s) => s.key)).toEqual(['a', 'b'])})- it('assigns yAxisIds [left, y1, y2] across three results when showMultipleYAxes is true', () => {- const results = [makeResult({ id: 'a' }), makeResult({ id: 'b' }), makeResult({ id: 'c' })]+ it('groups y-axes by the magnitude of the percent-converted values when showMultipleYAxes is true', () => {+ // Same raw data, but b's much larger count makes its percentages ~2 orders smaller.+ const results = [+ makeResult({ id: 'a', count: 100 }),+ makeResult({ id: 'b', count: 10000 }),+ makeResult({ id: 'c', count: 100 }),+ ]const series = buildStickinessSeries(results, { getColor: () => RED, showMultipleYAxes: true })- expect(series.map((s) => s.yAxisId)).toEqual([DEFAULT_Y_AXIS_ID, 'y1', 'y2'])+ expect(series.map((s) => s.yAxisId)).toEqual([DEFAULT_Y_AXIS_ID, 'y1', DEFAULT_Y_AXIS_ID])})it('transforms each result independently using its own count', () => {diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.tsindex 167cd53edff6..834dac2424ff 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts@@ -9,6 +9,7 @@ import { ChartDisplayType } from '~/types'import { INSIGHT_TOOLTIP_CONFIG } from '../../shared/tooltipConfig'import { COMPARE_PREVIOUS_DIM_OPACITY, dimHexColor } from '../../trends/shared/compareDimming'import { humanizeSeriesLabel } from '../../trends/shared/humanizeSeriesLabel'+import { computeMagnitudeAxisIds } from '../../trends/shared/magnitudeAxisIds'// Shape both IndexedTrendResult (kea) and StickinessResultItem (MCP) satisfy.export interface StickinessResultLike {@@ -51,9 +52,9 @@ export function toPercentData(data: number[], count: number): number[] {export function buildStickinessMainSeries<R extends StickinessResultLike, M = unknown>(r: R,index: number,- opts: BuildStickinessSeriesOpts<R, M>+ opts: BuildStickinessSeriesOpts<R, M>,+ yAxisId: string = DEFAULT_Y_AXIS_ID): Series<M> {- const yAxisId = opts.showMultipleYAxes && index > 0 ? `y${index}` : DEFAULT_Y_AXIS_IDconst excluded = opts.getHidden ? opts.getHidden(r, index) : falseconst meta: M | undefined = opts.buildMeta ? opts.buildMeta(r, index) : undefined// Dim the compare-against-previous series so it recedes behind the current period, matching trends.@@ -75,7 +76,11 @@ export function buildStickinessSeries<R extends StickinessResultLike, M = unknowresults: R[],opts: BuildStickinessSeriesOpts<R, M>): Series<M>[] {- return results.map((r, index) => buildStickinessMainSeries(r, index, opts))+ // Group on the rendered (percent-converted) values, not the raw counts.+ const yAxisIds = opts.showMultipleYAxes+ ? computeMagnitudeAxisIds(results.map((r) => toPercentData(r.data, r.count)))+ : undefined+ return results.map((r, index) => buildStickinessMainSeries(r, index, opts, yAxisIds?.[index]))}/** Produce per-bucket labels ("Day 0", "Day 1", …). The API's own "X day(s)" labelsdiff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsxindex 57a9433bcdce..d8f2772bc8db 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx@@ -329,19 +329,10 @@ export function TrendsBarChart({[isAggregated, goalLines, series])- const indexByResult = useMemo(() => {- const m = new Map<IndexedTrendResult, number>()- ;(indexedResults ?? []).forEach((r: IndexedTrendResult, i: number) => m.set(r, i))- return m- }, [indexedResults])-// Anomaly markers must read the same axis their series is scaled against.const getYAxisId = useCallback(- (r: IndexedTrendResult) => {- const idx = indexByResult.get(r) ?? 0- return applyMultipleYAxes && idx > 0 ? `y${idx}` : DEFAULT_Y_AXIS_ID- },- [indexByResult, applyMultipleYAxes]+ (r: IndexedTrendResult) => series.find((s) => s.key === String(r.id))?.yAxisId ?? DEFAULT_Y_AXIS_ID,+ [series])const onPointClick = useCallback(diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.tsindex 36d19e5f2ef3..4bb6391a79ab 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts@@ -79,9 +79,13 @@ describe('buildTrendsBarTimeSeries', () => {it.each([{ showMultipleYAxes: undefined, expected: ['left', 'left', 'left'] },- { showMultipleYAxes: true, expected: ['left', 'y1', 'y2'] },- ])('assigns yAxisId per series (showMultipleYAxes=$showMultipleYAxes)', ({ showMultipleYAxes, expected }) => {- const results = [makeResult({ id: 'a' }), makeResult({ id: 'b' }), makeResult({ id: 'c' })]+ { showMultipleYAxes: true, expected: ['left', 'y1', 'left'] },+ ])('groups yAxisIds by magnitude (showMultipleYAxes=$showMultipleYAxes)', ({ showMultipleYAxes, expected }) => {+ const results = [+ makeResult({ id: 'a', data: [1, 2, 3] }),+ makeResult({ id: 'b', data: [1000, 2000, 3000] }),+ makeResult({ id: 'c', data: [2, 4, 6] }),+ ]const series = buildTrendsBarTimeSeries(results, { getColor: () => RED, showMultipleYAxes })expect(series.map((s) => s.yAxisId)).toEqual(expected)})diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.tsindex 8487d278790d..09610b113a70 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts@@ -4,6 +4,7 @@ import type { Series, TimeInterval, TimeSeriesBarChartConfig, TooltipContext, YAimport { COMPARE_PREVIOUS_DIM_OPACITY, dimHexColor } from '../shared/compareDimming'import { schemaGoalLinesToConfigs } from '../shared/goalLinesAdapter'import { humanizeSeriesLabel } from '../shared/humanizeSeriesLabel'+import { computeMagnitudeAxisIds } from '../shared/magnitudeAxisIds'import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'import type { GoalLineLike, YFormatterFields } from '../shared/trendsChartDisplayOptions'@@ -30,8 +31,9 @@ export interface BuildTrendsBarSeriesOpts<R extends TrendsBarResultLike, M = unk// Resolves the legend/series label (custom name + breakdown formatting). Hosts that lack the// breakdown/cohort deps (e.g. MCP) omit it and fall back to the raw humanized event name.getLabel?: (r: R) => string- // Scale each series past the first against its own y-axis. Grouped (unstacked) bars only —- // stacked layouts must share one axis, so the adapter never sets this for them.+ // Give series of different orders of magnitude their own y-axes (similar ones share).+ // Grouped (unstacked) bars only — stacked layouts must share one axis, so the adapter+ // never sets this for them.showMultipleYAxes?: boolean}@@ -58,12 +60,12 @@ function buildMainTrendsBarSeries<R extends TrendsBarResultLike, M = unknown>(r: R,index: number,opts: BuildTrendsBarSeriesOpts<R, M>,- data: number[]+ data: number[],+ yAxisId: string = DEFAULT_Y_AXIS_ID): Series<M> {const color = resolveBarColor(r, index, opts)const excluded = opts.getHidden ? opts.getHidden(r, index) : falseconst meta = opts.buildMeta ? opts.buildMeta(r, index) : undefined- const yAxisId = opts.showMultipleYAxes && index > 0 ? `y${index}` : DEFAULT_Y_AXIS_IDreturn {key: String(r.id),label: opts.getLabel ? opts.getLabel(r) : humanizeSeriesLabel(r.label),@@ -79,7 +81,8 @@ export function buildTrendsBarTimeSeries<R extends TrendsBarResultLike, M = unknresults: R[],opts: BuildTrendsBarSeriesOpts<R, M>): Series<M>[] {- return results.map((r, index) => buildMainTrendsBarSeries(r, index, opts, r.data))+ const yAxisIds = opts.showMultipleYAxes ? computeMagnitudeAxisIds(results.map((r) => r.data)) : undefined+ return results.map((r, index) => buildMainTrendsBarSeries(r, index, opts, r.data, yAxisIds?.[index]))}export interface BuildTrendsBarTimeSeriesConfigOpts {diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsxindex 5239efe49d71..bb29628354ee 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx@@ -157,20 +157,6 @@ export function TrendsLineChart({[trendsFilter, isPercentStackView, baseCurrency])- const indexByResult = useMemo(() => {- const m = new Map<IndexedTrendResult, number>()- ;(indexedResults ?? []).forEach((r, i) => m.set(r, i))- return m- }, [indexedResults])-- const getYAxisId = useCallback(- (r: IndexedTrendResult) => {- const idx = indexByResult.get(r) ?? 0- return showMultipleYAxes && idx > 0 ? `y${idx}` : DEFAULT_Y_AXIS_ID- },- [indexByResult, showMultipleYAxes]- )-const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModal// The persons modal is intentionally unavailable for multi-series formulas (there's no// single series of actors behind a computed ratio). On dashboard/card tiles a click@@ -301,6 +287,12 @@ export function TrendsLineChart({])+ // Anomaly markers must read the same axis their series is scaled against.+ const getYAxisId = useCallback(+ (r: IndexedTrendResult) => series.find((s) => s.key === String(r.id))?.yAxisId ?? DEFAULT_Y_AXIS_ID,+ [series]+ )+const config = useChartConfig(() =>buildTrendsLineTimeSeriesConfig<IndexedTrendResult>({diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.tsindex e9f28b8b3e53..7a2a0fc82ebe 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts@@ -150,11 +150,15 @@ describe('trendsChartTransforms', () => {expect(series.map((s) => s.key)).toEqual(['a', 'b'])})- it('assigns yAxisIds [left, y1, y2] across three results when showMultipleYAxes is true', () => {- const results = [makeResult({ id: 'a' }), makeResult({ id: 'b' }), makeResult({ id: 'c' })]+ it('groups series onto shared y-axes by magnitude when showMultipleYAxes is true', () => {+ const results = [+ makeResult({ id: 'a', data: [1, 2, 3] }),+ makeResult({ id: 'b', data: [1000, 2000, 3000] }),+ makeResult({ id: 'c', data: [2, 4, 6] }),+ ]const series = buildTrendsSeries(results, { getColor: () => RED, showMultipleYAxes: true })- expect(series.map((s) => s.yAxisId)).toEqual([DEFAULT_Y_AXIS_ID, 'y1', 'y2'])+ expect(series.map((s) => s.yAxisId)).toEqual([DEFAULT_Y_AXIS_ID, 'y1', DEFAULT_Y_AXIS_ID])})})diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.tsindex 3bb66b88004e..b486685e9aa9 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts@@ -11,6 +11,7 @@ import type {import { schemaGoalLinesToConfigs } from '../shared/goalLinesAdapter'import { humanizeSeriesLabel } from '../shared/humanizeSeriesLabel'+import { computeMagnitudeAxisIds } from '../shared/magnitudeAxisIds'import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'import type { CiRangesFn, GoalLineLike, YFormatterFields } from '../shared/trendsChartDisplayOptions'@@ -30,6 +31,7 @@ export interface TrendsResultLike {export interface BuildTrendsSeriesOpts<R extends TrendsResultLike, M = unknown> {/** Area fill under each series (web maps `display === ActionsAreaGraph`). */isArea?: boolean+ /** Give series of different orders of magnitude their own y-axes (similar ones share). */showMultipleYAxes?: boolean// Negative number — index from the end where the in-progress tail begins. Omit to skip.incompletenessOffsetFromEnd?: number@@ -60,10 +62,10 @@ export function computeDashedFromIndex(export function buildMainTrendsSeries<R extends TrendsResultLike, M = unknown>(r: R,index: number,- opts: BuildTrendsSeriesOpts<R, M>+ opts: BuildTrendsSeriesOpts<R, M>,+ yAxisId: string = DEFAULT_Y_AXIS_ID): Series<M> {const dashedFromIndex = computeDashedFromIndex(r, opts)- const yAxisId = opts.showMultipleYAxes && index > 0 ? `y${index}` : DEFAULT_Y_AXIS_IDconst excluded = opts.getHidden ? opts.getHidden(r, index) : falseconst meta: M | undefined = opts.buildMeta ? opts.buildMeta(r, index) : undefinedreturn {@@ -83,7 +85,8 @@ export function buildTrendsSeries<R extends TrendsResultLike, M = unknown>(results: R[],opts: BuildTrendsSeriesOpts<R, M>): Series<M>[] {- return results.map((r, index) => buildMainTrendsSeries(r, index, opts))+ const yAxisIds = opts.showMultipleYAxes ? computeMagnitudeAxisIds(results.map((r) => r.data)) : undefined+ return results.map((r, index) => buildMainTrendsSeries(r, index, opts, yAxisIds?.[index]))}export interface BuildDerivedConfigsOpts<R extends TrendsResultLike> {diff --git a/products/product_analytics/frontend/insights/trends/shared/magnitudeAxisIds.test.ts b/products/product_analytics/frontend/insights/trends/shared/magnitudeAxisIds.test.tsnew file mode 100644index 000000000000..e7066f106e22--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/shared/magnitudeAxisIds.test.ts@@ -0,0 +1,61 @@+import { DEFAULT_Y_AXIS_ID } from '@posthog/quill-charts'++import { computeMagnitudeAxisIds } from './magnitudeAxisIds'++describe('computeMagnitudeAxisIds', () => {+ it.each<{ name: string; datasets: number[][]; expected: string[] }>([+ {+ name: 'similar magnitudes share the default axis',+ datasets: [+ [1, 2, 3],+ [4, 5, 6],+ [2, 8, 9],+ ],+ expected: [DEFAULT_Y_AXIS_ID, DEFAULT_Y_AXIS_ID, DEFAULT_Y_AXIS_ID],+ },+ {+ name: 'an order-of-magnitude gap splits into two axes, interleaved series regroup',+ datasets: [+ [1, 2, 3],+ [1000, 2000, 3000],+ [2, 4, 6],+ [5000, 1000, 2000],+ ],+ expected: [DEFAULT_Y_AXIS_ID, 'y1', DEFAULT_Y_AXIS_ID, 'y1'],+ },+ {+ name: 'the first series keeps the default axis even when its group is the largest magnitude',+ datasets: [+ [1000, 2000],+ [1, 2],+ ],+ expected: [DEFAULT_Y_AXIS_ID, 'y1'],+ },+ {+ name: 'a smooth magnitude ramp with sub-order gaps stays on one axis',+ datasets: [[5], [20], [90], [400]],+ expected: [DEFAULT_Y_AXIS_ID, DEFAULT_Y_AXIS_ID, DEFAULT_Y_AXIS_ID, DEFAULT_Y_AXIS_ID],+ },+ {+ name: 'axes are capped at four even with more magnitude clusters',+ datasets: [[1], [100], [10000], [1000000], [100000000]],+ expected: [DEFAULT_Y_AXIS_ID, 'y1', 'y2', 'y3', 'y3'],+ },+ {+ name: 'all-zero and empty series join the lowest-magnitude group',+ datasets: [[1000, 2000], [1, 2], [0, 0], []],+ expected: [DEFAULT_Y_AXIS_ID, 'y1', 'y1', 'y1'],+ },+ {+ name: 'negative values group by absolute magnitude',+ datasets: [+ [-1000, -2000],+ [900, 1100],+ ],+ expected: [DEFAULT_Y_AXIS_ID, DEFAULT_Y_AXIS_ID],+ },+ { name: 'empty input', datasets: [], expected: [] },+ ])('$name', ({ datasets, expected }) => {+ expect(computeMagnitudeAxisIds(datasets)).toEqual(expected)+ })+})diff --git a/products/product_analytics/frontend/insights/trends/shared/magnitudeAxisIds.ts b/products/product_analytics/frontend/insights/trends/shared/magnitudeAxisIds.tsnew file mode 100644index 000000000000..b5a66c5e0ac5--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/shared/magnitudeAxisIds.ts@@ -0,0 +1,55 @@+import { DEFAULT_Y_AXIS_ID } from '@posthog/quill-charts'++const MAGNITUDE_GAP = 1+const MAX_Y_AXES = 4++/** Assign a y-axis id per series so series of similar magnitude share an axis. Series are+ * clustered on log10 of their max |value|, splitting at the largest gaps of at least+ * MAGNITUDE_GAP orders, capped at MAX_Y_AXES axes. The first series' group keeps the+ * default axis id; other groups get stable ids in series order. */+export function computeMagnitudeAxisIds(datasets: readonly (readonly number[])[]): string[] {+ const magnitudes = datasets.map((data) => {+ let max = 0+ for (const value of data) {+ const abs = Math.abs(value)+ if (Number.isFinite(abs) && abs > max) {+ max = abs+ }+ }+ return max > 0 ? Math.log10(max) : null+ })++ const measured = magnitudes+ .flatMap((magnitude, seriesIndex) => (magnitude === null ? [] : [{ magnitude, seriesIndex }]))+ .sort((a, b) => a.magnitude - b.magnitude)++ const splitPositions = new Set(+ measured+ .slice(1)+ .map((entry, k) => ({ pos: k + 1, gap: entry.magnitude - measured[k].magnitude }))+ .filter(({ gap }) => gap >= MAGNITUDE_GAP)+ .sort((a, b) => b.gap - a.gap)+ .slice(0, MAX_Y_AXES - 1)+ .map(({ pos }) => pos)+ )++ // Flat (all-zero or empty) series carry no magnitude and join the lowest group.+ const groupOf = datasets.map(() => 0)+ let group = 0+ measured.forEach(({ seriesIndex }, k) => {+ if (splitPositions.has(k)) {+ group += 1+ }+ groupOf[seriesIndex] = group+ })++ const idOf = new Map<number, string>(datasets.length ? [[groupOf[0], DEFAULT_Y_AXIS_ID]] : [])+ return groupOf.map((g) => {+ let id = idOf.get(g)+ if (!id) {+ id = `y${idOf.size}`+ idOf.set(g, id)+ }+ return id+ })+}