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): correct percent-stack bar chart labels and y-axis (#59932)

Sam Pennington805e63f677d1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d1914d8f2fa9..a6437e49ba0c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1968,6 +1968,10 @@ snapshots:
hash: v1.k794b7964.68689d02aa245c2ccd04888b1c2bc578136eda4117f2fff911bde3f5c276b9da.svBnhEDDJ61_Vp6T3AUEjT3wlS2aamf9o-YNooKTRlw
insights-trendsbarchart--compare--light:
hash: v1.k794b7964.08db5d36c08b26300a7cd09fddd8f02e9ba973ffcf42e556e7f8ae01a27e907b.jN5qaeiDphtPJ90-0-bNC0jmD0MVkSCj6zjO8XzvZkI
+ insights-trendsbarchart--percent-stack-breakdown--dark:
+ hash: v1.k794b7964.b7e405e7536059add287822bbcae51772fab8005ac1f864ee3c65495eaeec4a9.0o8Vkv9xYOCBk1d35UNO2_kA2Oy9iajzneJBiTlq6vg
+ insights-trendsbarchart--percent-stack-breakdown--light:
+ hash: v1.k794b7964.02fcdcf3d83d1d4a1c0e28e097e1affbecb5d89f803d658bfe90ad49da0bd444.Mqj_tHvOG038o4BV0jE89RHVuDXjLZiYAluTs8Hx1pg
insights-trendslifecyclechart--stacked--dark:
hash: v1.k794b7964.f01dae4d665fea93c451e5bb48d6409d586c89856ffb1fff155937c7eb9119d9.coUQ2-TFqEqeP38cPDoiz5RbwkfznST9H3pR5TRbpvg
insights-trendslifecyclechart--stacked--light:
@@ -4711,7 +4715,7 @@ snapshots:
scenes-app-insights-funnels--funnel-historical-trends-edit--light:
hash: v1.k794b7964.fa67675b6f95f0ae9c46eb0e803f9db69702419bb4ccc2d21ea973f9fe49d9cc.Zz4siV83g7nIXf96Nfvy6eN5rRtzwO3CEmv24KSztlA
scenes-app-insights-funnels--funnel-left-to-right-breakdown-edit--dark:
- hash: v1.k794b7964.945ed16d72ed2ec67559ed2a478237267bf3fae0ec5437202145e4bbddaa99c2.Pl63KVs13EuxFB41jKCVv-dOTSP27veYuLRl7pFf7UQ
+ hash: v1.k794b7964.2a18d8ba3f9634f9d7c9ece2ad8ee2f6716706ecbb30595102d003ca8ad27184.y6n_yOa8fbdhe6yHOtjclzfTFAJ9hj0Da0VbQIhaj2M
scenes-app-insights-funnels--funnel-left-to-right-breakdown-edit--light:
hash: v1.k794b7964.414326f685dca45885b93d728ae8a75c7d8b600af35d76c9512a74a27e453006.IyZ8qHUwOv6qsBYvdUR1ZsK1Md_GNFCftDGvNZj78BQ
scenes-app-insights-funnels--funnel-left-to-right-edit--dark:
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
index fcf047782604..359cc1f2d8a0 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
@@ -245,10 +245,15 @@ describe('TimeSeriesBarChart', () => {
expect(chart.yTicks().some((t) => /\d+%/.test(t))).toBe(true)
})
- it('formats value labels as percentages when yAxis.format=percentage_scaled with 0-1 data', () => {
+ it('formats value labels as each segment fraction (0..1) in percent layout', () => {
+ // Two series with totals (10, 100, 1000); a's share is 0.1, 0.2, 0.3 of each band.
+ // The `percentage_scaled` formatter takes 0..1 input so the labels render as "10%, 20%, 30%".
const { chart } = renderHogChart(
<TimeSeriesBarChart
- series={[{ key: 'a', label: 'A', data: [0.1, 0.2, 0.3] }]}
+ series={[
+ { key: 'a', label: 'A', data: [1, 20, 300] },
+ { key: 'b', label: 'B', data: [9, 80, 700] },
+ ]}
labels={LABELS}
theme={THEME}
config={{
@@ -258,7 +263,14 @@ describe('TimeSeriesBarChart', () => {
}}
/>
)
- expect(chart.valueLabels().map((l) => l.text)).toEqual(['10%', '20%', '30%'])
+ // a's shares are [0.1, 0.2, 0.3]; b's are [0.9, 0.8, 0.7]. Sort so the assertion
+ // doesn't depend on render order.
+ expect(
+ chart
+ .valueLabels()
+ .map((l) => l.text)
+ .sort()
+ ).toEqual(['10%', '20%', '30%', '70%', '80%', '90%'].sort())
})
})
diff --git a/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx b/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
index d52d115364a9..ed5527000b98 100644
--- a/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ValueLabels.test.tsx
@@ -287,10 +287,37 @@ describe('ValueLabels', () => {
})
})
- it('isPercent on context is informational — consumers supply their own formatter', () => {
- const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [0.25, 0.5, 0.75] }]
- const ctx = makeContext(series, { isPercent: true, labels: ['Mon', 'Tue', 'Wed'] })
- const { container } = renderInChart(ctx, <ValueLabels valueFormatter={(v) => `${(v * 100).toFixed(1)}%`} />)
- expect(labelDivs(container).map((d) => d.textContent)).toEqual(['25.0%', '50.0%', '75.0%'])
+ it('in percent layout, formatter receives each segment fraction (0..1), not raw data', () => {
+ // Both series have non-zero values in both bands so we exercise the `raw / total`
+ // division, not the trivial single-segment-per-band 100% path.
+ // Band totals: Mon = 100, Tue = 100. Expected fractions: a = [0.2, 0.6], b = [0.8, 0.4].
+ const series: ResolvedSeries[] = [
+ { key: 'a', label: 'A', color: '#f00', data: [20, 60] },
+ { key: 'b', label: 'B', color: '#0f0', data: [80, 40] },
+ ]
+ // Custom yScale on 0..1 (matches percent layout) so segment centers don't collide.
+ const percentScales: ChartScales = {
+ x: xScale,
+ y: (v: number) => 368 - v * 352,
+ yTicks: () => [0, 0.5, 1],
+ }
+ // Stacked tops per series in 0..1 space — matches d3.stackOffsetExpand output.
+ const positionByKey: Record<string, number[]> = {
+ a: [0.2, 0.6],
+ b: [1.0, 1.0],
+ }
+ const resolvePositionValue: ResolveValueFn = (s, i) => positionByKey[s.key]?.[i] ?? 0
+ const ctx = makeContext(series, {
+ isPercent: true,
+ labels: ['Mon', 'Tue'],
+ scales: percentScales,
+ resolvePositionValue,
+ })
+ const { container } = renderInChart(ctx, <ValueLabels valueFormatter={(v) => `${(v * 100).toFixed(0)}%`} />)
+ expect(
+ labelDivs(container)
+ .map((d) => d.textContent)
+ .sort()
+ ).toEqual(['20%', '40%', '60%', '80%'])
})
})
diff --git a/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx b/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
index 38debaa3748c..a8ba9c01fd99 100644
--- a/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx
@@ -32,6 +32,9 @@ interface Candidate {
width: number
color: string
above: boolean
+ /** Anchor the label centered on `(x, y)` instead of offset by `above`. Used for percent-stack
+ * segments so the topmost label doesn't render above the chart top. */
+ centered: boolean
}
function defaultLocaleFormatter(v: number): string {
@@ -59,7 +62,8 @@ function pushCandidate(
text: string,
categoricalCoord: number,
valueCoord: number,
- above: boolean
+ above: boolean,
+ centered: boolean = false
): void {
const textWidth = ctx ? ctx.measureText(text).width : text.length * 6
const width = textWidth + LABEL_HORIZONTAL_CHROME
@@ -72,6 +76,7 @@ function pushCandidate(
width,
color,
above,
+ centered,
})
}
@@ -147,9 +152,17 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
}
function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2D | null): Candidate[] {
- const { series, labels, scales, resolvePositionValue, valueFormatter, isHorizontal } = args
+ const { series, labels, scales, resolvePositionValue, valueFormatter, isHorizontal, isPercent } = args
const out: Candidate[] = []
+ // In percent layout each band sums to 1, so we need the band total to convert each segment's
+ // raw value into the fraction d3 uses for placement (`raw / total`). Match the d3 stack's own
+ // denominator — every non-excluded stacked series — even if some have `valueLabel: false`,
+ // since those still contribute to the visual stack height.
+ const visibleForTotal = isPercent
+ ? series.filter((s) => !s.visibility?.excluded && !s.fill?.lowerData && !s.overlay)
+ : []
+
for (let sIdx = 0; sIdx < series.length; sIdx++) {
const s = series[sIdx]
if (s.visibility?.excluded || s.visibility?.valueLabel === false) {
@@ -165,11 +178,33 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
if (typeof yValue !== 'number' || !isFinite(yValue)) {
continue
}
+
+ let displayValue = rawValue
+ let positionValue = yValue
+ let above = yValue >= 0
+ let centered = false
+
+ if (isPercent) {
+ const total = bandTotal(visibleForTotal, dIdx)
+ if (total == null || total === 0) {
+ continue
+ }
+ const fraction = rawValue / total
+ // Pass the fraction (0..1) so consumers can use the same percentage formatter
+ // (`percentage_scaled`, BarChart's default tick formatter, etc.) they already use
+ // for the value axis.
+ displayValue = fraction
+ // `yValue` here is the stacked top in 0..1 space; subtract half the segment's
+ // height to land at the segment center.
+ positionValue = yValue - fraction / 2
+ centered = true
+ }
+
// Pass `s.key` so grouped bar charts (compare-against-previous) anchor each
// label on its own bar rather than the band center between bars. Other chart
// types ignore the second arg and fall back to the band/point center.
const categoricalCoord = scales.x(labels[dIdx], s.key)
- const valueCoord = yScale(yValue)
+ const valueCoord = yScale(positionValue)
if (categoricalCoord == null || !isFinite(categoricalCoord) || !isFinite(valueCoord)) {
continue
}
@@ -180,10 +215,11 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2
`${s.key}-${dIdx}`,
sIdx,
s.color,
- valueFormatter(rawValue, sIdx, dIdx),
+ valueFormatter(displayValue, sIdx, dIdx),
categoricalCoord,
valueCoord,
- yValue >= 0
+ above,
+ centered
)
}
}
@@ -200,11 +236,12 @@ interface Rect {
function labelRect(c: Candidate, isHorizontal: boolean): Rect {
if (isHorizontal) {
const halfH = LABEL_HEIGHT / 2
- const left = c.above ? c.x : c.x - c.width
+ const halfW = c.width / 2
+ const left = c.centered ? c.x - halfW : c.above ? c.x : c.x - c.width
return { left, right: left + c.width, top: c.y - halfH, bottom: c.y + halfH }
}
const halfW = c.width / 2
- const top = c.above ? c.y - LABEL_HEIGHT : c.y
+ const top = c.centered ? c.y - LABEL_HEIGHT / 2 : c.above ? c.y - LABEL_HEIGHT : c.y
return { left: c.x - halfW, right: c.x + halfW, top, bottom: top + LABEL_HEIGHT }
}
@@ -278,6 +315,9 @@ const LABEL_STYLE_BASE: React.CSSProperties = {
}
function transformFor(c: Candidate, isHorizontal: boolean): string {
+ if (c.centered) {
+ return 'translate(-50%, -50%)'
+ }
if (isHorizontal) {
return c.above ? 'translateY(-50%)' : 'translate(-100%, -50%)'
}
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.stories.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.stories.tsx
index 611db7ceaca3..86d276b9413b 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.stories.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.stories.tsx
@@ -341,3 +341,115 @@ const AGGREGATED_COMPARE_BREAKDOWN_INSIGHT = {
export const AggregatedCompareBreakdown: Story = {
render: () => renderTrendsBarChart(AGGREGATED_COMPARE_BREAKDOWN_INSIGHT),
}
+
+// Stacked bar in 100% mode with value labels enabled. Pre-fix this snapshot showed a 0%–1%
+// y-axis, raw-count value labels (e.g. "22,865%"), and a clipped top-segment label. After
+// the fix the y-axis runs 0%–100%, labels show each segment's share, and the topmost label
+// sits inside its segment.
+const PERCENT_STACK_BREAKDOWN_INSIGHT = {
+ id: 202,
+ short_id: 'barPercentStack',
+ name: 'Pageviews by browser (100% stacked)',
+ derived_name: 'Pageview count',
+ filters: {},
+ last_refresh: '2023-07-11T12:00:00Z',
+ refreshing: false,
+ saved: true,
+ is_sample: false,
+ description: '',
+ tags: [],
+ favorited: false,
+ created_at: '2023-07-11T12:00:00Z',
+ updated_at: '2023-07-11T12:00:00Z',
+ last_modified_at: '2023-07-11T12:00:00Z',
+ dashboards: [],
+ dashboard_tiles: [],
+ result: [
+ {
+ action: ACTION,
+ label: 'Chrome',
+ count: 14000,
+ data: [4000, 3500, 3000, 1500, 1200, 600, 200],
+ labels: CURRENT_LABELS,
+ days: CURRENT_DAYS,
+ breakdown_value: 'Chrome',
+ filter: {
+ date_from: '2023-07-04T00:00:00Z',
+ date_to: '2023-07-10T23:59:59Z',
+ display: 'ActionsBar',
+ insight: 'TRENDS',
+ interval: 'day',
+ },
+ },
+ {
+ action: ACTION,
+ label: 'Safari',
+ count: 6500,
+ data: [400, 800, 1500, 1800, 1500, 400, 100],
+ labels: CURRENT_LABELS,
+ days: CURRENT_DAYS,
+ breakdown_value: 'Safari',
+ filter: {
+ date_from: '2023-07-04T00:00:00Z',
+ date_to: '2023-07-10T23:59:59Z',
+ display: 'ActionsBar',
+ insight: 'TRENDS',
+ interval: 'day',
+ },
+ },
+ {
+ action: ACTION,
+ label: 'Firefox',
+ count: 2200,
+ data: [200, 250, 300, 500, 500, 350, 100],
+ labels: CURRENT_LABELS,
+ days: CURRENT_DAYS,
+ breakdown_value: 'Firefox',
+ filter: {
+ date_from: '2023-07-04T00:00:00Z',
+ date_to: '2023-07-10T23:59:59Z',
+ display: 'ActionsBar',
+ insight: 'TRENDS',
+ interval: 'day',
+ },
+ },
+ {
+ action: ACTION,
+ label: 'Edge',
+ count: 900,
+ data: [80, 120, 150, 200, 200, 100, 50],
+ labels: CURRENT_LABELS,
+ days: CURRENT_DAYS,
+ breakdown_value: 'Edge',
+ filter: {
+ date_from: '2023-07-04T00:00:00Z',
+ date_to: '2023-07-10T23:59:59Z',
+ display: 'ActionsBar',
+ insight: 'TRENDS',
+ interval: 'day',
+ },
+ },
+ ],
+ query: {
+ kind: 'InsightVizNode',
+ source: {
+ dateRange: { date_from: '2023-07-04', date_to: '2023-07-10' },
+ filterTestAccounts: false,
+ interval: 'day',
+ kind: 'TrendsQuery',
+ series: [{ event: '$pageview', kind: 'EventsNode', math: 'total', name: '$pageview' }],
+ trendsFilter: {
+ display: 'ActionsBar',
+ showPercentStackView: true,
+ showValuesOnSeries: true,
+ },
+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },
+ version: 2,
+ },
+ full: true,
+ },
+}
+
+export const PercentStackBreakdown: Story = {
+ render: () => renderTrendsBarChart(PERCENT_STACK_BREAKDOWN_INSIGHT),
+}
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
index ac8922db479b..2befbcaf8236 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
@@ -11,7 +11,8 @@ import {
ValueLabels,
} from 'lib/hog-charts'
import type { BarChartConfig, PointClickData, TimeSeriesBarChartConfig, TooltipContext } from 'lib/hog-charts'
-import { formatPercentStackAxisValue } from 'scenes/insights/aggregationAxisFormat'
+import { percentage } from 'lib/utils'
+import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { insightLogic } from 'scenes/insights/insightLogic'
import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
@@ -129,7 +130,14 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
}, [isAggregated, indexedResults, getTrendsColor, getTrendsHidden, currentPeriodResult?.labels])
const valueLabelFormatter = useCallback(
- (value: number) => formatPercentStackAxisValue(trendsFilter, value, isPercentStackView, baseCurrency),
+ (value: number) => {
+ // In percent layout the chart computes each segment's share of its band and passes
+ // a 0..1 fraction here, so we render it directly as a percentage.
+ if (isPercentStackView) {
+ return percentage(value)
+ }
+ return formatAggregationAxisValue(trendsFilter, value, baseCurrency)
+ },
[trendsFilter, isPercentStackView, baseCurrency]
)
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
index 1d3b2398eca0..d3b4a8f15194 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
@@ -201,13 +201,15 @@ describe('buildTrendsBarTimeSeriesConfig', () => {
})
})
- it('forces percentage format when isPercentStackView is true', () => {
+ it('forces percentage_scaled format when isPercentStackView is true', () => {
+ // BarChart percent layout puts the value scale on 0..1, so the y-tick formatter
+ // expects 0..1 input rather than the 0..100 input of the regular `percentage` format.
const cfg = buildTrendsBarTimeSeriesConfig({
isPercentStackView: true,
isGrouped: false,
trendsFilter: { aggregationAxisFormat: 'currency' },
})
- expect(cfg.yAxis?.format).toBe('percentage')
+ expect(cfg.yAxis?.format).toBe('percentage_scaled')
})
it('maps schema goal lines through the shared adapter', () => {
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
index f455a5cc417a..36c338ccd6ad 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
@@ -4,7 +4,8 @@ import { useCallback, useMemo } from 'react'
import { buildTheme } from 'lib/charts/utils/theme'
import { DEFAULT_Y_AXIS_ID, TimeSeriesLineChart } from 'lib/hog-charts'
import type { PointClickData, Series, TimeSeriesLineChartConfig, TooltipConfig, TooltipContext } from 'lib/hog-charts'
-import { formatPercentStackAxisValue } from 'scenes/insights/aggregationAxisFormat'
+import { percentage } from 'lib/utils'
+import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { insightLogic } from 'scenes/insights/insightLogic'
import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
@@ -104,7 +105,14 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
)
const valueLabelFormatter = useCallback(
- (value: number) => formatPercentStackAxisValue(trendsFilter, value, isPercentStackView, baseCurrency),
+ (value: number) => {
+ // In percent layout the chart computes each segment's share of its band and passes
+ // a 0..1 fraction here, so we render it directly as a percentage.
+ if (isPercentStackView) {
+ return percentage(value)
+ }
+ return formatAggregationAxisValue(trendsFilter, value, baseCurrency)
+ },
[trendsFilter, isPercentStackView, baseCurrency]
)
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts
index 0f4aceb64e5d..381c384d9a91 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts
@@ -407,7 +407,7 @@ describe('trendsChartTransforms', () => {
tooltip: TOOLTIP,
showCrosshair: false,
})
- expect(config.yAxis).toMatchObject({ format: 'percentage', scale: 'linear', showGrid: true })
+ expect(config.yAxis).toMatchObject({ format: 'percentage_scaled', scale: 'linear', showGrid: true })
expect(config.percentStackView).toBe(true)
expect(config.tooltip).toBe(TOOLTIP)
expect(config.showCrosshair).toBe(false)
diff --git a/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.test.ts b/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.test.ts
index e34a17a73f9e..87b83b0641b5 100644
--- a/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.test.ts
+++ b/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.test.ts
@@ -45,10 +45,12 @@ describe('trendsFilterToYFormatterConfig', () => {
expect(trendsFilterToYFormatterConfig(trendsFilter, false)).toEqual({ format: 'numeric' })
})
- it('returns a percentage config when isPercentStackView is true, ignoring the trends filter', () => {
+ it('returns a percentage_scaled config when isPercentStackView is true, ignoring the trends filter', () => {
+ // BarChart percent layout puts the value scale on 0..1, so we use the 0..1 formatter
+ // (`percentage_scaled`) instead of the 0..100 `percentage` formatter.
const trendsFilter: TrendsFilter = { aggregationAxisFormat: 'currency', aggregationAxisPrefix: '$' }
expect(trendsFilterToYFormatterConfig(trendsFilter, true, 'USD' as CurrencyCode)).toEqual({
- format: 'percentage',
+ format: 'percentage_scaled',
})
})
})
@@ -70,9 +72,10 @@ describe('trends y-tick formatter end-to-end', () => {
})
it('formats percent-stack values regardless of the underlying trends filter', () => {
+ // Input is a 0..1 fraction (d3's percent scale), so 0.5 → "50%".
const trendsFilter: TrendsFilter = { aggregationAxisFormat: 'currency' }
const fmt = buildYTickFormatter(trendsFilterToYFormatterConfig(trendsFilter, true, 'USD' as CurrencyCode))
- expect(fmt(50)).toBe('50%')
+ expect(fmt(0.5)).toBe('50%')
})
})
@@ -102,8 +105,8 @@ describe('buildTrendsYAxisConfig', () => {
expect(cfg).toMatchObject({ format: 'duration', prefix: '~', decimalPlaces: 2, currency: 'USD' })
})
- it('forces percentage format when isPercentStackView is true', () => {
+ it('forces percentage_scaled format when isPercentStackView is true', () => {
const trendsFilter: TrendsFilter = { aggregationAxisFormat: 'currency', aggregationAxisPrefix: '$' }
- expect(buildTrendsYAxisConfig(trendsFilter, true, 'USD' as CurrencyCode).format).toBe('percentage')
+ expect(buildTrendsYAxisConfig(trendsFilter, true, 'USD' as CurrencyCode).format).toBe('percentage_scaled')
})
})
diff --git a/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.ts b/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.ts
index 52bd2738ee4b..f4088c0b4cb3 100644
--- a/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.ts
+++ b/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.ts
@@ -8,7 +8,8 @@ export function trendsFilterToYFormatterConfig(
baseCurrency?: CurrencyCode
): YFormatterConfig {
if (isPercentStackView) {
- return { format: 'percentage' }
+ // BarChart's percent layout puts the value scale on 0..1, so use the 0..1 formatter.
+ return { format: 'percentage_scaled' }
}
return {
format: trendsFilter?.aggregationAxisFormat ?? 'numeric',