: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 multiple y-axes for grouped hog-charts bars (#62627)
Sam Pennington96801618a291
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex f46192a72a38..04e3015ad207 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -644,6 +644,10 @@ snapshots:hash: v1.k794b7964.d7d7bf5c59f5331244fe1296a1fc8aa3f64b978932157cb721811f6d5a8ee7b9.RVzEH-awcLfkkPb9sGtmTTW71fFC0qjbnSk8TtFynq8components-hogcharts-linechart--stacked-area--light:hash: v1.k794b7964.81201734b8069950cb9b0765a487ace24ce480ac38f3244a93b283ab6a5d440a.CyG0hbIs0gRo4XJJwMiA6EVZ_CbqKgbNMETTujDXh5Y+ components-hogcharts-linechart--triple-y-axis--dark:+ hash: v1.k794b7964.8101b94f8627a2a4f9db787e1811da546e557d08f5cb2e1d26babd11f1e7821c.I8prrcLl2sRZrw0MttyFsFdYgSIK50FUv1nb5s1pKcQ+ components-hogcharts-linechart--triple-y-axis--light:+ hash: v1.k794b7964.c3d381e4abb5769e63c33e52e03aef90f6056b8abb94ca1a7fcf4213b47f18f6.6zmZr3ZLjZgr40OFrge5wiqFjZBErWZpBLFf1kZYN1Ycomponents-hogcharts-linechart--visibility-flags--dark:hash: v1.k794b7964.2f7e324b0723e7e452601b86b6c3e27fe0b7a3a1c9236c652af244488b8dc67e.cJbINcSzaWfVAc-auv8Rnve9OVdIPKexGrLMW880UzIcomponents-hogcharts-linechart--visibility-flags--light:@@ -748,6 +752,10 @@ snapshots:hash: v1.k794b7964.e43f17182ff96d9f3bf99c4f43505215f9bda8bfc9cfbea0a205f52a5dff40d2.hi-taHZs3EIV72aJ9bMO_NjG-WuGgtL2lxr6iHAx7Nocomponents-hogcharts-timeseriesbarchart--grouped--light:hash: v1.k794b7964.c32979d833aead7e40f2c517f99b4507aea70c556637eb2775b22623cc22598c.2MT3W9PS7R1u4o-3ioE-sTrvINGzjw98B5CjlO00Kwg+ components-hogcharts-timeseriesbarchart--grouped-multiple-y-axes--dark:+ hash: v1.k794b7964.86d0101b7b8e35adeef827178134c31d771c61774f052434c733cea40d5096f9.ea3S4uhpKAjM1rxa_hhOfsR4yJvDDmhq9SEe-u7jdrQ+ components-hogcharts-timeseriesbarchart--grouped-multiple-y-axes--light:+ hash: v1.k794b7964.560aba051af54d6536a316d9435f8bf453e2f177f26255101fcd7633745757ef.DitSIG11N9IAP6AfBhXbP1P5NetsWhK-6lNET-ykH_Ecomponents-hogcharts-timeseriesbarchart--percent--dark:hash: v1.k794b7964.f93bc4e07e775e75bea135bc08913635c867b97368d82d1790646c4cf8beed60.6spfuVxBN-g51eHzBf1An1kY4adoOeHRkpZfPXWPLEwcomponents-hogcharts-timeseriesbarchart--percent--light:diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsxindex e24761dfad44..5520573d320b 100644--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx@@ -26,6 +26,7 @@ import type {ResolvedSeries,Series,TooltipContext,+ YAxisScale,} from '../../core/types'import { DEFAULT_Y_AXIS_ID } from '../../core/types'import { BarTooltip } from './BarTooltip'@@ -177,6 +178,20 @@ function BarChartInner<Meta = unknown>({const tickAxisLength = isHorizontal ? dimensions.plotWidth : dimensions.plotHeightconst yTickCount = yTickCountForHeight(tickAxisLength)+ // Expose per-axis scales so AxisLabels renders the right-hand axis and the tooltip /+ // value-label overlays resolve each series against its own axis.+ let yAxes: Record<string, YAxisScale> | undefined+ if (d3Scales.yAxes) {+ yAxes = {}+ for (const [axisId, { scale, position }] of Object.entries(d3Scales.yAxes)) {+ yAxes[axisId] = {+ scale: (value: number) => scale(value),+ ticks: () => scale.ticks?.(yTickCount) ?? [],+ position,+ }+ }+ }+// Stash the raw d3 scales in the private slot so drawStatic/drawHover/click routing// can read them from the committed ChartScales — every render gets a self-contained// object, which avoids strict-mode / concurrent-rendering races.@@ -197,6 +212,7 @@ function BarChartInner<Meta = unknown>({},y: (value: number) => d3Scales.value(value),yTicks: () => d3Scales.value.ticks?.(yTickCount) ?? [],+ yAxes,// Width of the rendered bar content within the band. In grouped mode the// bars sit inside group outer padding, so `band.bandwidth()` overshoots// the rightmost bar's right edge and anchors the tooltip in empty space.diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.stories.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.stories.tsxindex c31e8fff8e8d..0e9d4c5bc359 100644--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.stories.tsx+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.stories.tsx@@ -308,6 +308,40 @@ export const DualYAxis: Story = {},}+export const TripleYAxis: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series[] = [+ {+ key: 'sessions',+ label: 'Sessions',+ color: '',+ data: [70, 78, 72, 88, 75, 90, 80],+ yAxisId: DEFAULT_Y_AXIS_ID,+ },+ {+ key: 'pageviews',+ label: 'Pageviews',+ color: '',+ data: [140, 168, 150, 184, 160, 178, 170],+ yAxisId: 'y1',+ },+ {+ key: 'events',+ label: 'Events',+ color: '',+ data: [3500, 4200, 3600, 4500, 3800, 4100, 4000],+ yAxisId: 'y2',+ },+ ]+ return (+ <Stage>+ <LineChart series={series} labels={DAYS} config={BASIC} theme={theme} />+ </Stage>+ )+ },+}+/** Plain line with the trailing segment dashed via stroke.partial — the in-progress tail. */export const InProgressTail: Story = {render: () => {diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsxindex b41c5a640731..9acfcaf7f363 100644--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx@@ -182,6 +182,20 @@ describe('LineChart', () => {expect(chart.yRightTicks().length).toBeGreaterThan(0)})+ it('stacks a third axis on the left for a 3-axis chart (alternating sides)', () => {+ const series: Series[] = [+ { key: 'a', label: 'A', data: [10, 20, 30] },+ { key: 'b', label: 'B', data: [100, 200, 300], yAxisId: 'y1' },+ { key: 'c', label: 'C', data: [3000, 4000, 5000], yAxisId: 'y2' },+ ]+ const { chart } = renderHogChart(<LineChart series={series} labels={LABELS} theme={THEME} />)+ expect(chart.hasRightAxis).toBe(true)+ const leftValues = chart.yTicks().map((t) => parseFloat(t.replace(/[^0-9.]/g, '')))+ // 30 is the default axis max, 5000 the third axis max — both gutters stack on the left.+ expect(leftValues).toContain(30)+ expect(leftValues).toContain(5000)+ })+it('renders without crashing in yScaleType log with positive data', () => {const series: Series[] = [{ key: 'a', label: 'A', data: [1, 10, 100] }]const { chart } = renderHogChart(diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsxindex 98f2ce65d478..0d7ea4c1f5d2 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx@@ -62,6 +62,31 @@ export const Grouped: Story = {},}+// Grouped bars whose series span very different magnitudes — each is scaled against its own+// y-axis (`yAxisId`) so all three stay individually legible instead of the small series being+// flattened against the large one. Mirrors the legacy "show multiple y-axes" trends option.+const MULTI_AXIS_SERIES: Series[] = [+ { key: 'sessions', label: 'Sessions', data: [70, 78, 72, 88, 75, 90, 80] },+ { key: 'pageviews', label: 'Pageviews', data: [140, 168, 150, 184, 160, 178, 170], yAxisId: 'y1' },+ { key: 'events', label: 'Events', data: [3500, 4200, 3600, 4500, 3800, 4100, 4000], yAxisId: 'y2' },+]++export const GroupedMultipleYAxes: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage>+ <TimeSeriesBarChart+ series={MULTI_AXIS_SERIES}+ labels={DAYS}+ theme={theme}+ config={{ barLayout: 'grouped', yAxis: { showGrid: true } }}+ />+ </Stage>+ )+ },+}+export const Percent: Story = {render: () => {const theme = useReactiveTheme()diff --git a/packages/quill/packages/charts/src/core/Chart.tsx b/packages/quill/packages/charts/src/core/Chart.tsxindex 745c93fa3d72..2130f60f013a 100644--- a/packages/quill/packages/charts/src/core/Chart.tsx+++ b/packages/quill/packages/charts/src/core/Chart.tsx@@ -13,7 +13,7 @@ import { useChartDraw } from './hooks/useChartDraw'import { useChartInteraction } from './hooks/useChartInteraction'import { useChartMargins } from './hooks/useChartMargins'import { useLatest } from './hooks/useLatest'-import { useResolvedYFormatters } from './hooks/useResolvedYFormatters'+import { useResolvedYFormatter } from './hooks/useResolvedYFormatters'import { useStableResolveValue } from './hooks/useStableResolveValue'import type {ChartConfig,@@ -190,7 +190,7 @@ export function Chart<Meta = unknown>({return createScalesFn(coloredSeries, labels, dimensions)}, [coloredSeries, labels, dimensions, createScalesFn])- const { left: resolvedYFormatter, right: resolvedYRightFormatter } = useResolvedYFormatters(scales, yTickFormatter)+ const resolvedYFormatter = useResolvedYFormatter(scales, yTickFormatter)const { hoverIndex, hoverPosition, tooltipCtx, handlers } = useChartInteraction<Meta>({scales,@@ -306,7 +306,7 @@ export function Chart<Meta = unknown>({<AxisLabelsxTickFormatter={xTickFormatter}yTickFormatter={resolvedYFormatter}- yRightTickFormatter={resolvedYRightFormatter}+ userYTickFormatter={yTickFormatter}hideXAxis={hideXAxis}hideYAxis={hideYAxis}axisColor={axisColor}diff --git a/packages/quill/packages/charts/src/core/bar-layout.ts b/packages/quill/packages/charts/src/core/bar-layout.tsindex 722806ff703a..1ba072bc2285 100644--- a/packages/quill/packages/charts/src/core/bar-layout.ts+++ b/packages/quill/packages/charts/src/core/bar-layout.ts@@ -1,6 +1,7 @@import type { BarRect, BarRoundedCorners } from './canvas-renderer'import { type BarScaleSet, groupedBandSlot, type StackedBand } from './scales'import type { Series } from './types'+import { DEFAULT_Y_AXIS_ID } from './types'/** Brand for the BarChart `ChartScales._private` slot — populated by BarChart and* narrowed by its draw callbacks. */@@ -163,14 +164,18 @@ export function computeBarAtIndex({const shouldRoundBaseline = isGrouped ? false : (baseRounded ?? false)const bandWidth = scales.band.bandwidth()+ // Grouped multi-axis: each series scales against its own value axis. Falls back to the+ // shared `value` scale when only one axis is present (`yAxes` unset).+ const valueScale = scales.yAxes?.[series.yAxisId ?? DEFAULT_Y_AXIS_ID]?.scale ?? scales.value+if (isGrouped) {const slot = groupedBandSlot(scales, label, series.key)- const valuePixel = scales.value(raw)+ const valuePixel = valueScale(raw)if (!slot || !isFinite(valuePixel)) {return null}const corners = cornersFor(isHorizontal, raw >= 0, shouldRoundCap)- return makeBarRect(isHorizontal, slot.x, slot.width, scales.value(0), valuePixel, corners, dataIndex)+ return makeBarRect(isHorizontal, slot.x, slot.width, valueScale(0), valuePixel, corners, dataIndex)}const topPixel = scales.value(stackedBand!.top[dataIndex])diff --git a/packages/quill/packages/charts/src/core/bar-scales.test.ts b/packages/quill/packages/charts/src/core/bar-scales.test.tsindex eff682d0fc97..6eacd100ceb7 100644--- a/packages/quill/packages/charts/src/core/bar-scales.test.ts+++ b/packages/quill/packages/charts/src/core/bar-scales.test.ts@@ -260,4 +260,57 @@ describe('hog-charts bar scales', () => {expect(groupedBandSlot(stacked, 'a', 's1')).toBeUndefined()})})++ describe('createBarScales — multiple y-axes (grouped)', () => {+ const smallSeries = makeSeries({ key: 's1', data: [10, 20, 30] })+ const largeSeries = makeSeries({ key: 's2', data: [1000, 2000, 3000], yAxisId: 'y1' })++ it('builds a per-axis scale for each axis id, with the default axis on the left', () => {+ const { yAxes } = createBarScales([smallSeries, largeSeries], ['a', 'b', 'c'], dimensions, {+ barLayout: 'grouped',+ })+ expect(yAxes).not.toBeUndefined()+ expect(Object.keys(yAxes!).sort()).toEqual(['left', 'y1'])+ expect(yAxes!.left.position).toBe('left')+ expect(yAxes!.y1.position).toBe('right')+ })++ it('alternates sides for three axes (left, right, left)', () => {+ const third = makeSeries({ key: 's3', data: [50000, 60000, 70000], yAxisId: 'y2' })+ const { yAxes } = createBarScales([smallSeries, largeSeries, third], ['a', 'b', 'c'], dimensions, {+ barLayout: 'grouped',+ })+ expect(yAxes!.left.position).toBe('left')+ expect(yAxes!.y1.position).toBe('right')+ expect(yAxes!.y2.position).toBe('left')+ })++ it('scales each series against its own domain so both fill the plot height', () => {+ const { value, yAxes } = createBarScales([smallSeries, largeSeries], ['a', 'b', 'c'], dimensions, {+ barLayout: 'grouped',+ })+ // The small series' max (30) and the large series' max (3000) both map near the plot top+ // because each axis covers only its own series' range.+ expect(yAxes!.left.scale(30)).toBeCloseTo(yAxes!.y1.scale(3000), 0)+ // `value` is the primary (left) axis scale.+ expect(value(30)).toBeCloseTo(yAxes!.left.scale(30), 5)+ })++ it('keeps a single shared scale when only one axis id is present', () => {+ const { yAxes } = createBarScales(+ [smallSeries, makeSeries({ key: 's2', data: [40, 50, 60] })],+ ['a', 'b', 'c'],+ dimensions,+ { barLayout: 'grouped' }+ )+ expect(yAxes).toBeUndefined()+ })++ it('ignores per-series axes for stacked layouts (shared axis only)', () => {+ const { yAxes } = createBarScales([smallSeries, largeSeries], ['a', 'b', 'c'], dimensions, {+ barLayout: 'stacked',+ })+ expect(yAxes).toBeUndefined()+ })+ })})diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.tsindex db73c7bf71d8..2475bb2a6e97 100644--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts@@ -3,7 +3,7 @@ import { useMemo } from 'react'import { normalizeAxisLabel } from '../../utils/axis-labels'import { measureLabelWidth } from '../../utils/text-measure'-import { autoFormatterFor, seriesValueRange } from '../scales'+import { autoFormatterFor, orderedAxisPositions, seriesValueRange } from '../scales'import { DEFAULT_Y_AXIS_ID } from '../types'import type { ChartMargins, Series } from '../types'@@ -16,6 +16,9 @@ const Y_LABEL_RIGHT_PADDING = 12// Gutter left of the y-axis labels so the widest label doesn't sit flush at the plot's left edge// and clip against the chart wrapper's `overflow: hidden`.const Y_LABEL_LEFT_GUTTER = 6+/** Horizontal gap between stacked value-axis gutters on the same side — shared by the margin+ * reservation here and the gutter rendering in AxisLabels so the two can't drift. */+export const GUTTER_GAP = 12const X_LABEL_EDGE_PADDING = 4export const X_AXIS_TITLE_MARGIN = 22const Y_AXIS_TITLE_MARGIN = 24@@ -127,25 +130,56 @@ export function useChartMargins({return Math.ceil(widestCategoryLabelWidth(labels, xTickFormatter, maxCategoryLabelWidth) / 2)}, [labels, xTickFormatter, hideXAxis, isHorizontal, valueSeries, yTickFormatter, maxCategoryLabelWidth])+ // With multiple y-axes the value-axis labels stack into several gutters per side; reserve the+ // cumulative width so the outer gutters aren't clipped. Mirrors AxisLabels' gutter layout.+ const gutterReserves = useMemo<{ left: number; right: number } | null>(() => {+ if (hideYAxis || isHorizontal || !hasMultipleAxes) {+ return null+ }+ const byAxis = new Map<string, Series[]>()+ for (const s of valueSeries) {+ if (s.visibility?.excluded) {+ continue+ }+ const id = s.yAxisId ?? DEFAULT_Y_AXIS_ID+ const bucket = byAxis.get(id)+ if (bucket) {+ bucket.push(s)+ } else {+ byAxis.set(id, [s])+ }+ }+ let left = 0+ let right = 0+ for (const { axisId, position } of orderedAxisPositions(valueSeries)) {+ const width = Math.ceil(widestValueLabelWidth(byAxis.get(axisId) ?? [], yTickFormatter)) + Y_LABEL_RIGHT_PADDING+ if (position === 'left') {+ left += width + (left > 0 ? GUTTER_GAP : 0)+ } else {+ right += width + (right > 0 ? GUTTER_GAP : 0)+ }+ }+ return { left, right }+ }, [hideYAxis, isHorizontal, hasMultipleAxes, valueSeries, yTickFormatter])+return useMemo<ChartMargins>(() => {const bottom = hideXAxis? COLLAPSED_AXIS_MARGIN: DEFAULT_MARGINS.bottom + (normalizedXAxisLabel ? X_AXIS_TITLE_MARGIN : 0)+ const leftLabelReserve = gutterReserves ? gutterReserves.left : Math.ceil(yLabelWidth) + Y_LABEL_RIGHT_PADDINGconst left = hideYAxis? COLLAPSED_AXIS_MARGIN- : Math.max(- MIN_LEFT_MARGIN,- Math.ceil(yLabelWidth) + Y_LABEL_RIGHT_PADDING + Y_LABEL_LEFT_GUTTER,- xLabelHalfWidth + X_LABEL_EDGE_PADDING- ) + (normalizedYAxisLabel ? Y_AXIS_TITLE_MARGIN : 0)+ : Math.max(MIN_LEFT_MARGIN, leftLabelReserve + Y_LABEL_LEFT_GUTTER, xLabelHalfWidth + X_LABEL_EDGE_PADDING) ++ (normalizedYAxisLabel ? Y_AXIS_TITLE_MARGIN : 0)const rightFloor = hasMultipleAxes && !hideYAxis ? MIN_RIGHT_MARGIN_DUAL_AXIS : DEFAULT_MARGINS.right- const right = Math.max(rightFloor, xLabelHalfWidth + X_LABEL_EDGE_PADDING)+ const right = Math.max(rightFloor, gutterReserves?.right ?? 0, xLabelHalfWidth + X_LABEL_EDGE_PADDING)const computed: ChartMargins = { top: DEFAULT_MARGINS.top, right, bottom, left }return override ? { ...computed, ...override } : computed}, [hideXAxis,hideYAxis,hasMultipleAxes,+ gutterReserves,yLabelWidth,xLabelHalfWidth,normalizedXAxisLabel,diff --git a/packages/quill/packages/charts/src/core/hooks/useResolvedYFormatters.ts b/packages/quill/packages/charts/src/core/hooks/useResolvedYFormatters.tsindex 7db4c1cd3c05..a3b68d4c2edd 100644--- a/packages/quill/packages/charts/src/core/hooks/useResolvedYFormatters.ts+++ b/packages/quill/packages/charts/src/core/hooks/useResolvedYFormatters.ts@@ -5,27 +5,15 @@ import type { ChartScales } from '../types'type YTickFormatter = (value: number) => string-interface ResolvedYFormatters {- left: YTickFormatter- right: YTickFormatter | undefined-}--export function useResolvedYFormatters(+/** Resolves the left/primary y-axis tick formatter: the caller's formatter when set, else one+ * auto-derived from the primary axis ticks. Stacked secondary axes format themselves in+ * AxisLabels (each against its own ticks), so this only covers the primary axis. */+export function useResolvedYFormatter(scales: ChartScales | null,yTickFormatter: YTickFormatter | undefined-): ResolvedYFormatters {- const left = useMemo<YTickFormatter>(+): YTickFormatter {+ return useMemo<YTickFormatter>(() => yTickFormatter ?? autoFormatterFor(scales?.yTicks() ?? []),[yTickFormatter, scales])-- const right = useMemo<YTickFormatter | undefined>(() => {- if (yTickFormatter) {- return yTickFormatter- }- const rightAxis = scales?.yAxes && Object.values(scales.yAxes).find((a) => a.position === 'right')- return rightAxis ? autoFormatterFor(rightAxis.ticks()) : undefined- }, [yTickFormatter, scales])-- return { left, right }}diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.tsindex 718b3d7a1fa0..610fea95b915 100644--- a/packages/quill/packages/charts/src/core/scales.ts+++ b/packages/quill/packages/charts/src/core/scales.ts@@ -205,6 +205,40 @@ export function createYScale(.range([dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop])}+/** Order the visible series' axis ids — DEFAULT_Y_AXIS_ID first (when present), then the+ * remaining ids in first-encountered order — and assign alternating positions starting on the+ * left: index 0 left, 1 right, 2 left, 3 right, … Each side stacks its gutters outward in this+ * order. Mirrors the legacy multi-axis trends rendering and is shared by the scale builders and+ * the margin/axis-label layout so they agree on how many gutters sit on each side. */+export function orderedAxisPositions(series: Series[]): { axisId: string; position: 'left' | 'right' }[] {+ const axisIds = new Set(series.filter((s) => !s.visibility?.excluded).map((s) => s.yAxisId ?? DEFAULT_Y_AXIS_ID))+ const ordered = [+ ...(axisIds.has(DEFAULT_Y_AXIS_ID) ? [DEFAULT_Y_AXIS_ID] : []),+ ...Array.from(axisIds).filter((id) => id !== DEFAULT_Y_AXIS_ID),+ ]+ return ordered.map((axisId, i) => ({ axisId, position: i % 2 === 0 ? 'left' : 'right' }))+}++/** Bucket visible series by axis id in a single O(series) pass so per-axis scale builders look+ * their series up instead of re-filtering the whole list per axis (which is O(series²) when each+ * series has its own axis, as in `showMultipleYAxes`). */+export function groupVisibleSeriesByAxis(series: Series[]): Map<string, Series[]> {+ const byAxis = new Map<string, Series[]>()+ for (const s of series) {+ if (s.visibility?.excluded) {+ continue+ }+ const id = s.yAxisId ?? DEFAULT_Y_AXIS_ID+ const bucket = byAxis.get(id)+ if (bucket) {+ bucket.push(s)+ } else {+ byAxis.set(id, [s])+ }+ }+ return byAxis+}+export function createScales(series: Series[],labels: string[],@@ -219,8 +253,8 @@ export function createScales(): ScaleSet {const x = createXScale(labels, dimensions)- const axisIds = new Set(series.filter((s) => !s.visibility?.excluded).map((s) => s.yAxisId ?? DEFAULT_Y_AXIS_ID))- const hasMultipleAxes = axisIds.size > 1+ const positions = orderedAxisPositions(series)+ const hasMultipleAxes = positions.length > 1if (!hasMultipleAxes) {const y = createYScale(series, dimensions, {@@ -231,25 +265,18 @@ export function createScales(return { x, y }}- // DEFAULT_Y_AXIS_ID is always the left axis when present, regardless of series order.- // Remaining axis ids keep their first-encountered order and take the right position.- const orderedAxisIds = [- ...(axisIds.has(DEFAULT_Y_AXIS_ID) ? [DEFAULT_Y_AXIS_ID] : []),- ...Array.from(axisIds).filter((id) => id !== DEFAULT_Y_AXIS_ID),- ]-+ const byAxis = groupVisibleSeriesByAxis(series)const yAxes: Record<string, { scale: D3YScale; position: 'left' | 'right' }> = {}- orderedAxisIds.forEach((axisId, axisIndex) => {- const axisSeries = series.filter((s) => !s.visibility?.excluded && (s.yAxisId ?? DEFAULT_Y_AXIS_ID) === axisId)- const scale = createYScale(axisSeries, dimensions, {+ positions.forEach(({ axisId, position }, axisIndex) => {+ const scale = createYScale(byAxis.get(axisId) ?? [], dimensions, {scaleType: options.scaleType,percentStack: options.percentStack,valueDomain: axisIndex === 0 ? options.valueDomain : undefined,})- yAxes[axisId] = { scale, position: axisIndex === 0 ? 'left' : 'right' }+ yAxes[axisId] = { scale, position }})- const primaryAxis = yAxes[DEFAULT_Y_AXIS_ID] ?? yAxes[orderedAxisIds[0]]+ const primaryAxis = yAxes[DEFAULT_Y_AXIS_ID] ?? yAxes[positions[0].axisId]return { x, y: primaryAxis.scale, yAxes }}@@ -375,6 +402,10 @@ export interface BarScaleSet {value: D3YScale/** Sub-band for grouped layout — maps a series key to its offset inside a band. */group?: ScaleBand<string>+ /** Per-axis value scales keyed by axis id. Only populated for grouped layouts with+ * more than one axis id across the visible series (`showMultipleYAxes`). `value` is+ * the primary (left) axis scale. */+ yAxes?: Record<string, { scale: D3YScale; position: 'left' | 'right' }>}/** Band-axis slot of one series's bar within a grouped band: `{ x, width }` along the band axis.@@ -467,6 +498,30 @@ export function createBarScales(const valueSeries = series.map(restrictToKept)const valueStackedSeries = stackedSeries?.map(restrictToKept)+ // Multiple y-axes only make sense for grouped bars — each series keeps its own scale so+ // series of different magnitudes are individually comparable. Stacked/percent layouts share+ // one axis (stacking values on different scales is meaningless).+ const visibleSeries = valueSeries.filter((s) => !s.visibility?.excluded)+ const positions = orderedAxisPositions(visibleSeries)+ if (barLayout === 'grouped' && positions.length > 1) {+ const byAxis = groupVisibleSeriesByAxis(visibleSeries)+ const yAxes: Record<string, { scale: D3YScale; position: 'left' | 'right' }> = {}+ positions.forEach(({ axisId, position }, axisIndex) => {+ const scale = buildBarValueScale(+ byAxis.get(axisId) ?? [],+ valueRange,+ tickCount,+ 'grouped',+ scaleType,+ undefined,+ axisIndex === 0 ? valueDomain : undefined+ )+ yAxes[axisId] = { scale, position }+ })+ const primary = yAxes[DEFAULT_Y_AXIS_ID] ?? yAxes[positions[0].axisId]+ return { band, value: primary.scale, group, yAxes }+ }+return {band,value: buildBarValueScale(diff --git a/packages/quill/packages/charts/src/overlays/AxisLabels.tsx b/packages/quill/packages/charts/src/overlays/AxisLabels.tsxindex 37f6fd385719..7a76ea4ab3bb 100644--- a/packages/quill/packages/charts/src/overlays/AxisLabels.tsx+++ b/packages/quill/packages/charts/src/overlays/AxisLabels.tsx@@ -1,13 +1,16 @@import React, { useMemo } from 'react'import { useChartLayout } from '../core/chart-context'-import { AXIS_LABEL_FONT, getTextMeasureCtx, truncateToWidth } from '../utils/text-measure'+import { GUTTER_GAP } from '../core/hooks/useChartMargins'+import { autoFormatterFor } from '../core/scales'+import { AXIS_LABEL_FONT, getTextMeasureCtx, measureLabelWidth, truncateToWidth } from '../utils/text-measure'interface AxisLabelsProps {xTickFormatter?: (value: string, index: number) => string | nullyTickFormatter?: (value: number) => string- /** Formatter for the right y-axis. Falls back to `yTickFormatter` if not provided. */- yRightTickFormatter?: (value: number) => string+ /** The *unresolved* user y-tick formatter (config). When set, every stacked axis uses it; when+ * unset, each axis auto-formats against its own ticks. Only consulted for the multi-axis path. */+ userYTickFormatter?: (value: number) => stringhideXAxis?: booleanhideYAxis?: booleanaxisColor?: string@@ -131,6 +134,16 @@ const TICK_STYLE_BASE: React.CSSProperties = {const TICK_GAP = 8+/** One stacked value-axis gutter: its ticks, scale, side, and outward pixel offset from the plot edge. */+interface Gutter {+ key: string+ side: 'left' | 'right'+ offset: number+ ticks: number[]+ scale: (v: number) => number+ formatter: (v: number) => string+}+interface ChartBox {width: numberplotLeft: number@@ -153,6 +166,7 @@ function YTickLabel({color,dataAttr,title,+ offset = 0,}: {y: numberside: 'left' | 'right'@@ -161,11 +175,13 @@ function YTickLabel({color: stringdataAttr: stringtitle?: string+ /** Extra px pushing this gutter outward (away from the plot) so stacked axes don't overlap. */+ offset?: number}): React.ReactElement {const edge =side === 'left'- ? { right: box.width - box.plotLeft + TICK_GAP }- : { left: box.plotLeft + box.plotWidth + TICK_GAP }+ ? { right: box.width - box.plotLeft + TICK_GAP + offset }+ : { left: box.plotLeft + box.plotWidth + TICK_GAP + offset }return (<divdata-attr={dataAttr}@@ -213,7 +229,7 @@ function XTickLabel({export const AxisLabels = React.memo(function AxisLabels({xTickFormatter,yTickFormatter,- yRightTickFormatter,+ userYTickFormatter,hideXAxis,hideYAxis,axisColor = 'rgba(0, 0, 0, 0.5)',@@ -224,13 +240,46 @@ export const AxisLabels = React.memo(function AxisLabels({const { scales, dimensions, labels } = useChartLayout()const yTicks = scales.yTicks()- const rightAxis = useMemo(() => {+ // Vertical value-axis gutters, stacked outward per side. With per-axis scales (`scales.yAxes`,+ // i.e. `showMultipleYAxes`) we render one gutter per axis — each labelled with its own ticks and+ // offset by the cumulative width of the inner gutters. Without, a single left gutter from the+ // shared scale (`scales.y` / `scales.yTicks`). Each axis auto-formats against its own ticks+ // unless the caller supplied an explicit formatter, in which case every axis shares it.+ const yGutters = useMemo(() => {+ if (hideYAxis || orientation === 'horizontal') {+ return []+ }if (!scales.yAxes) {- return null+ return [+ {+ key: 'y-left',+ side: 'left' as const,+ offset: 0,+ ticks: yTicks,+ scale: scales.y,+ formatter: yTickFormatter ?? autoFormatterFor(yTicks),+ },+ ] satisfies Gutter[]}- return Object.values(scales.yAxes).find((a) => a.position === 'right') ?? null- }, [scales.yAxes])- const rightTicks = useMemo(() => rightAxis?.ticks() ?? [], [rightAxis])+ const widthOf = (ticks: number[], formatter: (v: number) => string): number =>+ ticks.reduce((widest, t) => Math.max(widest, measureLabelWidth(formatter(t))), 0)+ let leftCum = 0+ let rightCum = 0+ const gutters: Gutter[] = []+ Object.entries(scales.yAxes).forEach(([axisId, axis]) => {+ const ticks = axis.ticks()+ const formatter = userYTickFormatter ?? autoFormatterFor(ticks)+ const offset = axis.position === 'left' ? leftCum : rightCum+ gutters.push({ key: `y-${axisId}`, side: axis.position, offset, ticks, scale: axis.scale, formatter })+ const width = widthOf(ticks, formatter) + GUTTER_GAP+ if (axis.position === 'left') {+ leftCum += width+ } else {+ rightCum += width+ }+ })+ return gutters+ }, [hideYAxis, orientation, scales.yAxes, scales.y, yTicks, yTickFormatter, userYTickFormatter])const visibleXLabels = useMemo(() =>@@ -248,8 +297,6 @@ export const AxisLabels = React.memo(function AxisLabels({[hideXAxis, orientation, yTicks, scales.y, yTickFormatter])- const rightFormatter = yRightTickFormatter ?? yTickFormatter-if (orientation === 'horizontal') {// In horizontal mode `scales.y` holds value→x-pixel and the label→y-pixel function lives// on `scales.x` (or `labelToCoord` if explicitly overridden).@@ -296,46 +343,26 @@ export const AxisLabels = React.memo(function AxisLabels({return (<>- {!hideYAxis &&- yTicks.map((tick: number) => {- const y = scales.y(tick)- if (!isFinite(y)) {- return null- }- const label = yTickFormatter ? yTickFormatter(tick) : String(tick)- return (- <YTickLabel- key={`y-${tick}`}- y={y}- side="left"- box={dimensions}- text={label}- color={axisColor}- dataAttr="hog-chart-axis-tick-y"- />- )- })}-- {!hideYAxis &&- rightAxis &&- rightTicks.map((tick: number) => {- const y = rightAxis.scale(tick)+ {yGutters.flatMap((gutter) =>+ gutter.ticks.map((tick: number) => {+ const y = gutter.scale(tick)if (!isFinite(y)) {return null}- const label = rightFormatter ? rightFormatter(tick) : String(tick)return (<YTickLabel- key={`yr-${tick}`}+ key={`${gutter.key}-${tick}`}y={y}- side="right"+ side={gutter.side}+ offset={gutter.offset}box={dimensions}- text={label}+ text={gutter.formatter(tick)}color={axisColor}- dataAttr="hog-chart-axis-tick-yr"+ dataAttr={gutter.side === 'left' ? 'hog-chart-axis-tick-y' : 'hog-chart-axis-tick-yr'}/>)- })}+ })+ )}{visibleXLabels.map(({ index, text, title, x }) => (<XTickLabeldiff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsxindex a90d3e266a44..331f34fa8210 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx@@ -107,6 +107,7 @@ export function TrendsBarChart({getTrendsHidden,goalLines,showValuesOnSeries,+ showMultipleYAxes,} = useValues(trendsDataLogic(insightProps))const { timezone, weekStartDay, baseCurrency } = useValues(teamLogic)const { aggregationLabel } = useValues(groupsModel)@@ -116,6 +117,9 @@ export function TrendsBarChart({const isAggregated = display === ChartDisplayType.ActionsBarValueconst isGrouped = display === ChartDisplayType.ActionsUnstackedBarconst isPercentStackView = !isAggregated && !!showPercentStackView && !!supportsPercentStackView+ // Per-series y-axes are only meaningful for grouped (unstacked) bars — stacked layouts share+ // one axis. Mirrors the legacy ActionsLineGraph, which assigns y0/y1/… per dataset.+ const applyMultipleYAxes = !!showMultipleYAxes && isGroupedconst resolvedGroupTypeLabel = resolveGroupTypeLabel(labelGroupType, aggregationLabel, context?.groupTypeLabel)@@ -154,6 +158,7 @@ export function TrendsBarChart({getColor: getTrendsColor,getHidden: getTrendsHidden,buildMeta: buildTrendsSeriesMeta,+ showMultipleYAxes: applyMultipleYAxes,})return {series: timeSeries,@@ -168,6 +173,7 @@ export function TrendsBarChart({currentPeriodResult?.labels,stackBreakdowns,getAggregatedDisplayLabel,+ applyMultipleYAxes,])const valueLabelFormatter = useCallback(@@ -296,9 +302,20 @@ export function TrendsBarChart({[isAggregated, goalLines, series])- // Bar charts don't yet expose multi-axis configuration, so all series live on the- // primary axis — alert anomaly markers always read the default scale.- const getYAxisId = useCallback(() => DEFAULT_Y_AXIS_ID, [])+ 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]+ )const onPointClick = useCallback((clickData: PointClickData) => {diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.tsindex 00a0a03983c2..32f2a20bffa2 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts@@ -73,6 +73,15 @@ describe('buildTrendsBarTimeSeries', () => {const series = buildTrendsBarTimeSeries([makeResult({ label: null })], { getColor: () => RED })expect(series[0].label).toBe('')})++ 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' })]+ const series = buildTrendsBarTimeSeries(results, { getColor: () => RED, showMultipleYAxes })+ expect(series.map((s) => s.yAxisId)).toEqual(expected)+ })})describe('buildTrendsBarAggregatedSeries', () => {diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.tsindex 7a461a78c827..6ce9ac47f500 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts@@ -1,4 +1,4 @@-import { normalizeAxisLabel } from '@posthog/quill-charts'+import { DEFAULT_Y_AXIS_ID, normalizeAxisLabel } from '@posthog/quill-charts'import type { Series, TimeInterval, TimeSeriesBarChartConfig } from '@posthog/quill-charts'import { schemaGoalLinesToConfigs } from '../shared/goalLinesAdapter'@@ -48,6 +48,9 @@ export interface BuildTrendsBarSeriesOpts<R extends TrendsBarResultLike, M = unkgetColor: (r: R, index: number) => stringgetHidden?: (r: R, index: number) => booleanbuildMeta?: (r: R, index: number) => M+ // 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.+ showMultipleYAxes?: boolean}export interface BuildTrendsBarAggregatedSeriesOpts<@@ -78,12 +81,14 @@ function buildMainTrendsBarSeries<R extends TrendsBarResultLike, M = unknown>(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: r.label ?? '',data,color,meta,+ yAxisId,visibility: excluded ? { excluded: true } : undefined,}}