: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
feat(charts): dual y-axis for bar/combo charts, range-based stacked tooltip, multi-axis scale fix (#67525)
Sam Pennington0ada2d077375
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.tsindex c29a34423134..343b0ecf95c5 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts@@ -436,7 +436,7 @@ export function buildBarChartConfig({goalLines,visualizationType,ySeriesData,-}: BuildBarConfigArgs): TimeSeriesBarChartConfig {+}: BuildBarConfigArgs): TimeSeriesBarChartConfig & { yAxis?: YAxisConfig } {const barLayout = barLayoutForDisplay(visualizationType, chartSettings)const labelFormatter = buildSqlDateLabelFormatter(xData, timezone)@@ -465,7 +465,7 @@ export function buildComboChartConfig({goalLines,visualizationType,ySeriesData,-}: BuildBarConfigArgs): TimeSeriesComboChartConfig {+}: BuildBarConfigArgs): TimeSeriesComboChartConfig & { yAxis?: YAxisConfig } {const labelFormatter = buildSqlDateLabelFormatter(xData, timezone)return {diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsxindex e4e88037cf7b..8f5b5b961f11 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx@@ -17,6 +17,9 @@ import { TrendLineOverlay } from '../../overlays/TrendLineOverlay'import { ValueLabels } from '../../overlays/ValueLabels'import { buildGoalLineReferenceLines, goalLineValueDomain, type GoalLineConfig } from '../../utils/goal-lines'import {+ buildYAxes,+ normalizeYAxisList,+ primaryYAxisConfig,useXTickFormatter,useYTickFormatter,type XAxisConfig,@@ -32,7 +35,8 @@ import {export interface TimeSeriesBarChartConfig {xAxis?: XAxisConfig- yAxis?: YAxisConfig+ /** Single object for a standard left axis; array for dual left+right axes (pass `id` and `position` on each). */+ yAxis?: YAxisConfig | YAxisConfig[]valueLabels?: boolean | ValueLabelsConfiggoalLines?: GoalLineConfig[]/** Defaults to `stacked`. */@@ -101,8 +105,12 @@ export function TimeSeriesBarChart<Meta = unknown>({legend,trendLines,} = config ?? {}+ const axisList = useMemo(() => normalizeYAxisList(yAxis), [yAxis])+ const primaryYAxis = useMemo<YAxisConfig | undefined>(() => primaryYAxisConfig(axisList), [axisList])+ const yAxes = useMemo(() => (Array.isArray(yAxis) ? buildYAxes(axisList) : undefined), [yAxis, axisList])+const xTickFormatter = useXTickFormatter(xAxis, labels)- const yTickFormatter = useYTickFormatter(yAxis)+ const yTickFormatter = useYTickFormatter(primaryYAxis)const { visibleSeries, legendProps } = useChartLegend(series, theme, legend)@@ -137,20 +145,21 @@ export function TimeSeriesBarChart<Meta = unknown>({}, [trendLines, visibleSeries])const barChartConfig: BarChartConfig = {- yScaleType: yAxis?.scale,+ yScaleType: primaryYAxis?.scale,xTickFormatter,yTickFormatter,hideXAxis: xAxis?.hide,- hideYAxis: yAxis?.hide,+ hideYAxis: primaryYAxis?.hide,xAxisLabel: xAxis?.label,- yAxisLabel: yAxis?.label,- showGrid: yAxis?.showGrid,+ yAxisLabel: primaryYAxis?.label,+ showGrid: primaryYAxis?.showGrid,showAxisLines,barLayout,axisOrientation,showCrosshair,tooltip: tooltipConfig,animateHover,+ yAxes,bars: {cornerRadius: barCornerRadius,divergingStack,diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsxindex 70d159f7fb95..980a786d1501 100644--- a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx+++ b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx@@ -17,6 +17,9 @@ import { TrendLineOverlay } from '../../overlays/TrendLineOverlay'import { ValueLabels } from '../../overlays/ValueLabels'import { buildGoalLineReferenceLines, goalLineValueDomain, type GoalLineConfig } from '../../utils/goal-lines'import {+ buildYAxes,+ normalizeYAxisList,+ primaryYAxisConfig,useXTickFormatter,useYTickFormatter,type XAxisConfig,@@ -32,7 +35,8 @@ import {export interface TimeSeriesComboChartConfig {xAxis?: XAxisConfig- yAxis?: YAxisConfig+ /** Single object for a standard left axis; array for dual left+right axes. */+ yAxis?: YAxisConfig | YAxisConfig[]valueLabels?: boolean | ValueLabelsConfiggoalLines?: GoalLineConfig[]/** Type used for series that don't set {@link Series.type}. Defaults to `'line'`. */@@ -96,8 +100,12 @@ export function TimeSeriesComboChart<Meta = unknown>({legend,trendLines,} = config ?? {}+ const axisList = useMemo(() => normalizeYAxisList(yAxis), [yAxis])+ const primaryYAxis = useMemo<YAxisConfig | undefined>(() => primaryYAxisConfig(axisList), [axisList])+ const yAxes = useMemo(() => (Array.isArray(yAxis) ? buildYAxes(axisList) : undefined), [yAxis, axisList])+const xTickFormatter = useXTickFormatter(xAxis, labels)- const yTickFormatter = useYTickFormatter(yAxis)+ const yTickFormatter = useYTickFormatter(primaryYAxis)const { visibleSeries, legendProps } = useChartLegend(series, theme, legend)@@ -130,14 +138,14 @@ export function TimeSeriesComboChart<Meta = unknown>({}, [trendLines, visibleSeries])const comboChartConfig: ComboChartConfig = {- yScaleType: yAxis?.scale,+ yScaleType: primaryYAxis?.scale,xTickFormatter,yTickFormatter,hideXAxis: xAxis?.hide,- hideYAxis: yAxis?.hide,+ hideYAxis: primaryYAxis?.hide,xAxisLabel: xAxis?.label,- yAxisLabel: yAxis?.label,- showGrid: yAxis?.showGrid,+ yAxisLabel: primaryYAxis?.label,+ showGrid: primaryYAxis?.showGrid,showAxisLines,showCrosshair,defaultSeriesType,@@ -145,6 +153,7 @@ export function TimeSeriesComboChart<Meta = unknown>({barCornerRadius,tooltip: tooltipConfig,valueDomain,+ yAxes,}return (diff --git a/packages/quill/packages/charts/src/core/interaction.ts b/packages/quill/packages/charts/src/core/interaction.tsindex 13e1e62e206c..f12961190117 100644--- a/packages/quill/packages/charts/src/core/interaction.ts+++ b/packages/quill/packages/charts/src/core/interaction.ts@@ -99,9 +99,9 @@ export function buildTooltipContext<Meta = unknown>(* Stacked charts pass the stacked-top resolver here so the anchor lands at the visual top* of each segment while each tooltip row still shows its own value via `resolveValue`. */resolvePositionValue: ResolveValueFn = resolveValue,- /** Resolves the stacked *bottom* value for each series — used to compute the segment midpoint- * for tooltip row highlighting. When provided, yPixel is set to the segment midpoint so- * findClosestSeriesKey transitions at the visual boundary between segments. */+ /** Resolves the stacked *bottom* value for each series. When provided, yPixelBottom is+ * stored alongside yPixel so findClosestSeriesKey can use range containment rather than+ * distance — cursor inside [yPixel, yPixelBottom] wins exactly at the segment boundary. */resolveBottomValue?: ResolveValueFn,/** Optional horizontal data-extent centered on the categorical axis position — bar charts* pass band width so the tooltip can anchor at the band edge instead of its center. */@@ -142,20 +142,22 @@ export function buildTooltipContext<Meta = unknown>(const bar = s.bars?.[dataIndex]const entrySeries = bar ? { ...s, meta: bar.meta ?? s.meta, label: bar.label ?? s.label } : sconst segmentValue = resolveValue(s, dataIndex)- // When resolveBottomValue is provided (stacked bar charts), use the segment midpoint- // so findClosestSeriesKey transitions exactly at the visual boundary between segments.- let yPx = px- if (isFinite(px) && resolveBottomValue) {- const bottomPx = seriesValueScale(resolveBottomValue(s, dataIndex))- if (isFinite(bottomPx)) {- yPx = (px + bottomPx) / 2- }- }+ // Expose the segment bottom pixel so findClosestSeriesKey can do range containment+ // testing (is cursor between top and bottom?) instead of distance-to-midpoint, which+ // breaks when adjacent segments differ greatly in size.+ const yPixelBottom =+ resolveBottomValue && isFinite(px)+ ? (() => {+ const b = seriesValueScale(resolveBottomValue(s, dataIndex))+ return isFinite(b) ? b : undefined+ })()+ : undefinedseriesData.push({series: entrySeries,value: segmentValue,color: barColorAt(s, dataIndex),- yPixel: isFinite(yPx) ? yPx : undefined,+ yPixel: isFinite(px) ? px : undefined,+ yPixelBottom,})}}diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.tsindex 07551035864b..ebb9a5af47d2 100644--- a/packages/quill/packages/charts/src/core/scales.ts+++ b/packages/quill/packages/charts/src/core/scales.ts@@ -614,22 +614,26 @@ 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).+ // Build per-axis scales for grouped layouts with multiple axes. Stacked/percent layouts+ // share a single value axis — per-series yAxisId is ignored so the stack is consistent.const visibleSeries = valueSeries.filter((s) => !s.visibility?.excluded)const positions = orderedAxisPositions(visibleSeries)- if (barLayout === 'grouped' && positions.length > 1) {+ if (positions.length > 1 && barLayout === 'grouped') {const byAxis = groupVisibleSeriesByAxis(visibleSeries)const yAxes: Record<string, { scale: D3YScale; position: 'left' | 'right' }> = {}positions.forEach(({ axisId, position }, axisIndex) => {+ const axisSeries = byAxis.get(axisId) ?? []+ const axisKeys = new Set(axisSeries.map((s) => s.key))+ // Filter the pre-computed stacked tops to this axis so the domain reflects+ // the cumulative stack for this axis's series, not raw individual values.+ const axisStackedSeries = stackedSeries?.filter((s) => axisKeys.has(s.key))const scale = buildBarValueScale(- byAxis.get(axisId) ?? [],+ axisSeries,valueRange,tickCount,- 'grouped',+ barLayout,scaleType,- undefined,+ axisStackedSeries?.length ? axisStackedSeries : undefined,axisIndex === 0 ? valueDomain : undefined,valuePadding)diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex 3902b0fc75d7..ee05a5b803b7 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -149,8 +149,12 @@ export interface TooltipContext<Meta = unknown> {value: numbercolor: stringfraction?: number- /** Canvas y-pixel of this series at the hovered x — used for cursor-proximity sorting. */+ /** Canvas y-pixel of the value-axis anchor for this series (top of bar segment, or dot for lines). */yPixel?: number+ /** Canvas y-pixel of the bottom of this series's bar segment. When both yPixel and+ * yPixelBottom are present, hover detection uses range containment rather than+ * distance-to-midpoint, giving correct results regardless of segment size differences. */+ yPixelBottom?: number}[]/** Pixel position (relative to the chart container) for anchoring the tooltip.* `width` (optional) is the horizontal data-extent centered on `x` — bar chartsdiff --git a/packages/quill/packages/charts/src/overlays/tooltipUtils.test.ts b/packages/quill/packages/charts/src/overlays/tooltipUtils.test.tsindex 8f7ddb77b8ee..637b1525488a 100644--- a/packages/quill/packages/charts/src/overlays/tooltipUtils.test.ts+++ b/packages/quill/packages/charts/src/overlays/tooltipUtils.test.ts@@ -5,6 +5,17 @@ const row = (key: string, yPixel?: number): { series: { key: string }; yPixel?:yPixel,})+// Stacked segment: yPixel = top pixel (smaller y = higher on screen), yPixelBottom = bottom pixel.+const segment = (+ key: string,+ yPixel: number,+ yPixelBottom: number+): { series: { key: string }; yPixel: number; yPixelBottom: number } => ({+ series: { key },+ yPixel,+ yPixelBottom,+})+describe('findClosestSeriesKey', () => {it('returns null when no entry has yPixel', () => {expect(findClosestSeriesKey([row('a'), row('b')], 100)).toBeNull()@@ -29,4 +40,41 @@ describe('findClosestSeriesKey', () => {it('prefers the first entry when distances are equal', () => {expect(findClosestSeriesKey([row('a', 80), row('b', 120)], 100)).toBe('a')})++ describe('range containment (stacked bar segments)', () => {+ // Three stacked segments in canvas coordinates (y=0 at top, increases downward):+ // A (bottom): top=150, bottom=300 → spans y 150..300+ // B (middle): top=75, bottom=150 → spans y 75..150+ // C (top): top=0, bottom=75 → spans y 0..75+ const segs = [segment('a', 150, 300), segment('b', 75, 150), segment('c', 0, 75)]++ it.each([+ // Cursor clearly inside each segment+ [250, 'a'],+ [112, 'b'],+ [30, 'c'],+ // Near boundaries but still inside+ [151, 'a'],+ [149, 'b'],+ ])('cursor y=%i → %s', (cursorY, expected) => {+ expect(findClosestSeriesKey(segs, cursorY)).toBe(expected)+ })++ it('catches the dead-zone bug: cursor near top of a tall lower segment still picks that segment', () => {+ // Without range containment, cursor at y=160 (inside A, range 150..300) would pick B+ // because B's midpoint (112) is closer than A's midpoint (225). Range containment fixes this.+ expect(findClosestSeriesKey(segs, 160)).toBe('a')+ })++ it('falls back to distance when cursor is outside all ranges', () => {+ // Cursor above all segments — picks the topmost (C, top=0) by distance.+ expect(findClosestSeriesKey(segs, -10)).toBe('c')+ })++ it('ignores yPixelBottom for entries that lack it, using distance fallback for those', () => {+ // Mix of range and non-range rows — range rows win when cursor is inside them.+ const mixed = [row('dist', 50), segment('range', 200, 300)]+ expect(findClosestSeriesKey(mixed, 250)).toBe('range')+ })+ })})diff --git a/packages/quill/packages/charts/src/overlays/tooltipUtils.ts b/packages/quill/packages/charts/src/overlays/tooltipUtils.tsindex 82fb6259c04e..5c5ce73033a6 100644--- a/packages/quill/packages/charts/src/overlays/tooltipUtils.ts+++ b/packages/quill/packages/charts/src/overlays/tooltipUtils.ts@@ -1,9 +1,26 @@-/** Returns the key of the series whose canvas y-pixel is closest to `cursorY`.- * Returns `null` when no entry carries `yPixel` data. */+/** Returns the key of the series whose segment contains `cursorY`, or the closest one by distance.+ *+ * When `yPixelBottom` is present alongside `yPixel` (stacked bar segments), uses range+ * containment: the series whose [top, bottom] range contains the cursor wins outright. This is+ * exact regardless of segment size differences — no midpoint dead-zones at boundaries.+ *+ * When only `yPixel` is present (line dots, non-stacked bars), falls back to closest by distance.+ */export function findClosestSeriesKey(- rows: Array<{ series: { key: string }; yPixel?: number }>,+ rows: Array<{ series: { key: string }; yPixel?: number; yPixelBottom?: number }>,cursorY: number): string | null {+ // Range containment pass — exact for stacked segments.+ for (const s of rows) {+ if (s.yPixel != null && s.yPixelBottom != null) {+ const lo = Math.min(s.yPixel, s.yPixelBottom)+ const hi = Math.max(s.yPixel, s.yPixelBottom)+ if (cursorY >= lo && cursorY <= hi) {+ return s.series.key+ }+ }+ }+ // Distance fallback for lines, dots, and non-stacked bars.let bestKey: string | null = nulllet bestDist = Infinityfor (const s of rows) {diff --git a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.tsindex fef047f80bb4..d4384c7ee3f6 100644--- a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts+++ b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts@@ -5,6 +5,7 @@ import type {TimeSeriesLineChartConfig,TooltipConfig,TrendLineConfig,+ YAxisConfig,} from '@posthog/quill-charts'import { schemaGoalLinesToConfigs } from 'products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter'@@ -112,7 +113,9 @@ export function buildRetentionLineChartConfig(opts: BuildRetentionChartConfigOpt}}-export function buildRetentionBarChartConfig(opts: BuildRetentionChartConfigOpts): TimeSeriesBarChartConfig {+export function buildRetentionBarChartConfig(+ opts: BuildRetentionChartConfigOpts+): TimeSeriesBarChartConfig & { yAxis?: YAxisConfig } {return {yAxis: {format: opts.isPercentage ? 'percentage' : 'numeric',@@ -251,7 +254,7 @@ export interface RetentionChartModel {series: Series<RetentionSeriesMeta>[]labels: string[]lineConfig: TimeSeriesLineChartConfig- barConfig: TimeSeriesBarChartConfig+ barConfig: TimeSeriesBarChartConfig & { yAxis?: YAxisConfig }/** Cohort count before the `maxCohorts` cap — lets the host show a truncation notice. */totalCohorts: number}diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/stickinessBarChartTransforms.ts b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/stickinessBarChartTransforms.tsindex 824f7bab2136..d1e28ffcbb47 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/stickinessBarChartTransforms.ts+++ b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/stickinessBarChartTransforms.ts@@ -1,4 +1,4 @@-import type { TimeSeriesBarChartConfig, TooltipConfig } from '@posthog/quill-charts'+import type { TimeSeriesBarChartConfig, TooltipConfig, YAxisConfig } from '@posthog/quill-charts'import {buildStickinessSeries,@@ -19,7 +19,7 @@ export interface BuildStickinessBarTimeSeriesConfigOpts {export function buildStickinessBarTimeSeriesConfig(opts: BuildStickinessBarTimeSeriesConfigOpts-): TimeSeriesBarChartConfig {+): TimeSeriesBarChartConfig & { yAxis?: YAxisConfig } {// No xAxis date config — labels are pre-formatted interval counts (Day 0, Day 1, …).return {yAxis: buildStickinessYAxisConfig({ yAxisScaleType: opts.yAxisScaleType, showGrid: opts.showGrid }),diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.tsindex dd0be2439d4e..173d8cc77820 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts@@ -1,5 +1,5 @@import { DEFAULT_Y_AXIS_ID, normalizeAxisLabel } from '@posthog/quill-charts'-import type { Series, TimeInterval, TimeSeriesBarChartConfig } from '@posthog/quill-charts'+import type { Series, TimeInterval, TimeSeriesBarChartConfig, YAxisConfig } from '@posthog/quill-charts'import { COMPARE_PREVIOUS_DIM_OPACITY, dimHexColor } from '../shared/compareDimming'import { schemaGoalLinesToConfigs } from '../shared/goalLinesAdapter'@@ -101,7 +101,9 @@ export interface BuildTrendsBarTimeSeriesConfigOpts {tooltip?: TimeSeriesBarChartConfig['tooltip']}-export function buildTrendsBarTimeSeriesConfig(opts: BuildTrendsBarTimeSeriesConfigOpts): TimeSeriesBarChartConfig {+export function buildTrendsBarTimeSeriesConfig(+ opts: BuildTrendsBarTimeSeriesConfigOpts+): TimeSeriesBarChartConfig & { yAxis?: YAxisConfig } {const yAxis = buildTrendsYAxisConfig(opts.trendsFilter, opts.isPercentStackView, opts.baseCurrency, {yAxisScaleType: opts.yAxisScaleType,showGrid: true,diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.tsindex d4e014773851..2a20fcabf912 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms.ts@@ -1,4 +1,10 @@-import type { Series, TimeInterval, TimeSeriesBarChartConfig, ValueLabelFormatter } from '@posthog/quill-charts'+import type {+ Series,+ TimeInterval,+ TimeSeriesBarChartConfig,+ ValueLabelFormatter,+ YAxisConfig,+} from '@posthog/quill-charts'import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'import type { YFormatterFields } from '../shared/trendsChartDisplayOptions'@@ -124,7 +130,9 @@ export interface BuildTrendsLifecycleConfigOpts {legend?: TimeSeriesBarChartConfig['legend']}-export function buildTrendsLifecycleConfig(opts: BuildTrendsLifecycleConfigOpts): TimeSeriesBarChartConfig {+export function buildTrendsLifecycleConfig(+ opts: BuildTrendsLifecycleConfigOpts+): TimeSeriesBarChartConfig & { yAxis?: YAxisConfig } {const yAxis = buildTrendsYAxisConfig(opts.trendsFilter, false, opts.baseCurrency, {yAxisScaleType: opts.yAxisScaleType,showGrid: true,