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.

feat(insights): toggle to stack breakdown values on bar-value chart (#61096)

Sam Pennington2a7d07a9817b
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
index 24f7f25832f2..28fe6e5a56d5 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
@@ -31,6 +31,7 @@ import { ShowLegendFilter } from 'scenes/insights/EditorFilters/ShowLegendFilter
import { ShowMultipleYAxesFilter } from 'scenes/insights/EditorFilters/ShowMultipleYAxesFilter'
import { ShowPieTotalFilter } from 'scenes/insights/EditorFilters/ShowPieTotalFilter'
import { ShowTrendLinesFilter } from 'scenes/insights/EditorFilters/ShowTrendLinesFilter'
+import { StackBreakdownFilter } from 'scenes/insights/EditorFilters/StackBreakdownFilter'
import { ValueOnSeriesFilter } from 'scenes/insights/EditorFilters/ValueOnSeriesFilter'
import { InsightDateFilter } from 'scenes/insights/filters/InsightDateFilter'
import { RetentionChartPicker } from 'scenes/insights/filters/RetentionChartPicker'
@@ -93,6 +94,7 @@ export function InsightDisplayConfig(): JSX.Element {
supportsValueOnSeries,
showPercentStackView,
supportsPercentStackView,
+ supportsBarValueStacking,
supportsResultCustomizationBy,
yAxisScaleType,
showMultipleYAxes,
@@ -204,6 +206,7 @@ export function InsightDisplayConfig(): JSX.Element {
...(isLifecycle ? [{ label: () => <LifecycleStackingFilter /> }] : []),
...(supportsValueOnSeries ? [{ label: () => <ValueOnSeriesFilter /> }] : []),
...(supportsPercentStackView ? [{ label: () => <PercentStackViewFilter /> }] : []),
+ ...(supportsBarValueStacking ? [{ label: () => <StackBreakdownFilter /> }] : []),
...(hasLegend ? [{ label: () => <ShowLegendFilter /> }] : []),
...(display === ChartDisplayType.ActionsPie
? [{ label: () => <ShowPieTotalFilter /> }]
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index aa85f9425075..842d4ed9edf7 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -41126,6 +41126,11 @@
"$ref": "#/definitions/integer",
"default": 1
},
+ "stackBreakdownValues": {
+ "default": false,
+ "description": "On the horizontal bar-value chart, stack a series' breakdown values into a single bar instead of rendering one bar per breakdown value.",
+ "type": "boolean"
+ },
"xAxisLabel": {
"description": "Custom label rendered under the X axis.",
"type": "string"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index e99675f375e4..a2908e6ceedc 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1451,6 +1451,10 @@ export type TrendsFilter = {
showLabelsOnSeries?: TrendsFilterLegacy['show_labels_on_series']
/** @default false */
showPercentStackView?: TrendsFilterLegacy['show_percent_stack_view']
+ /** On the horizontal bar-value chart, stack a series' breakdown values into a single bar
+ * instead of rendering one bar per breakdown value.
+ * @default false */
+ stackBreakdownValues?: boolean
yAxisScaleType?: TrendsFilterLegacy['y_axis_scale_type']
/** @default false */
showMultipleYAxes?: TrendsFilterLegacy['show_multiple_y_axes']
@@ -1503,6 +1507,7 @@ export const TRENDS_FILTER_PROPERTIES = new Set<keyof TrendsFilter>([
'showValuesOnSeries',
'showLabelsOnSeries',
'showPercentStackView',
+ 'stackBreakdownValues',
'yAxisScaleType',
'hiddenLegendIndexes',
'excludeBoxPlotOutliers',
diff --git a/frontend/src/queries/utils.test.ts b/frontend/src/queries/utils.test.ts
index 7a01d19a0396..6188c2da2b9d 100644
--- a/frontend/src/queries/utils.test.ts
+++ b/frontend/src/queries/utils.test.ts
@@ -5,6 +5,7 @@ import { getAppContext } from 'lib/utils/getAppContext'
import { teamLogic } from 'scenes/teamLogic'
import { DataTableNode, DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'
+import type { InsightQueryNode } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { AppContext, ChartDisplayType, TeamType } from '~/types'
@@ -13,6 +14,7 @@ import {
escapeDottedHogQLIdentifier,
escapeHogQLString,
hogql,
+ supportsBarValueStacking,
} from './utils'
window.POSTHOG_APP_CONTEXT = { current_team: { id: MOCK_TEAM_ID } } as unknown as AppContext
@@ -165,3 +167,45 @@ describe('convertDataTableNodeToDataVisualizationNode', () => {
})
})
})
+
+describe('supportsBarValueStacking', () => {
+ const breakdown = { breakdown: '$browser', breakdown_type: 'event' as const }
+ const trends = (display: ChartDisplayType, withBreakdown: boolean): InsightQueryNode =>
+ ({
+ kind: NodeKind.TrendsQuery,
+ series: [],
+ trendsFilter: { display },
+ ...(withBreakdown ? { breakdownFilter: breakdown } : {}),
+ }) as InsightQueryNode
+
+ it.each([
+ {
+ name: 'trends + bar-value + breakdown',
+ query: trends(ChartDisplayType.ActionsBarValue, true),
+ expected: true,
+ },
+ {
+ name: 'trends + bar-value without breakdown',
+ query: trends(ChartDisplayType.ActionsBarValue, false),
+ expected: false,
+ },
+ {
+ name: 'trends + vertical bar + breakdown',
+ query: trends(ChartDisplayType.ActionsBar, true),
+ expected: false,
+ },
+ {
+ name: 'trends + line + breakdown',
+ query: trends(ChartDisplayType.ActionsLineGraph, true),
+ expected: false,
+ },
+ {
+ name: 'funnels + breakdown',
+ query: { kind: NodeKind.FunnelsQuery, series: [], breakdownFilter: breakdown } as InsightQueryNode,
+ expected: false,
+ },
+ { name: 'null query', query: null, expected: false },
+ ])('returns $expected for $name', ({ query, expected }) => {
+ expect(supportsBarValueStacking(query)).toBe(expected)
+ })
+})
diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.ts
index 34ae835cbf88..ab359dc640e6 100644
--- a/frontend/src/queries/utils.ts
+++ b/frontend/src/queries/utils.ts
@@ -661,6 +661,12 @@ export const supportsPercentStackView = (q: InsightQueryNode | null | undefined)
export const getShowPercentStackView = (query: InsightQueryNode): boolean | undefined =>
supportsPercentStackView(query) && (query as TrendsQuery)?.trendsFilter?.showPercentStackView
+export const supportsBarValueStacking = (q: InsightQueryNode | null | undefined): boolean =>
+ isTrendsQuery(q) && getDisplay(q) === ChartDisplayType.ActionsBarValue && hasBreakdownFilter(getBreakdown(q))
+
+export const getStackBreakdownValues = (query: InsightQueryNode): boolean | undefined =>
+ supportsBarValueStacking(query) && (query as TrendsQuery)?.trendsFilter?.stackBreakdownValues
+
export const nodeKindToFilterProperty: Record<ProductAnalyticsInsightNodeKind, InsightFilterProperty> = {
[NodeKind.TrendsQuery]: 'trendsFilter',
[NodeKind.FunnelsQuery]: 'funnelsFilter',
diff --git a/frontend/src/scenes/insights/EditorFilters/StackBreakdownFilter.tsx b/frontend/src/scenes/insights/EditorFilters/StackBreakdownFilter.tsx
new file mode 100644
index 000000000000..c46296908e6c
--- /dev/null
+++ b/frontend/src/scenes/insights/EditorFilters/StackBreakdownFilter.tsx
@@ -0,0 +1,24 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
+import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
+
+import { insightLogic } from '../insightLogic'
+
+export function StackBreakdownFilter(): JSX.Element {
+ const { insightProps } = useValues(insightLogic)
+ const { trendsFilter } = useValues(trendsDataLogic(insightProps))
+ const { updateInsightFilter } = useActions(trendsDataLogic(insightProps))
+
+ return (
+ <LemonCheckbox
+ className="p-1 px-2"
+ checked={!!trendsFilter?.stackBreakdownValues}
+ onChange={(checked) => {
+ updateInsightFilter({ stackBreakdownValues: checked })
+ }}
+ label={<span className="font-normal">Stack breakdown values</span>}
+ size="small"
+ />
+ )
+}
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.ts
index 003797292701..0b74ba122a70 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts
@@ -94,6 +94,7 @@ import {
isWebOverviewQuery,
isWebStatsTableQuery,
nodeKindToFilterProperty,
+ supportsBarValueStacking,
supportsPercentStackView,
} from '~/queries/utils'
import { BaseMathType, ChartDisplayType, InsightLogicProps, LabelGroupType, SlowQueryPossibilities } from '~/types'
@@ -214,6 +215,7 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
dateRange?.date_from !== 'all',
],
supportsPercentStackView: [(s) => [s.querySource], (q) => supportsPercentStackView(q)],
+ supportsBarValueStacking: [(s) => [s.querySource], (q) => supportsBarValueStacking(q)],
supportsValueOnSeries: [
(s) => [s.isTrends, s.isFunnels, s.isStickiness, s.isLifecycle, s.display],
(isTrends, isFunnels, isStickiness, isLifecycle, display) => {
diff --git a/frontend/src/scenes/insights/utils/queryUtils.ts b/frontend/src/scenes/insights/utils/queryUtils.ts
index d237c5893de1..d764eeb4db5c 100644
--- a/frontend/src/scenes/insights/utils/queryUtils.ts
+++ b/frontend/src/scenes/insights/utils/queryUtils.ts
@@ -227,6 +227,7 @@ export const cleanInsightQuery = (query: InsightQueryNode, opts?: CompareQueryOp
...insightFilter,
showLegend: undefined,
showPercentStackView: undefined,
+ stackBreakdownValues: undefined,
showValuesOnSeries: undefined,
aggregationAxisFormat: undefined,
aggregationAxisPrefix: undefined,
diff --git a/frontend/src/test/insight-testing/mocks.ts b/frontend/src/test/insight-testing/mocks.ts
index 3888f7c78cc5..1564f6fc6b94 100644
--- a/frontend/src/test/insight-testing/mocks.ts
+++ b/frontend/src/test/insight-testing/mocks.ts
@@ -73,7 +73,9 @@ function buildTrendsResponse(series: SeriesData[]): TrendsQueryResponse {
id: `$${s.label.toLowerCase().replace(/\s+/g, '_')}`,
type: 'events',
name: s.label,
- order: s.compare ? 0 : i,
+ // Breakdown rows of a single series share the series' order (as the real query
+ // runner does); only distinct series get distinct orders.
+ order: s.compare || s.breakdown_value != null ? 0 : i,
},
label: s.label,
count: s.data.reduce((a, b) => a + b, 0),
diff --git a/posthog/schema.py b/posthog/schema.py
index e0acb90e2613..ff7a7c0485df 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -9602,6 +9602,13 @@ class TrendsFilter(BaseModel):
showTrendLines: bool | None = None
showValuesOnSeries: bool | None = False
smoothingIntervals: int | None = 1
+ stackBreakdownValues: bool | None = Field(
+ default=False,
+ description=(
+ "On the horizontal bar-value chart, stack a series' breakdown values into a"
+ " single bar instead of rendering one bar per breakdown value."
+ ),
+ )
xAxisLabel: str | None = Field(default=None, description="Custom label rendered under the X axis.")
yAxisLabel: str | None = Field(default=None, description="Custom label rendered alongside the Y axis.")
yAxisScaleType: YAxisScaleType | None = YAxisScaleType.LINEAR
diff --git a/posthog/schema_helpers.py b/posthog/schema_helpers.py
index 11cc7248a54e..98b1f3fce56c 100644
--- a/posthog/schema_helpers.py
+++ b/posthog/schema_helpers.py
@@ -85,6 +85,7 @@ def to_dict(query: BaseModel) -> dict:
not in [
"showLegend",
"showPercentStackView",
+ "stackBreakdownValues",
"showValuesOnSeries",
"aggregationAxisFormat",
"aggregationAxisPrefix",
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index e5663ef03d07..42366d7f08da 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1872,6 +1872,8 @@ export interface TrendsFilterApi {
showTrendLines?: boolean | null
showValuesOnSeries?: boolean | null
smoothingIntervals?: number | null
+ /** On the horizontal bar-value chart, stack a series' breakdown values into a single bar instead of rendering one bar per breakdown value. */
+ stackBreakdownValues?: boolean | null
/** Custom label rendered under the X axis. */
xAxisLabel?: string | null
/** Custom label rendered alongside the Y axis. */
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index b8ffd99e783a..b99737ecb4fa 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -1565,6 +1565,8 @@ export interface TrendsFilterApi {
showTrendLines?: boolean | null
showValuesOnSeries?: boolean | null
smoothingIntervals?: number | null
+ /** On the horizontal bar-value chart, stack a series' breakdown values into a single bar instead of rendering one bar per breakdown value. */
+ stackBreakdownValues?: boolean | null
/** Custom label rendered under the X axis. */
xAxisLabel?: string | null
/** Custom label rendered alongside the Y axis. */
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
index f41ae2a507cc..af0fb901f9e9 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
@@ -283,6 +283,45 @@ describe('TrendsBarChart (ActionsBarValue)', () => {
)
})
+ it('labels each aggregated breakdown bar by its breakdown value, one band per value by default', async () => {
+ renderInsight({
+ query: aggregatedBar({
+ series: [{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' }],
+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },
+ }),
+ featureFlags: HOG_CHARTS_FLAG,
+ })
+ await screen.findByRole('img', { name: /chart with 5 data series/i }, { timeout: 5000 })
+
+ await waitFor(
+ () => {
+ const ticks = getHogChart().yTicks()
+ expect(ticks).toEqual(expect.arrayContaining(['Spike']))
+ expect(ticks).toHaveLength(5)
+ },
+ { timeout: 5000 }
+ )
+ })
+
+ it('collapses breakdown bars onto one band when stackBreakdownValues is set', async () => {
+ renderInsight({
+ query: aggregatedBar({
+ series: [{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' }],
+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },
+ trendsFilter: { display: ChartDisplayType.ActionsBarValue, stackBreakdownValues: true },
+ }),
+ featureFlags: HOG_CHARTS_FLAG,
+ })
+ await screen.findByRole('img', { name: /chart with 5 data series/i }, { timeout: 5000 })
+
+ await waitFor(
+ () => {
+ expect(getHogChart().yTicks()).toHaveLength(1)
+ },
+ { timeout: 5000 }
+ )
+ })
+
it('omits the header from the tooltip', async () => {
renderInsight({
query: aggregatedBar(),
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
index d4b036bd0bcb..53c43fa828b0 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
@@ -16,14 +16,18 @@ import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisForma
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { insightLogic } from 'scenes/insights/insightLogic'
import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
+import { formatBreakdownLabel, getDisplayNameFromEntityFilter } from 'scenes/insights/utils'
import { teamLogic } from 'scenes/teamLogic'
import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'
import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
import type { IndexedTrendResult } from 'scenes/trends/types'
+import { cohortsModel } from '~/models/cohortsModel'
import { groupsModel } from '~/models/groupsModel'
+import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { InsightVizNode } from '~/queries/schema/schema-general'
import { QueryContext } from '~/queries/types'
+import { getStackBreakdownValues } from '~/queries/utils'
import { ChartDisplayType } from '~/types'
import { AnnotationsLayer } from '../shared/AnnotationsLayer'
@@ -98,6 +102,8 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
} = useValues(trendsDataLogic(insightProps))
const { timezone, weekStartDay, baseCurrency } = useValues(teamLogic)
const { aggregationLabel } = useValues(groupsModel)
+ const { allCohorts } = useValues(cohortsModel)
+ const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)
const isAggregated = display === ChartDisplayType.ActionsBarValue
const isGrouped = display === ChartDisplayType.ActionsUnstackedBar
@@ -113,12 +119,37 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
)
: !!indexedResults[0].data && indexedResults.some((r: IndexedTrendResult) => r.count !== 0))
+ const stackBreakdowns = !!querySource && !!getStackBreakdownValues(querySource)
+
+ const getAggregatedDisplayLabel = useCallback(
+ (r: IndexedTrendResult): string => {
+ if (stackBreakdowns) {
+ // Breakdown values within the band are distinguished by color and the tooltip.
+ return getDisplayNameFromEntityFilter(r.action) ?? r.label ?? ''
+ }
+ if (r.breakdown_value != null) {
+ return formatBreakdownLabel(
+ r.breakdown_value,
+ breakdownFilter,
+ allCohorts?.results,
+ formatPropertyValueForDisplay,
+ undefined,
+ r.label
+ )
+ }
+ return r.label ?? ''
+ },
+ [stackBreakdowns, breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay]
+ )
+
const { series, labels, displayLabels } = useMemo(() => {
if (isAggregated) {
return buildTrendsBarAggregatedSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {
getColor: getTrendsColor,
getHidden: getTrendsHidden,
buildMeta: buildTrendsSeriesMeta,
+ stackBreakdowns,
+ getDisplayLabel: getAggregatedDisplayLabel,
})
}
const timeSeries = buildTrendsBarTimeSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {
@@ -131,7 +162,15 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
labels: currentPeriodResult?.labels ?? EMPTY_LABELS,
displayLabels: undefined,
}
- }, [isAggregated, indexedResults, getTrendsColor, getTrendsHidden, currentPeriodResult?.labels])
+ }, [
+ isAggregated,
+ indexedResults,
+ getTrendsColor,
+ getTrendsHidden,
+ currentPeriodResult?.labels,
+ stackBreakdowns,
+ getAggregatedDisplayLabel,
+ ])
const valueLabelFormatter = useCallback(
(value: number) => {
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 4d370aa32efb..50c58e838ea0 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
@@ -94,23 +94,50 @@ describe('buildTrendsBarAggregatedSeries', () => {
expect(new Set(labels).size).toBe(4)
})
- it('groups same-label breakdown rows of one series onto one band (overlap layout preserved)', () => {
- // Formula+breakdown shape: each formula carries a top-level `order`; breakdown rows of
- // the same formula share it, so they share a band and the overlap-on-top visual holds.
- const spec: [string, number][] = [
- ['Binary Size', 0],
- ['Binary Size', 0],
- ['Binary Size', 0],
- ['Embedded Assets', 1],
- ['Embedded Assets', 1],
- ['Runtime & Code', 2],
- ['Runtime & Code', 2],
+ // Formula+breakdown shape: each formula carries a top-level `order`; breakdown rows of the
+ // same formula share both the formula label and the order. They must NOT collapse by default.
+ const formulaBreakdownSpec: [string, number][] = [
+ ['Binary Size', 0],
+ ['Binary Size', 0],
+ ['Binary Size', 0],
+ ['Embedded Assets', 1],
+ ['Embedded Assets', 1],
+ ['Runtime & Code', 2],
+ ['Runtime & Code', 2],
+ ]
+
+ it.each([
+ { name: 'separate by default — one band per breakdown value', stackBreakdowns: undefined, expectedBands: 7 },
+ { name: 'one band per formula when stackBreakdowns is set', stackBreakdowns: true, expectedBands: 3 },
+ ])('formula breakdown rows: $name', ({ stackBreakdowns, expectedBands }) => {
+ const results = formulaBreakdownSpec.map(([label, order], i) => mkResult({ id: `r${i}`, label, order }))
+ const { labels } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED, stackBreakdowns })
+ expect(new Set(labels).size).toBe(expectedBands)
+ })
+
+ it('keeps each result label as its band display label in separate mode', () => {
+ const results = formulaBreakdownSpec.map(([label, order], i) => mkResult({ id: `r${i}`, label, order }))
+ const { displayLabels } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED })
+ expect(displayLabels).toEqual(formulaBreakdownSpec.map(([label]) => label))
+ })
+
+ it('keeps current and previous on separate bands in stacked mode even at the same order', () => {
+ const results = [
+ mkResult({ id: 'a', label: 'F', order: 0, compare_label: 'current', breakdown_value: 'Chrome' }),
+ mkResult({ id: 'b', label: 'F', order: 0, compare_label: 'current', breakdown_value: 'Safari' }),
+ mkResult({ id: 'c', label: 'F', order: 0, compare_label: 'previous', breakdown_value: 'Chrome' }),
]
- const results = spec.map(([label, order], i) => mkResult({ id: `r${i}`, label, order }))
- const { labels, displayLabels } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED })
- expect(displayLabels).toEqual(spec.map(([label]) => label))
- // 7 results, but only 3 distinct band slots — one per formula.
- expect(new Set(labels).size).toBe(3)
+ const { labels } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED, stackBreakdowns: true })
+ expect(new Set(labels).size).toBe(2)
+ })
+
+ it('uses getDisplayLabel for the category label when provided', () => {
+ const results = [mkResult({ id: 'a', label: 'Formula (A + B)', breakdown_value: 'Chrome' })]
+ const { displayLabels } = buildTrendsBarAggregatedSeries(results, {
+ getColor: () => RED,
+ getDisplayLabel: (r) => String(r.breakdown_value),
+ })
+ expect(displayLabels).toEqual(['Chrome'])
})
it('places each aggregated_value at the index matching its own band — zero everywhere else', () => {
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
index aea6bf0090d7..e78d28632774 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
@@ -31,6 +31,14 @@ export interface BuildTrendsBarSeriesOpts<R extends TrendsBarResultLike, M = unk
buildMeta?: (r: R, index: number) => M
}
+export interface BuildTrendsBarAggregatedSeriesOpts<
+ R extends TrendsBarResultLike,
+ M = unknown,
+> extends BuildTrendsBarSeriesOpts<R, M> {
+ stackBreakdowns?: boolean
+ getDisplayLabel?: (r: R, index: number) => string
+}
+
function buildMainTrendsBarSeries<R extends TrendsBarResultLike, M = unknown>(
r: R,
index: number,
@@ -98,7 +106,7 @@ export function buildTrendsBarTimeSeriesConfig(opts: BuildTrendsBarTimeSeriesCon
}
}
-/** Separator between display label and series id in synthetic band keys. */
+/** Separator between the series id and compare label in synthetic stacked-mode band keys. */
const BAND_KEY_SEP = '\u001f'
// Sparse-stacked: hog-charts BarChart allows one color per series, so we emit N series with
@@ -106,20 +114,25 @@ const BAND_KEY_SEP = '\u001f'
// Trade-off: only the last series gets rounded-corner caps.
export function buildTrendsBarAggregatedSeries<R extends TrendsBarResultLike, M = unknown>(
results: R[],
- opts: BuildTrendsBarSeriesOpts<R, M>
+ opts: BuildTrendsBarAggregatedSeriesOpts<R, M>
): { series: Series<M>[]; labels: string[]; displayLabels: string[] } {
// Hidden results are dropped entirely — keeping them as `excluded` series would leave
// a phantom band on the category axis with no bar.
const visible = opts.getHidden ? results.filter((r, i) => !opts.getHidden!(r, i)) : results
- const displayLabels = visible.map((r) => {
- const base = r.label ?? ''
+ const displayLabels = visible.map((r, i) => {
+ const base = opts.getDisplayLabel ? opts.getDisplayLabel(r, i) : (r.label ?? '')
return r.compare_label ? `${base} - ${r.compare_label}` : base
})
- // Suffix the band key with the series identity so duplicate display labels from
- // different series get distinct bands (breakdowns of one series still share a band).
+ // Band key strategy:
+ // - separate (default): unique per result, so every breakdown value gets its own band.
+ // - stacked: one band per series/formula (keyed by order + compare_label) so a series'
+ // breakdown values collapse onto one band and stack into a single bar.
const labels = visible.map((r, i) => {
+ if (!opts.stackBreakdowns) {
+ return String(i)
+ }
const seriesId = r.action?.order ?? r.order ?? 0
- return `${displayLabels[i]}${BAND_KEY_SEP}${seriesId}`
+ return `${seriesId}${BAND_KEY_SEP}${r.compare_label ?? ''}`
})
const n = visible.length
const series = visible.map((r, index) => {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index de546a0e6dbb..ed471924d116 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2175,6 +2175,8 @@ export namespace Schemas {
showTrendLines?: boolean | null;
showValuesOnSeries?: boolean | null;
smoothingIntervals?: number | null;
+ /** On the horizontal bar-value chart, stack a series' breakdown values into a single bar instead of rendering one bar per breakdown value. */
+ stackBreakdownValues?: boolean | null;
/** Custom label rendered under the X axis. */
xAxisLabel?: string | null;
/** Custom label rendered alongside the Y axis. */