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.

fix(insights): stacked bar tooltip shows per-series, not cumulative (#59576)

Georgis Andonis5d5f9e6d1c26
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
index d03e6c6d6aff..cfaef78c7683 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
@@ -1,6 +1,6 @@
import { fireEvent, waitFor } from '@testing-library/react'
-import type { BarChartConfig, ChartTheme, Series } from '../../core/types'
+import type { BarChartConfig, ChartTheme, PointClickData, Series } from '../../core/types'
import { ReferenceLine } from '../../overlays/ReferenceLine'
import { renderHogChart } from '../../testing'
import { dimensions } from '../../testing/jsdom'
@@ -207,6 +207,49 @@ describe('BarChart', () => {
expect(tooltip.seriesData.map((s) => s.series.key)).toEqual(expectedKeys)
})
+ it('stacked tooltip shows each series own value, not the cumulative stack total', async () => {
+ // At index 1: a=20 (bottom) and b=15 stacked on top. b's stacked top is 35, but the
+ // tooltip must report b's own 15 — the segment, not the running total.
+ const { chart } = renderHogChart(
+ <BarChart series={SERIES} labels={LABELS} theme={THEME} config={{ barLayout: 'stacked' }} />
+ )
+ chart.hoverAtIndex(1)
+ const tooltip = await chart.waitForTooltip()
+ expect(tooltip.series.a.value).toBe(20)
+ expect(tooltip.series.b.value).toBe(15)
+ })
+
+ it('percent tooltip shows each series own fraction, not the cumulative fraction', async () => {
+ // At index 1: a=20, b=15 → total 35. b sits on top of a, so b's cumulative top is 1.0,
+ // but the tooltip must report b's own 15/35 fraction — the segment, not the running total.
+ const { chart } = renderHogChart(
+ <BarChart series={SERIES} labels={LABELS} theme={THEME} config={{ barLayout: 'percent' }} />
+ )
+ chart.hoverAtIndex(1)
+ const tooltip = await chart.waitForTooltip()
+ expect(tooltip.series.a.value).toBeCloseTo(20 / 35, 5)
+ expect(tooltip.series.b.value).toBeCloseTo(15 / 35, 5)
+ })
+
+ it('stacked onPointClick reports each series own value, not the cumulative stack total', async () => {
+ const onPointClick = jest.fn()
+ const { chart } = renderHogChart(
+ <BarChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ barLayout: 'stacked' }}
+ onPointClick={onPointClick}
+ />
+ )
+ await chart.clickAtIndex(1)
+ const clickData: PointClickData = onPointClick.mock.calls[0][0]
+ expect(clickData.crossSeriesData.map((d) => ({ key: d.series.key, value: d.value }))).toEqual([
+ { key: 'a', value: 20 },
+ { key: 'b', value: 15 },
+ ])
+ })
+
it.each<[string, BarChartConfig]>([
['grouped', { barLayout: 'grouped' } as BarChartConfig],
['stacked', { barLayout: 'stacked' } as BarChartConfig],
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
index d574e26476e5..030dd17c5704 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
@@ -6,7 +6,8 @@ import { type BarRect, drawBarHighlight, drawBars, drawGrid, type DrawContext }
import { Chart } from '../../core/Chart'
import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
import {
- buildStackedResolveValue,
+ buildSegmentResolveValue,
+ buildStackedPositionValue,
computePercentStackData,
computeStackData,
createBarScales,
@@ -300,7 +301,10 @@ function BarChartInner<Meta = unknown>({
[stackedData, barLayout, isHorizontal, topStackedKeyByAxis, barCornerRadius]
)
- const resolveValue = useMemo(() => buildStackedResolveValue(stackedData), [stackedData])
+ // Show each series's own segment value (resolveValue) but anchor the tooltip/value labels
+ // at the stacked top (resolvePositionValue) so a stacked bar doesn't read as a running total.
+ const resolveValue = useMemo(() => buildSegmentResolveValue(stackedData), [stackedData])
+ const resolvePositionValue = useMemo(() => buildStackedPositionValue(stackedData), [stackedData])
return (
<Chart
@@ -325,6 +329,7 @@ function BarChartInner<Meta = unknown>({
className={className}
dataAttr={dataAttr}
resolveValue={resolveValue}
+ resolvePositionValue={resolvePositionValue}
>
{children}
</Chart>
diff --git a/frontend/src/lib/hog-charts/charts/LineChart.tsx b/frontend/src/lib/hog-charts/charts/LineChart.tsx
index 944321ded6a7..8684891fec36 100644
--- a/frontend/src/lib/hog-charts/charts/LineChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/LineChart.tsx
@@ -5,7 +5,8 @@ import type { DrawContext } from '../core/canvas-renderer'
import { Chart } from '../core/Chart'
import { ChartErrorBoundary } from '../core/ChartErrorBoundary'
import {
- buildStackedResolveValue,
+ buildSegmentResolveValue,
+ buildStackedPositionValue,
computePercentStackData,
computeStackData,
createScales as createLineScales,
@@ -228,7 +229,10 @@ function LineChartInner<Meta = unknown>({
[stackedData]
)
- const resolveValue = useMemo(() => buildStackedResolveValue(stackedData), [stackedData])
+ // Stacked/percent-stacked areas: display each series's own segment value (resolveValue)
+ // but anchor the tooltip/value labels at the stacked top (resolvePositionValue).
+ const resolveValue = useMemo(() => buildSegmentResolveValue(stackedData), [stackedData])
+ const resolvePositionValue = useMemo(() => buildStackedPositionValue(stackedData), [stackedData])
return (
<Chart
@@ -244,6 +248,7 @@ function LineChartInner<Meta = unknown>({
className={className}
dataAttr={dataAttr}
resolveValue={resolveValue}
+ resolvePositionValue={resolvePositionValue}
>
{children}
</Chart>
diff --git a/frontend/src/lib/hog-charts/core/Chart.tsx b/frontend/src/lib/hog-charts/core/Chart.tsx
index 65b4a88e49d9..30941a4e622f 100644
--- a/frontend/src/lib/hog-charts/core/Chart.tsx
+++ b/frontend/src/lib/hog-charts/core/Chart.tsx
@@ -72,13 +72,18 @@ export interface ChartProps<Meta = unknown> {
className?: string
dataAttr?: string
children?: React.ReactNode
- /** Resolves the y-value for a series at a given index. Defaults to series.data[index].
- * Identity is read live for tooltip values and overlays, but the pinned-tooltip
+ /** Resolves the y-value to *display* for a series at a given index. Defaults to
+ * series.data[index]. Identity is read live for tooltip values, but the pinned-tooltip
* rebuild only refires when `series`, `labels`, or `scales` change. Callers that
* derive values from data not reflected in those (e.g. an external "%" toggle)
* should ensure that toggle also updates `series` or the chart's scales — otherwise
* a held pin will keep showing values from the previous resolver. */
resolveValue?: ResolveValueFn
+ /** Value used to *anchor* the tooltip and value-label overlays per series. Defaults to
+ * `resolveValue`. Stacked charts pass the stacked-top resolver here so overlays land at the
+ * visual top of each segment, while each tooltip row still shows that series's own value
+ * via `resolveValue`. */
+ resolvePositionValue?: ResolveValueFn
/** Required for horizontal orientation — maps labels to the coordinate on the categorical
* axis (y in horizontal mode). Should be referentially stable; non-stable identities
* invalidate the interaction memo on every render. */
@@ -99,6 +104,7 @@ export function Chart<Meta = unknown>({
dataAttr,
children,
resolveValue,
+ resolvePositionValue,
labelToCoord,
}: ChartProps<Meta>): React.ReactElement {
const {
@@ -159,6 +165,7 @@ export function Chart<Meta = unknown>({
pinnable: pinnableTooltip,
onPointClick,
resolveValue,
+ resolvePositionValue,
interactionAxis,
labelToCoord,
})
@@ -202,7 +209,9 @@ export function Chart<Meta = unknown>({
[canvasRef]
)
- const stableResolveValue = useStableResolveValue(resolveValue)
+ // Overlays (value labels) anchor at the stacked top, so expose the position resolver —
+ // falling back to the value resolver when the chart doesn't stack.
+ const stablePositionValue = useStableResolveValue(resolvePositionValue ?? resolveValue)
const axisValue = useMemo(
() => ({ orientation: axisOrientation, xTickFormatter, isPercent }),
@@ -219,11 +228,11 @@ export function Chart<Meta = unknown>({
labels,
series: coloredSeries,
theme,
- resolveValue: stableResolveValue,
+ resolvePositionValue: stablePositionValue,
canvasBounds,
axis: axisValue,
}
- }, [scales, dimensions, labels, coloredSeries, theme, stableResolveValue, canvasBounds, axisValue])
+ }, [scales, dimensions, labels, coloredSeries, theme, stablePositionValue, canvasBounds, axisValue])
const hoverValue = useMemo<ChartHoverContextValue>(() => ({ hoverIndex }), [hoverIndex])
diff --git a/frontend/src/lib/hog-charts/core/chart-context.test.tsx b/frontend/src/lib/hog-charts/core/chart-context.test.tsx
index 40bd8ba3fbb7..37372527a1db 100644
--- a/frontend/src/lib/hog-charts/core/chart-context.test.tsx
+++ b/frontend/src/lib/hog-charts/core/chart-context.test.tsx
@@ -13,7 +13,7 @@ const LAYOUT: ChartLayoutContextValue = {
series: [],
scales: { x: () => 0, y: () => 0, yTicks: () => [] },
theme: THEME,
- resolveValue: (s, i) => s.data[i] ?? 0,
+ resolvePositionValue: (s, i) => s.data[i] ?? 0,
canvasBounds: () => null,
axis: { orientation: 'vertical', xTickFormatter: undefined, isPercent: false },
}
diff --git a/frontend/src/lib/hog-charts/core/chart-context.ts b/frontend/src/lib/hog-charts/core/chart-context.ts
index d0af2ff2a1dc..34ad5f1acb77 100644
--- a/frontend/src/lib/hog-charts/core/chart-context.ts
+++ b/frontend/src/lib/hog-charts/core/chart-context.ts
@@ -28,10 +28,11 @@ export interface ChartLayoutContextValue<Meta = unknown> {
/** Theme passed to the chart. Use {@link ChartTheme.backgroundColor} for borders/fills
* that need to blend into the chart background (e.g. value-label borders). */
theme: ChartTheme
- /** Resolves the y-value for a series at a given index. Honors stacking when the
- * parent chart provides a stacked resolver — overlays should always go through
- * this rather than reading `series.data[i]` directly. */
- resolveValue: ResolveValueFn
+ /** Resolves the y-value used to *position* (anchor) a series at a given index — the
+ * stacked top when the parent chart stacks, otherwise the raw value. Overlays use this
+ * for placement (e.g. value-label anchoring). The value to *display* is the series's own
+ * segment; read it from `series.data[i]`, not from this resolver. */
+ resolvePositionValue: ResolveValueFn
/** Returns the current canvas bounding rect, or null if the canvas is unmounted.
* This is a getter (not a value) because DOMRect changes on scroll. Useful for
* custom overlays that portal positioned content outside the chart wrapper. */
diff --git a/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts b/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts
index f951cc601bd8..53bbedc523c4 100644
--- a/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts
+++ b/frontend/src/lib/hog-charts/core/hooks/useChartInteraction.ts
@@ -58,6 +58,10 @@ interface UseChartInteractionOptions<Meta> {
pinnable: boolean
onPointClick?: (data: PointClickData<Meta>) => void
resolveValue?: ResolveValueFn
+ /** Value used to *anchor* the tooltip per series. Defaults to `resolveValue`. Stacked
+ * charts pass the stacked-top resolver so the anchor lands at the visual top of each
+ * segment while each tooltip row still shows its own value via `resolveValue`. */
+ resolvePositionValue?: ResolveValueFn
interactionAxis?: 'x' | 'y'
labelToCoord?: (label: string) => number | undefined
}
@@ -84,9 +88,13 @@ export function useChartInteraction<Meta = unknown>({
pinnable,
onPointClick,
resolveValue = defaultResolveValue,
+ resolvePositionValue,
interactionAxis = 'x',
labelToCoord,
}: UseChartInteractionOptions<Meta>): UseChartInteractionResult<Meta> {
+ // Falls back to the value resolver when the chart doesn't distinguish position from
+ // value (i.e. non-stacked charts, where the two are identical).
+ const effectivePositionResolve = resolvePositionValue ?? resolveValue
const [hoverIndex, setHoverIndex] = useState<number>(-1)
const [hoverPosition, setHoverPosition] = useState<{ x: number; y: number } | null>(null)
const [tooltipCtx, setTooltipCtx] = useState<TooltipContext<Meta> | null>(null)
@@ -119,6 +127,7 @@ export function useChartInteraction<Meta = unknown>({
// contract on `ChartProps.resolveValue`: any external toggle that changes the
// resolver's output must also update series or scales.
const resolveValueRef = useLatest(resolveValue)
+ const effectivePositionResolveRef = useLatest(effectivePositionResolve)
useEffect(() => {
if (!isPinned || !scales || !dimensions) {
return
@@ -141,7 +150,8 @@ export function useChartInteraction<Meta = unknown>({
resolveValueRef.current,
scales.yAxes,
interactionAxis,
- prev.hoverPosition
+ prev.hoverPosition,
+ effectivePositionResolveRef.current
)
if (!fresh) {
return null
@@ -257,7 +267,8 @@ export function useChartInteraction<Meta = unknown>({
resolveValue,
scales.yAxes,
interactionAxis,
- { x: mouseX, y: mouseY }
+ { x: mouseX, y: mouseY },
+ effectivePositionResolve
)
)
}
@@ -269,6 +280,7 @@ export function useChartInteraction<Meta = unknown>({
series,
showTooltip,
resolveValue,
+ effectivePositionResolve,
canvasRef,
isPinned,
clearTooltip,
diff --git a/frontend/src/lib/hog-charts/core/interaction.ts b/frontend/src/lib/hog-charts/core/interaction.ts
index 7236ea897cc1..9eecbc1ca3ba 100644
--- a/frontend/src/lib/hog-charts/core/interaction.ts
+++ b/frontend/src/lib/hog-charts/core/interaction.ts
@@ -70,7 +70,11 @@ export function buildTooltipContext<Meta = unknown>(
yAxes?: Record<string, YAxisScale>,
/** Returned `position.{x,y}` are canvas-pixel coordinates regardless of orientation. */
interactionAxis: 'x' | 'y' = 'x',
- hoverPosition: { x: number; y: number } | null = null
+ hoverPosition: { x: number; y: number } | null = null,
+ /** Resolves the value used to *anchor* the tooltip per series. Defaults to `resolveValue`.
+ * 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
): TooltipContext<Meta> | null {
if (dataIndex < 0 || dataIndex >= labels.length) {
return null
@@ -88,12 +92,13 @@ export function buildTooltipContext<Meta = unknown>(
if (s.visibility?.excluded) {
continue
}
- const value = resolveValue(s, dataIndex)
+ // `resolveValue` is the value shown to the user (the segment); `resolvePositionValue`
+ // is where to anchor (the stacked top). They diverge only for stacked charts.
if (s.visibility?.tooltip !== false) {
- seriesData.push({ series: s, value, color: s.color })
+ seriesData.push({ series: s, value: resolveValue(s, dataIndex), color: s.color })
}
const seriesValueScale = yAxes?.[s.yAxisId ?? DEFAULT_Y_AXIS_ID]?.scale ?? yScale
- const px = seriesValueScale(value)
+ const px = seriesValueScale(resolvePositionValue(s, dataIndex))
if (isFinite(px)) {
valuePixels.push(px)
}
diff --git a/frontend/src/lib/hog-charts/core/scales.test.ts b/frontend/src/lib/hog-charts/core/scales.test.ts
index 1db780b735fd..9898f070ebd1 100644
--- a/frontend/src/lib/hog-charts/core/scales.test.ts
+++ b/frontend/src/lib/hog-charts/core/scales.test.ts
@@ -1,7 +1,8 @@
import { dimensions, makeSeries } from '../testing'
import {
autoFormatYTick,
- buildStackedResolveValue,
+ buildSegmentResolveValue,
+ buildStackedPositionValue,
computePercentStackData,
computeStackData,
createScales,
@@ -516,29 +517,29 @@ describe('hog-charts scales', () => {
})
})
- describe('buildStackedResolveValue', () => {
+ describe('buildStackedPositionValue', () => {
const series = makeSeries({ key: 'a', data: [10, 20, 30] })
it('returns undefined when stackedData is undefined', () => {
- expect(buildStackedResolveValue(undefined)).toBeUndefined()
+ expect(buildStackedPositionValue(undefined)).toBeUndefined()
})
it('returns the stacked top when present and finite', () => {
const stacked = new Map<string, StackedBand>([['a', { top: [100, 200, 300], bottom: [0, 0, 0] }]])
- const resolve = buildStackedResolveValue(stacked)!
+ const resolve = buildStackedPositionValue(stacked)!
expect(resolve(series, 0)).toBe(100)
expect(resolve(series, 2)).toBe(300)
})
it('falls back to the raw value when the series is not in the stack', () => {
const stacked = new Map<string, StackedBand>()
- const resolve = buildStackedResolveValue(stacked)!
+ const resolve = buildStackedPositionValue(stacked)!
expect(resolve(series, 1)).toBe(20)
})
it('falls back to the raw value when the stacked top is non-finite', () => {
const stacked = new Map<string, StackedBand>([['a', { top: [NaN, Infinity, 50], bottom: [0, 0, 0] }]])
- const resolve = buildStackedResolveValue(stacked)!
+ const resolve = buildStackedPositionValue(stacked)!
expect(resolve(series, 0)).toBe(10)
expect(resolve(series, 1)).toBe(20)
expect(resolve(series, 2)).toBe(50)
@@ -547,9 +548,67 @@ describe('hog-charts scales', () => {
it('returns 0 when both stacked top and raw value are non-finite', () => {
const nanSeries = makeSeries({ key: 'a', data: [NaN, Infinity, 0] })
const stacked = new Map<string, StackedBand>([['a', { top: [NaN, NaN, 0], bottom: [0, 0, 0] }]])
- const resolve = buildStackedResolveValue(stacked)!
+ const resolve = buildStackedPositionValue(stacked)!
expect(resolve(nanSeries, 0)).toBe(0)
expect(resolve(nanSeries, 1)).toBe(0)
})
})
+
+ describe('buildSegmentResolveValue', () => {
+ const series = makeSeries({ key: 'a', data: [10, 20, 30] })
+
+ it('returns undefined when stackedData is undefined', () => {
+ expect(buildSegmentResolveValue(undefined)).toBeUndefined()
+ })
+
+ it('returns the segment height (top − bottom), not the cumulative top', () => {
+ // `a` sits on top of 490 of other series, so its top is 980 but its own value is 490.
+ const stacked = new Map<string, StackedBand>([['a', { top: [490, 980, 1470], bottom: [0, 490, 980] }]])
+ const resolve = buildSegmentResolveValue(stacked)!
+ expect(resolve(series, 0)).toBe(490)
+ expect(resolve(series, 1)).toBe(490)
+ expect(resolve(series, 2)).toBe(490)
+ })
+
+ it('falls back to the raw value when the series is not in the stack', () => {
+ const resolve = buildSegmentResolveValue(new Map<string, StackedBand>())!
+ expect(resolve(series, 1)).toBe(20)
+ })
+
+ it('falls back to the raw value when either the segment top or bottom is non-finite', () => {
+ // The guard requires both top and bottom finite, so a NaN on either edge falls back to raw.
+ const stacked = new Map<string, StackedBand>([['a', { top: [NaN, 20, 980], bottom: [0, NaN, 490] }]])
+ const resolve = buildSegmentResolveValue(stacked)!
+ expect(resolve(series, 0)).toBe(10) // top NaN → raw 10
+ expect(resolve(series, 1)).toBe(20) // bottom NaN → raw 20
+ expect(resolve(series, 2)).toBe(490) // both finite → 980 - 490
+ })
+
+ it('returns 0 when both the segment and the raw value are non-finite', () => {
+ const nanSeries = makeSeries({ key: 'a', data: [NaN, Infinity, 0] })
+ const stacked = new Map<string, StackedBand>([['a', { top: [NaN, 10, 0], bottom: [NaN, NaN, 0] }]])
+ const resolve = buildSegmentResolveValue(stacked)!
+ expect(resolve(nanSeries, 0)).toBe(0) // segment NaN + raw NaN → 0
+ expect(resolve(nanSeries, 1)).toBe(0) // bottom NaN + raw Infinity → 0
+ })
+
+ it('resolves a negative-valued count-stacked series to 0 (buildStackData floors it)', () => {
+ // buildStackData clamps data to >= 0 before stacking, so a negative series has a
+ // zero-height segment — the resolver reports 0, not the raw negative value.
+ const negSeries = makeSeries({ key: 'a', data: [10, -50] })
+ const resolve = buildSegmentResolveValue(computeStackData([negSeries], ['x', 'y']))!
+ expect(resolve(negSeries, 0)).toBe(10)
+ expect(resolve(negSeries, 1)).toBe(0)
+ })
+
+ it('returns each series own fraction for a percent stack, not the cumulative fraction', () => {
+ // a=20, b=15 at index 1 → total 35. b sits on top of a, so b's cumulative top is 1.0,
+ // but its own fraction is 15/35 — that segment is what the tooltip must report.
+ const a = makeSeries({ key: 'a', data: [10, 20] })
+ const b = makeSeries({ key: 'b', data: [5, 15] })
+ const resolve = buildSegmentResolveValue(computePercentStackData([a, b], ['x', 'y']))!
+ expect(resolve(a, 1)).toBeCloseTo(20 / 35, 5)
+ expect(resolve(b, 1)).toBeCloseTo(15 / 35, 5)
+ })
+ })
})
diff --git a/frontend/src/lib/hog-charts/core/scales.ts b/frontend/src/lib/hog-charts/core/scales.ts
index 7d5c8689de08..aa22ea86c8fa 100644
--- a/frontend/src/lib/hog-charts/core/scales.ts
+++ b/frontend/src/lib/hog-charts/core/scales.ts
@@ -248,10 +248,12 @@ export function computePercentStackData(series: Series[], labels: string[]): Map
return buildStackData(series, labels, d3.stackOffsetExpand)
}
-/** Returns the stacked top of each series so the tooltip anchor lands at the visual
- * top of each segment, not the raw series value. Falls back to the raw value when the
- * series isn't part of the stack (e.g. trend-line overlays, CI bands). */
-export function buildStackedResolveValue(
+/** Returns the stacked top of each series so the tooltip anchor and value-label position
+ * land at the visual top of each segment. This is a *position* resolver — for the value
+ * to *display* (the segment, not the cumulative total) use {@link buildSegmentResolveValue}.
+ * Falls back to the raw value when the series isn't part of the stack (e.g. trend-line
+ * overlays, CI bands). */
+export function buildStackedPositionValue(
stackedData: Map<string, StackedBand> | undefined
): ResolveValueFn | undefined {
if (!stackedData) {
@@ -267,6 +269,29 @@ export function buildStackedResolveValue(
}
}
+/** Returns each series's own segment height (`top − bottom`) — the per-series value to
+ * display, not the cumulative stack total. Falls back to the raw value for series not in
+ * the stack. Pair with {@link buildStackedPositionValue} for anchor positioning. */
+export function buildSegmentResolveValue(
+ stackedData: Map<string, StackedBand> | undefined
+): ResolveValueFn | undefined {
+ if (!stackedData) {
+ return undefined
+ }
+ return (s, dataIndex) => {
+ const band = stackedData.get(s.key)
+ if (band) {
+ const top = band.top[dataIndex]
+ const bottom = band.bottom[dataIndex]
+ if (Number.isFinite(top) && Number.isFinite(bottom)) {
+ return top - bottom
+ }
+ }
+ const raw = s.data[dataIndex]
+ return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0
+ }
+}
+
export interface BarScaleSet {
band: d3.ScaleBand<string>
value: D3YScale
diff --git a/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx b/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
index c688e4e2a3dc..d52d115364a9 100644
--- a/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
@@ -212,11 +212,11 @@ describe('ValueLabels', () => {
it('positions labels at the resolved (e.g. stacked) y, not the raw series.data y', () => {
// Raw value 25 sits at y=278 on the left axis; stacking lifts it to top-of-stack=75 → y=104.
- // The resolveValue closure mimics what LineChart provides for stacked series.
+ // The resolvePositionValue closure mimics what LineChart provides for stacked series.
const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [25] }]
const stackedTops: Record<string, number[]> = { s: [75] }
- const resolveValue: ResolveValueFn = (s, i) => stackedTops[s.key]?.[i] ?? s.data[i] ?? 0
- const ctx = makeContext(series, { labels: ['Mon'], resolveValue })
+ const resolvePositionValue: ResolveValueFn = (s, i) => stackedTops[s.key]?.[i] ?? s.data[i] ?? 0
+ const ctx = makeContext(series, { labels: ['Mon'], resolvePositionValue })
const { container } = renderInChart(ctx, <ValueLabels />)
const divs = labelDivs(container)
expect(divs).toHaveLength(1)
diff --git a/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx b/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
index 5a2a172a2caa..38debaa3748c 100644
--- a/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
@@ -42,7 +42,7 @@ interface BuildCandidatesArgs {
series: ResolvedSeries[]
labels: string[]
scales: ChartScales
- resolveValue: ResolveValueFn
+ resolvePositionValue: ResolveValueFn
valueFormatter: NonNullable<ValueLabelsProps['valueFormatter']>
isHorizontal: boolean
mode: ValueLabelsMode
@@ -147,7 +147,7 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
}
function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2D | null): Candidate[] {
- const { series, labels, scales, resolveValue, valueFormatter, isHorizontal } = args
+ const { series, labels, scales, resolvePositionValue, valueFormatter, isHorizontal } = args
const out: Candidate[] = []
for (let sIdx = 0; sIdx < series.length; sIdx++) {
@@ -161,7 +161,7 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
if (typeof rawValue !== 'number' || !isFinite(rawValue) || rawValue === 0) {
continue
}
- const yValue = resolveValue(s, dIdx)
+ const yValue = resolvePositionValue(s, dIdx)
if (typeof yValue !== 'number' || !isFinite(yValue)) {
continue
}
@@ -289,7 +289,7 @@ export function ValueLabels({
minGap = 4,
mode = 'per-segment',
}: ValueLabelsProps): React.ReactElement | null {
- const { series, scales, labels, theme, resolveValue, axis } = useChartLayout()
+ const { series, scales, labels, theme, resolvePositionValue, axis } = useChartLayout()
const isHorizontal = axis.orientation === 'horizontal'
const isPercent = axis.isPercent
@@ -302,7 +302,7 @@ export function ValueLabels({
series,
labels,
scales,
- resolveValue,
+ resolvePositionValue,
valueFormatter: formatter,
isHorizontal,
mode,
@@ -311,7 +311,7 @@ export function ValueLabels({
minGap,
isHorizontal
),
- [series, labels, scales, resolveValue, formatter, minGap, isHorizontal, mode, isPercent]
+ [series, labels, scales, resolvePositionValue, formatter, minGap, isHorizontal, mode, isPercent]
)
if (visible.length === 0) {
diff --git a/frontend/src/lib/hog-charts/testing/accessor.ts b/frontend/src/lib/hog-charts/testing/accessor.ts
index 046d4c7069d5..8016ca41cd1a 100644
--- a/frontend/src/lib/hog-charts/testing/accessor.ts
+++ b/frontend/src/lib/hog-charts/testing/accessor.ts
@@ -12,9 +12,16 @@ import type { TooltipContext } from '../core/types'
import { dimensions } from './jsdom'
import { type HogChartTooltip, waitForHogChartTooltip } from './tooltip'
+/** A single entry of `TooltipContext.seriesData`. */
+type TooltipSeriesEntry<Meta = unknown> = TooltipContext<Meta>['seriesData'][number]
+
/** Handle returned by `chart.waitForTooltip()` — every field of the structured `TooltipContext`,
- * plus the rendered portal `element` and an `isPinned` snapshot. */
-export type TooltipSnapshot<Meta = unknown> = TooltipContext<Meta> & HogChartTooltip
+ * plus the rendered portal `element`, an `isPinned` snapshot, and `series` (seriesData indexed
+ * by series key, for order-independent lookups like `tooltip.series.a.value`). */
+export type TooltipSnapshot<Meta = unknown> = TooltipContext<Meta> &
+ HogChartTooltip & {
+ series: Record<string, TooltipSeriesEntry<Meta>>
+ }
interface ReferenceLineSummary {
label: string | null
@@ -209,6 +216,7 @@ export function getHogChart<Meta = unknown>(
...ctx,
element,
isPinned: element.classList.contains('hog-charts-tooltip--pinned'),
+ series: Object.fromEntries(ctx.seriesData.map((s) => [s.series.key, s])),
}
},
}
diff --git a/frontend/src/lib/hog-charts/testing/overlay.tsx b/frontend/src/lib/hog-charts/testing/overlay.tsx
index 37e4435fcbd5..b15518df7575 100644
--- a/frontend/src/lib/hog-charts/testing/overlay.tsx
+++ b/frontend/src/lib/hog-charts/testing/overlay.tsx
@@ -14,7 +14,7 @@ export interface OverlayContextOverrides {
labels?: string[]
series?: ResolvedSeries[]
theme?: ChartTheme
- resolveValue?: ResolveValueFn
+ resolvePositionValue?: ResolveValueFn
canvasBounds?: () => DOMRect | null
axisOrientation?: 'vertical' | 'horizontal'
isPercent?: boolean
@@ -31,7 +31,7 @@ export function makeOverlayContext(scales: ChartScales, overrides: OverlayContex
series: overrides.series ?? [],
scales,
theme: overrides.theme ?? DEFAULT_THEME,
- resolveValue: overrides.resolveValue ?? DEFAULT_RESOLVE,
+ resolvePositionValue: overrides.resolvePositionValue ?? DEFAULT_RESOLVE,
canvasBounds: overrides.canvasBounds ?? (() => null),
axis: {
orientation: overrides.axisOrientation ?? 'vertical',
diff --git a/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.test.tsx b/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.test.tsx
index 23aab2e746fc..f0e464c04c47 100644
--- a/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.test.tsx
+++ b/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.test.tsx
@@ -57,6 +57,26 @@ describe('TrendsBarChart (ActionsBar)', () => {
expect(tooltip.row('Pageview')).toContain('134')
})
+ it('stacked tooltip shows each series own value, not the cumulative stack total', async () => {
+ // $pageview=134 and Napped=5 at index 2. Napped stacks on top of $pageview, so its
+ // cumulative top is 139 — the tooltip must report Napped's own 5, not the running total.
+ renderInsight({
+ query: trendsBar({
+ series: [
+ { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },
+ { kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },
+ ],
+ }),
+ featureFlags: HOG_CHARTS_FLAG,
+ })
+
+ const tooltip = await chart.hoverTooltip(2)
+
+ expect(tooltip.row('Pageview')).toContain('134')
+ expect(tooltip.row('Napped')).toContain('5')
+ expect(tooltip.row('Napped')).not.toContain('139')
+ })
+
it('shows a date header in the tooltip', async () => {
renderInsight({ query: trendsBar(), featureFlags: HOG_CHARTS_FLAG })