: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(insights): show series names in breakdown labels (#102825)
Sam Penningtonb606f57590db
diff --git a/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsxindex 4d2478e5f446..0f6599713cb7 100644--- a/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx+++ b/products/product_analytics/frontend/insights/shared/InsightSeriesTooltip.tsx@@ -23,6 +23,8 @@ import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'import { BreakdownFilter, CurrencyCode, DateRange, TrendsFilter } from '~/queries/schema/schema-general'import { ActionFilter, CompareLabelType, IntervalType } from '~/types'+import { getSeriesIdentification, type SeriesIdentification } from './seriesIdentification'+// ── Types ──────────────────────────────────────────────────────────────────type InsightSeriesMetaBase = {@@ -110,14 +112,6 @@ function formatHeaderDate(date: string | undefined, options: FormattedDateOption// ── SeriesLabel ────────────────────────────────────────────────────────────-/** How rows must identify the series they belong to:- * `none` — single series (or no way to tell them apart), no identifier needed;- * `name` — series names differ, the name alone identifies a row;- * `letter-and-name` — several series share a display name (e.g. the same event added- * twice with different math/filters), so the name is prefixed with the series letter- * (A, B, …) shown in the insight editor. */-export type SeriesIdentification = 'none' | 'name' | 'letter-and-name'-/** `SeriesDatum` plus the series name for rows whose meta has no `action` (formula series). */type TooltipSeriesDatum = SeriesDatum & { series_name?: string }@@ -269,24 +263,7 @@ export function InsightSeriesTooltip<Meta extends InsightSeriesMetaBase>({return m}, [context.seriesData, context.dataIndex])- const seriesIdentification = useMemo((): SeriesIdentification => {- // One entry per series entity — breakdown/compare rows of one series share its `order`.- // Formula series have no `action`, but their `order` still identifies the formula they- // came from, with `series_name` carrying the formula label.- const nameByEntity = new Map<number | string, string>()- for (const d of datumByKey.values()) {- if (d.action) {- const entityKey = d.action.order ?? `${d.action.type}:${d.action.id}`- nameByEntity.set(entityKey, getDisplayNameFromEntityFilter(d.action) ?? '')- } else if (d.series_name != null) {- nameByEntity.set(d.order, d.series_name)- }- }- if (nameByEntity.size <= 1) {- return 'none'- }- return new Set(nameByEntity.values()).size < nameByEntity.size ? 'letter-and-name' : 'name'- }, [datumByKey])+ const seriesIdentification = useMemo(() => getSeriesIdentification(datumByKey.values()), [datumByKey])const compareDates = useMemo((): Partial<Record<CompareLabelType, string>> => {const dates: Partial<Record<CompareLabelType, string>> = {}diff --git a/products/product_analytics/frontend/insights/shared/seriesIdentification.ts b/products/product_analytics/frontend/insights/shared/seriesIdentification.tsnew file mode 100644index 000000000000..20bac98fd80e--- /dev/null+++ b/products/product_analytics/frontend/insights/shared/seriesIdentification.ts@@ -0,0 +1,27 @@+import { getDisplayNameFromEntityFilter } from 'scenes/insights/utils'++import type { ActionFilter } from '~/types'++export type SeriesIdentification = 'none' | 'name' | 'letter-and-name'++interface SeriesIdentity {+ action?: ActionFilter | null+ order?: number+ series_name?: string+}++export function getSeriesIdentification(series: Iterable<SeriesIdentity>): SeriesIdentification {+ const nameByEntity = new Map<number | string, string>()+ for (const item of series) {+ if (item.action) {+ const entityKey = item.action.order ?? `${item.action.type}:${item.action.id}`+ nameByEntity.set(entityKey, getDisplayNameFromEntityFilter(item.action) ?? '')+ } else if (item.series_name != null && item.order != null) {+ nameByEntity.set(item.order, item.series_name)+ }+ }+ if (nameByEntity.size <= 1) {+ return 'none'+ }+ return new Set(nameByEntity.values()).size < nameByEntity.size ? 'letter-and-name' : 'name'+}diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsxindex aa3dc46a5090..eecc76f38bd7 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx+++ b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx@@ -23,6 +23,7 @@ import type { IndexedTrendResult } from 'products/product_analytics/frontend/insimport { hasTrendsChartData } from '../../shared/hasTrendsChartData'import { InsightSeriesTooltip } from '../../shared/InsightSeriesTooltip'+import { getSeriesIdentification } from '../../shared/seriesIdentification'import { makeChartErrorHandler } from '../../trends/shared/chartErrorHandler'import { getTrendsSeriesDisplayLabel } from '../../trends/shared/getTrendsSeriesDisplayLabel'import {@@ -65,20 +66,34 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.ElhasPersonsModal,querySource,showValuesOnSeries,+ isSingleSeriesDefinition,} = useValues(trendsDataLogic(insightProps))const { timezone, baseCurrency } = useValues(teamLogic)const { aggregationLabel } = useValues(groupsModel)const { allCohorts } = useValues(cohortsModel)const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)+ const seriesIdentification = useMemo(+ () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),+ [indexedResults]+ )+const getLabel = useCallback((r: IndexedTrendResult): string =>getTrendsSeriesDisplayLabel(r, {breakdownFilter,cohorts: allCohorts?.results,formatPropertyValueForDisplay,+ isSingleSeriesDefinition,+ seriesIdentification,}),- [breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay]+ [+ breakdownFilter,+ allCohorts?.results,+ formatPropertyValueForDisplay,+ isSingleSeriesDefinition,+ seriesIdentification,+ ])// Inverted polarity vs legacy `isStacked` in `ActionsLineGraph`; matches `TrendsBarChart`.diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsxindex bc24d3c07a5f..5e6ca8b8cecb 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx@@ -23,6 +23,7 @@ import type { IndexedTrendResult } from 'products/product_analytics/frontend/insimport { chartStyleCurve } from '../../shared/chartStyleAdapter'import { hasTrendsChartData } from '../../shared/hasTrendsChartData'import { InsightSeriesTooltip } from '../../shared/InsightSeriesTooltip'+import { getSeriesIdentification } from '../../shared/seriesIdentification'import { makeChartErrorHandler } from '../../trends/shared/chartErrorHandler'import { getTrendsSeriesDisplayLabel } from '../../trends/shared/getTrendsSeriesDisplayLabel'import {@@ -68,12 +69,17 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.hasPersonsModal,querySource,showValuesOnSeries,+ isSingleSeriesDefinition,} = useValues(trendsDataLogic(insightProps))const { timezone, baseCurrency } = useValues(teamLogic)const { aggregationLabel } = useValues(groupsModel)const { allCohorts } = useValues(cohortsModel)const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)+ const seriesIdentification = useMemo(+ () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),+ [indexedResults]+ )const resolvedGroupTypeLabel = context?.groupTypeLabel ?? resolveGroupTypeLabel(labelGroupType, aggregationLabel)const getLabel = useCallback(@@ -82,8 +88,16 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.breakdownFilter,cohorts: allCohorts?.results,formatPropertyValueForDisplay,+ isSingleSeriesDefinition,+ seriesIdentification,}),- [breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay]+ [+ breakdownFilter,+ allCohorts?.results,+ formatPropertyValueForDisplay,+ isSingleSeriesDefinition,+ seriesIdentification,+ ])const labels = currentPeriodResult?.labels ?? []diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsxindex 44c4a10bea8e..e039ea56a413 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx@@ -35,6 +35,7 @@ import type { IndexedTrendResult } from 'products/product_analytics/frontend/insimport { hasTrendsChartData } from '../../shared/hasTrendsChartData'import { InsightSeriesTooltip } from '../../shared/InsightSeriesTooltip'+import { getSeriesIdentification } from '../../shared/seriesIdentification'import { INSIGHT_TOOLTIP_CONFIG } from '../../shared/tooltipConfig'import { makeChartErrorHandler } from '../shared/chartErrorHandler'import { getTrendsSeriesDisplayLabel } from '../shared/getTrendsSeriesDisplayLabel'@@ -116,12 +117,18 @@ export function TrendsBarChart({goalLines,showValuesOnSeries,showMultipleYAxes,+ isSingleSeriesDefinition,} = useValues(trendsDataLogic(insightProps))const { timezone, weekStartDay, baseCurrency } = useValues(teamLogic)const { aggregationLabel } = useValues(groupsModel)const { allCohorts } = useValues(cohortsModel)const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)+ const seriesIdentification = useMemo(+ () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),+ [indexedResults]+ )+const isAggregated = display === ChartDisplayType.ActionsBarValueconst isGrouped = display === ChartDisplayType.ActionsUnstackedBarconst isPercentStackView = !isAggregated && !!showPercentStackView && !!supportsPercentStackView@@ -152,8 +159,16 @@ export function TrendsBarChart({breakdownFilter,cohorts: allCohorts?.results,formatPropertyValueForDisplay,+ isSingleSeriesDefinition,+ seriesIdentification,}),- [breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay]+ [+ breakdownFilter,+ allCohorts?.results,+ formatPropertyValueForDisplay,+ isSingleSeriesDefinition,+ seriesIdentification,+ ])const { series, labels, displayLabels } = useMemo(() => {diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsxindex fb89641ee88b..4e56a6642312 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx@@ -811,6 +811,25 @@ describe('TrendsLineChart', () => {expect(container.querySelector('.InsightLegendMenu')).not.toBeInTheDocument()})+ it('adds series letters when same-named series share a breakdown', async () => {+ const { container } = renderInsight({+ query: buildTrendsQuery({+ series: [+ { kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },+ { kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },+ ],+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },+ trendsFilter: { showLegend: true },+ }),+ })++ await waitFor(() => {+ const legendText = getInChartLegend(container).textContent+ expect(legendText).toContain('A Napped · Spike')+ expect(legendText).toContain('B Napped · Spike')+ })+ })+it('keeps a toggled-off series listed and dimmed in the legend but out of the tooltip', async () => {const { container } = renderInsight({ query: twoSeriesQuery })diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsxindex c709bc264190..f1c8a4176c64 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx@@ -32,6 +32,7 @@ import type { IndexedTrendResult } from 'products/product_analytics/frontend/insimport { chartStyleCurve } from '../../shared/chartStyleAdapter'import { hasTrendsChartData } from '../../shared/hasTrendsChartData'import { InsightSeriesTooltip } from '../../shared/InsightSeriesTooltip'+import { getSeriesIdentification } from '../../shared/seriesIdentification'import { INSIGHT_TOOLTIP_CONFIG } from '../../shared/tooltipConfig'import { makeChartErrorHandler } from '../shared/chartErrorHandler'import { getTrendsSeriesDisplayLabel } from '../shared/getTrendsSeriesDisplayLabel'@@ -111,20 +112,34 @@ export function TrendsLineChart({showValuesOnSeries,showConfidenceIntervals,confidenceLevel,+ isSingleSeriesDefinition,} = useValues(trendsDataLogic(insightProps))const { timezone, weekStartDay, baseCurrency } = useValues(teamLogic)const { aggregationLabel } = useValues(groupsModel)const { allCohorts } = useValues(cohortsModel)const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)+ const seriesIdentification = useMemo(+ () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),+ [indexedResults]+ )+const getLabel = useCallback((r: IndexedTrendResult): string =>getTrendsSeriesDisplayLabel(r, {breakdownFilter,cohorts: allCohorts?.results,formatPropertyValueForDisplay,+ isSingleSeriesDefinition,+ seriesIdentification,}),- [breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay]+ [+ breakdownFilter,+ allCohorts?.results,+ formatPropertyValueForDisplay,+ isSingleSeriesDefinition,+ seriesIdentification,+ ])const isPercentStackView = !!showPercentStackView && !!supportsPercentStackViewdiff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsxindex 1876fd56e04c..cb533c34bf06 100644--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/TrendsPieChart.tsx@@ -29,8 +29,9 @@ import type { IndexedTrendResult } from 'products/product_analytics/frontend/insimport { datasetToActorsQuery } from 'products/product_analytics/frontend/insights/trends/viz/datasetToActorsQuery'import { InsightSeriesTooltip } from '../../shared/InsightSeriesTooltip'+import { getSeriesIdentification } from '../../shared/seriesIdentification'import { getTrendsSeriesDisplayLabel } from '../shared/getTrendsSeriesDisplayLabel'-import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'+import { buildTrendsSeriesMeta, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'import { useInsightsLegendConfig } from '../shared/useInsightsLegendConfig'import { DonutCenterLabel } from './DonutCenterLabel'import { buildTrendsPieSeries } from './trendsPieTransforms'@@ -80,9 +81,14 @@ export function TrendsPieChart({labelGroupType,getTrendsColor,getTrendsHidden,+ isSingleSeriesDefinition,} = useValues(trendsDataLogic(insightProps))const isPercentStackView = !!showPercentStackView && !!supportsPercentStackView+ const seriesIdentification = useMemo(+ () => getSeriesIdentification((indexedResults ?? []).map(buildTrendsSeriesMeta)),+ [indexedResults]+ )const resolvedGroupTypeLabel =context?.groupTypeLabel ??@@ -104,8 +110,16 @@ export function TrendsPieChart({breakdownFilter,cohorts: allCohorts.results,formatPropertyValueForDisplay,+ isSingleSeriesDefinition,+ seriesIdentification,}),- [breakdownFilter, allCohorts.results, formatPropertyValueForDisplay]+ [+ breakdownFilter,+ allCohorts.results,+ formatPropertyValueForDisplay,+ isSingleSeriesDefinition,+ seriesIdentification,+ ])const series: Series<TrendsSeriesMeta>[] = useMemo(diff --git a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.tsindex 3ea4ed083d93..6653b9255a8f 100644--- a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts+++ b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts@@ -8,12 +8,16 @@ const NO_BREAKDOWN_DEPS: TrendsSeriesLabelDeps = {formatPropertyValueForDisplay: undefined,}+const BREAKDOWN_DEPS: TrendsSeriesLabelDeps = {+ breakdownFilter: { breakdown_type: 'event', breakdown: '$browser' },+ cohorts: undefined,+ formatPropertyValueForDisplay: undefined,+}+const makeResult = (overrides: Partial<IndexedTrendResult>): IndexedTrendResult =>({ id: 0, label: '$pageview', data: [], ...overrides }) as IndexedTrendResultdescribe('getTrendsSeriesDisplayLabel', () => {- // Guards the legend regression: the in-chart legend must show the series' custom name, not the- // raw event/action name. A revert to `humanizeSeriesLabel(r.label)` would fail the custom-name case.it.each([['custom name wins over the event name', { action: { name: '$pageview', custom_name: 'Signups' } }, 'Signups'],['humanizes the event name when no custom name', { action: { name: '$pageview' } }, 'Pageview'],@@ -29,18 +33,32 @@ describe('getTrendsSeriesDisplayLabel', () => {).toBe(expected)})- it('resolves to the breakdown value, not the custom name, for breakdown series', () => {- // The action (and its custom_name) is shared across every breakdown band, so the breakdown- // value must win — otherwise all bands collapse onto one label.+ it.each([+ ['the series name and breakdown value for multiple series', {}, {}, 'Signups · Chrome'],+ [+ 'the series letter when display names collide',+ {},+ { seriesIdentification: 'letter-and-name' },+ 'A Signups · Chrome',+ ],+ ['the breakdown value alone for a single-series query', {}, { isSingleSeriesDefinition: true }, 'Chrome'],+ [+ 'the formula name and breakdown value for a formula row',+ { action: null, label: 'A + B' },+ {},+ 'A + B · Chrome',+ ],+ ])('resolves to %s', (_name, resultOverrides, depOverrides, expected) => {const result = makeResult({action: { custom_name: 'Signups' } as IndexedTrendResult['action'],breakdown_value: 'Chrome',+ ...(resultOverrides as Partial<IndexedTrendResult>),})- const deps: TrendsSeriesLabelDeps = {- breakdownFilter: { breakdown_type: 'event', breakdown: '$browser' },- cohorts: undefined,- formatPropertyValueForDisplay: undefined,- }- expect(getTrendsSeriesDisplayLabel(result, deps)).toBe('Chrome')+ expect(+ getTrendsSeriesDisplayLabel(result, {+ ...BREAKDOWN_DEPS,+ ...(depOverrides as Partial<TrendsSeriesLabelDeps>),+ })+ ).toBe(expected)})})diff --git a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.tsindex 787136de44df..1f2a3d88757d 100644--- a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts+++ b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts@@ -1,3 +1,4 @@+import { alphabet } from 'lib/utils/strings'import { formatBreakdownLabel, getDisplayNameFromEntityFilter } from 'scenes/insights/utils'import type { FormatPropertyValueForDisplayFunction } from '~/models/propertyDefinitionsModel'@@ -6,21 +7,21 @@ import type { CohortType } from '~/types'import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'+import type { SeriesIdentification } from '../../shared/seriesIdentification'import { humanizeSeriesLabel } from './humanizeSeriesLabel'export interface TrendsSeriesLabelDeps {breakdownFilter: BreakdownFilter | null | undefinedcohorts: CohortType[] | undefinedformatPropertyValueForDisplay: FormatPropertyValueForDisplayFunction | undefined+ isSingleSeriesDefinition?: boolean+ seriesIdentification?: SeriesIdentification}-/** Legend/series label for a single trends result. The user's custom rename (`action.custom_name`,- * set via the series rename UI) wins over the raw event/action name; breakdown series resolve to- * their formatted breakdown value. The `action` is shared across a series' breakdown values, so the- * breakdown guard must come first — otherwise every breakdown band would collapse onto one label. */export function getTrendsSeriesDisplayLabel(r: IndexedTrendResult, deps: TrendsSeriesLabelDeps): string {+ const seriesName = getDisplayNameFromEntityFilter(r.action) ?? humanizeSeriesLabel(r.label)if (r.breakdown_value != null) {- return formatBreakdownLabel(+ const breakdownLabel = formatBreakdownLabel(r.breakdown_value,deps.breakdownFilter,deps.cohorts,@@ -28,6 +29,14 @@ export function getTrendsSeriesDisplayLabel(r: IndexedTrendResult, deps: TrendsSundefined,r.label)+ if (deps.isSingleSeriesDefinition) {+ return breakdownLabel+ }+ const seriesPrefix =+ deps.seriesIdentification === 'letter-and-name'+ ? `${alphabet[r.action?.order ?? r.order ?? 0]} ${seriesName}`+ : seriesName+ return `${seriesPrefix} · ${breakdownLabel}`}- return getDisplayNameFromEntityFilter(r.action) ?? humanizeSeriesLabel(r.label)+ return seriesName}