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): show series custom name in in-chart legend (#66203)

Steven Shults794a91c4e308
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index cd7e58ee9c0e..0f4b928b37c7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2481,9 +2481,9 @@ snapshots:
insights-funnellinechart--value-labels--light:
hash: v1.k794b7964.e77fc0556d6cb2928d6f4733a2469335c193dc4e69d3709979b56c48b3336a26.-ANj2Y7kjX0XvQaWN4iIavrWM-Spk8vjpICJr4WX5_0
insights-funnellinechart--with-legend--dark:
- hash: v1.k794b7964.6c58b60fb6fe098f82269bb90abd93f328395da35d45ea130256987bcccc2214.Kd0RUQaPljabFqiPKo6FDiSeCCFlgwfYyJQgC8AtYLs
+ hash: v1.k794b7964.a55ce8954a2a9617baa1bc4699a883c25a5efc07e3180f937b58925f05b391d6.wpol2eLJyIFMCWDr9ghi2ZWLKKs9VKOxUJUQMwjIPsA
insights-funnellinechart--with-legend--light:
- hash: v1.k794b7964.814e7addc2f121aed26b646f3be6981ecabfcb72054ebcf671bf939ff599d945.BcXL3z4XlxOgh4GkOcGzIuuL7ydYn_p_2NS7CpmidvM
+ hash: v1.k794b7964.5873f00573762f50860835ab9636dd1114bcd05be6eda60da041cbf734aa0aeb.-4-_gc2ESmQmr8PNmQny_x93pVMTU7EY6fQjjYt56lw
insights-funnellinechart-tooltip--breakdown-ordered-by-conversion--dark:
hash: v1.k794b7964.28fcb86c4f61884b1c2d0d6956482149d06c7a49a8425aa040b4ae36e2ac6c50.i5loD1ggBoEypNfx7cLJUjqPTUWcUXid0YcZUP0igpM
insights-funnellinechart-tooltip--breakdown-ordered-by-conversion--light:
@@ -2617,9 +2617,9 @@ snapshots:
insights-trendslifecyclechart--stacked--light:
hash: v1.k794b7964.6f542884e9d767dcf000afd0604296d1b7c88ffacae02136c6657f2ba2cc0b8d.btS_HEQZaP1c2kExtglIP7xO9JH4GOO37MLrDfhcnDo
insights-trendslifecyclechart--stacked-with-legend--dark:
- hash: v1.k794b7964.5ab4d649cc919964c17e19bea4ab57c3f97ae9a52449c84119baf0fa9d6fb151.DCQvKv1u3XpVfZoZZAMkP-Qwu-SEEhp485oJsdK0EXo
+ hash: v1.k794b7964.c99421b52af935afabb39350ba2a11c304a3a6a690a8a2354762ef4e75ce1cf2.T9DdcQGe0211HuTm26gdyzSJsPxnXRMRvJsTmQG_-kg
insights-trendslifecyclechart--stacked-with-legend--light:
- hash: v1.k794b7964.57a2cdf284c58efefaedebf2cf80f70a839600edde39c17acb3f51088372e613.bOhwN6zBvOA46W2w1Mhbh62N4ZWahoxYauqwkrQuxf4
+ hash: v1.k794b7964.4270d6defbb370ea52d45fc9485bb625970c9b6b5181b6289132070392d2b807.Xk8absK51TdOh0ipMUZWdNQUvEzaF-pPGMDgKJvgZLU
insights-trendslifecyclechart--stacked-with-percentages-on-series--dark:
hash: v1.k794b7964.a07939aacffaca561bf32b6d94c8c1fe24b401a097633e3ddc830dee3dd01564.jaqXSLUJl_Sv4mJP-_CUEyd1xXeNRTxmh7f4ueVidqM
insights-trendslifecyclechart--stacked-with-percentages-on-series--light:
@@ -2637,9 +2637,9 @@ snapshots:
insights-trendslifecyclechart--unstacked--light:
hash: v1.k794b7964.1d01deb9c9081a6ad5e5554fa0efb1df960051a8663d037000599783bcdb3873._yrVG5fErPmwKntTMK9MmgqTrAsOdo20FXhPqKD-39k
insights-trendslifecyclechart--unstacked-with-legend--dark:
- hash: v1.k794b7964.dcdc8528fb0e36f462200a73a591836d599009ad8d3ece4f49b66df4bad23138.7aHOY8gLlu50TfodzVnWHGx_zhse_p9u_yqLmYDF-sM
+ hash: v1.k794b7964.574220a7b896d56d62b6e0f63cf27003a77e91616847536bb2b1d922ceeb97a1.eM7oXJJzIVp533_JGuQNo_RRejNhBv9n0okTjZzOs4Y
insights-trendslifecyclechart--unstacked-with-legend--light:
- hash: v1.k794b7964.ae1037a551d24f0d8a9bf5f94bc6cc8921eb3d979fb910426f9563f8d56f7f5b.tgvY_MUl5V_KREh7iWdPtwnpcHBSkvFkqPFRKmNTLr8
+ hash: v1.k794b7964.2256dd4ae7dd4b50df9adfe0dbdd1af2fe7a337a69d75cfa0fea2763dd00fae7.Bhs-r2irJrYC5LDouGsRe8NsjM0hzcDdPvnNtOhPOhw
insights-trendslifecyclechart--unstacked-with-percentages-on-series--dark:
hash: v1.k794b7964.e89fef8b35437fb4e4dc345c809e7e8a8d84df5f4114e59e9eb7d773b310fb23.9GII3E9SZ9-KPi_lgA6rjSV23tfGVlVUXArAaYkdW-Q
insights-trendslifecyclechart--unstacked-with-percentages-on-series--light:
@@ -6225,9 +6225,9 @@ snapshots:
scenes-app-posthog-ai--generation-failure-thread--light:
hash: v1.k794b7964.2466d52afb9f60e1df1da396d3489696b420357fe6ae84980b3514be4aaafbd3.6HsoitoqUEDTx68Gz38cIHl84jCI-zF1a7YJ4rczj-w
scenes-app-posthog-ai--multi-visualization-in-thread--dark:
- hash: v1.k794b7964.69ba29ff5ae3e924fc9c0afd2c11362676628eecce218c9dc94632859fc0acc4.7vwX-9bINKddlF5MxNvmGl0t4NBKInr8pzXfgfOxRGQ
+ hash: v1.k794b7964.37958625f0b04c1e69899ed3af8907af4e0a11ed1df80201e3d9f0405b5ac60d.OlP2qMlOd2FvOTJO_TpWBOulU3g_YDYgC5W2alvijO8
scenes-app-posthog-ai--multi-visualization-in-thread--light:
- hash: v1.k794b7964.ec32f784fb4084e076ca55b320fbbd541620c69d41e12d1d390b409f8ed15f72.lZsJ9fL2DrPJQwh3ZfW1vofBCNvWQ6BEK-NPwSLWf8k
+ hash: v1.k794b7964.a1799f847c1a184b3ea87b9c64af484396619eb90f7ba10582ef94a822aec387.xBt1KDXIkrBmbHpVHaqXdVmv14UZdkrIT6-LET5kE4g
scenes-app-posthog-ai--notebook-artifact-markdown-only--dark:
hash: v1.k794b7964.3bf04c9fd8f9a2654162d001c454676e859951f738d1a3b3f44931ac58d3c1de.1Cyyg8kv0tdZXfY_w8ABNotfhGQfChtz23ioBsYlQTM
scenes-app-posthog-ai--notebook-artifact-markdown-only--light:
diff --git a/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx b/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx
index 49c17bcf5b9d..e731bdb9a654 100644
--- a/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx
@@ -1,14 +1,11 @@
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
-import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
-
-import { useInsightDisplayOptions } from '~/queries/nodes/InsightViz/insightDisplayOptions'
-
-// The insight editor's "Options" menu, surfaced as a submenu in the dashboard card ⋯ menu. Edits
-// persist to the saved insight via the card's `setQuery` wiring (see InsightCard).
-export function DashboardInsightDisplayOptions(): JSX.Element | null {
- const { items } = useInsightDisplayOptions()
+import { LemonMenu, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
+// Items are computed in InsightMeta (always mounted) and passed down to avoid mounting
+// useInsightDisplayOptions lazily inside the More popover overlay, which triggers kea logic
+// mounts that cascade and close the popover before the user can interact with it.
+export function DashboardInsightDisplayOptions({ items }: { items: LemonMenuItems }): JSX.Element | null {
if (items.length === 0) {
return null
}
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index a7a2cd6418b5..990ad15485ba 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -41,6 +41,7 @@ import { urls } from 'scenes/urls'
import { dashboardsModel } from '~/models/dashboardsModel'
import { insightsModel } from '~/models/insightsModel'
+import { useInsightDisplayOptions } from '~/queries/nodes/InsightViz/insightDisplayOptions'
import { Node, ProductKey } from '~/queries/schema/schema-general'
import { isDataVisualizationNode } from '~/queries/utils'
import {
@@ -200,6 +201,9 @@ export function InsightMeta({
})
const showDisplayOptionsMenu = isUsedAsDashboardTile && canEditInsight && !!persistDisplayOptions
+ // Hoist the hook out of the More overlay so kea logics it mounts don't do so lazily inside a
+ // portal, which cascades into closing the dropdown before the user can interact with it.
+ const { items: displayOptionItems } = useInsightDisplayOptions()
const hasTileStyleActions = !!(showCompactTile && toggleShowDescription && insight.description) || !!updateColor
const canShowCopyToDashboardTile = showCompactTile && !!copyToDashboard && canViewInsight
@@ -461,7 +465,7 @@ export function InsightMeta({
Alerts
</LemonButton>
) : null}
- {showDisplayOptionsMenu && <DashboardInsightDisplayOptions />}
+ {showDisplayOptionsMenu && <DashboardInsightDisplayOptions items={displayOptionItems} />}
{canShowCopyToDashboardTile && !canEditDashboard && (
<>
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
index 68c5b580fc21..6672a5ccfa85 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
@@ -243,7 +243,7 @@ describe('InsightDisplayConfig', () => {
'Stack bars',
'Show values on series',
'Show percentages on series',
- 'Show legendBottom',
+ 'Show legendRight',
],
},
],
@@ -378,6 +378,7 @@ describe('InsightDisplayConfig', () => {
const legendItem = getDisplaySectionItems().find((item) => item.includes('Show legend'))
expect(legendItem).toBeTruthy()
+ // legend is off, no saved position → shows 'Bottom' as the prospective default
expect(legendItem).toContain('Bottom')
})
@@ -393,7 +394,8 @@ describe('InsightDisplayConfig', () => {
const legendItem = getDisplaySectionItems().find((item) => item.includes('Show legend'))
expect(legendItem).toBeTruthy()
- expect(legendItem).toContain('Bottom')
+ // Lifecycle sets showLegend:true (no saved position → 'Right'); others have legend off (→ 'Bottom').
+ expect(legendItem).toMatch(/Bottom|Right/)
})
it('keeps the plain "Show legend" checkbox for the aggregated bar-value chart', async () => {
diff --git a/frontend/src/scenes/insights/EditorFilters/LegendOptionsFilter.tsx b/frontend/src/scenes/insights/EditorFilters/LegendOptionsFilter.tsx
index f2c45bb4c282..a689ff2c70aa 100644
--- a/frontend/src/scenes/insights/EditorFilters/LegendOptionsFilter.tsx
+++ b/frontend/src/scenes/insights/EditorFilters/LegendOptionsFilter.tsx
@@ -25,14 +25,20 @@ export function LegendOptionsFilter(): JSX.Element {
return (
<div className="flex items-center justify-between gap-2 p-1 px-2">
<LemonCheckbox
- onChange={(checked) => updateInsightFilter({ showLegend: checked })}
+ onChange={(checked) =>
+ updateInsightFilter({
+ showLegend: checked,
+ // Seed bottom on first enable — old insights without a saved position render right (chart-config fallback).
+ ...(checked && legendPosition == null ? { legendPosition: 'bottom' } : {}),
+ })
+ }
checked={!!showLegend}
label={<span className="font-normal">Show legend</span>}
size="small"
/>
<LemonSelect
size="small"
- value={(legendPosition ?? 'bottom') as LegendPosition}
+ value={(legendPosition ?? (showLegend ? 'right' : 'bottom')) as LegendPosition}
options={POSITION_OPTIONS}
disabledReason={!showLegend ? 'Enable the legend to set its position' : undefined}
onChange={(position) => updateInsightFilter({ legendPosition: position })}
diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx
index 585f34105e01..133088043450 100644
--- a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx
+++ b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx
@@ -13,12 +13,15 @@ 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 { ChartDisplayType } from '~/types'
import { makeChartErrorHandler } from '../../trends/shared/chartErrorHandler'
+import { getTrendsSeriesDisplayLabel } from '../../trends/shared/getTrendsSeriesDisplayLabel'
import {
buildTrendsSeriesMeta,
resolveGroupTypeLabel,
@@ -66,6 +69,18 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.El
} = useValues(trendsDataLogic(insightProps))
const { timezone, baseCurrency } = useValues(teamLogic)
const { aggregationLabel } = useValues(groupsModel)
+ const { allCohorts } = useValues(cohortsModel)
+ const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)
+
+ const getLabel = useCallback(
+ (r: IndexedTrendResult): string =>
+ getTrendsSeriesDisplayLabel(r, {
+ breakdownFilter,
+ cohorts: allCohorts?.results,
+ formatPropertyValueForDisplay,
+ }),
+ [breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay]
+ )
// Inverted polarity vs legacy `isStacked` in `ActionsLineGraph`; matches `TrendsBarChart`.
const isGrouped = display === ChartDisplayType.ActionsUnstackedBar
@@ -85,9 +100,10 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.El
// With the quill legend on, hidden series stay listed (dimmed) and are excluded via
// config.legend.hiddenKeys instead of being dropped here, so the legend can restore them.
getHidden: quillLegendEnabled ? undefined : getTrendsHidden,
+ getLabel,
buildMeta: buildTrendsSeriesMeta,
}),
- [indexedResults, getTrendsColor, getTrendsHidden, quillLegendEnabled]
+ [indexedResults, getTrendsColor, getTrendsHidden, getLabel, quillLegendEnabled]
)
const chartConfig: TimeSeriesBarChartConfig = useMemo(
diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx
index 54def9175274..296e4c0c104f 100644
--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx
+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx
@@ -13,11 +13,14 @@ 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 { makeChartErrorHandler } from '../../trends/shared/chartErrorHandler'
+import { getTrendsSeriesDisplayLabel } from '../../trends/shared/getTrendsSeriesDisplayLabel'
import {
buildTrendsSeriesMeta,
resolveGroupTypeLabel,
@@ -67,9 +70,21 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.
} = useValues(trendsDataLogic(insightProps))
const { timezone, baseCurrency } = useValues(teamLogic)
const { aggregationLabel } = useValues(groupsModel)
+ const { allCohorts } = useValues(cohortsModel)
+ const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)
const resolvedGroupTypeLabel = context?.groupTypeLabel ?? resolveGroupTypeLabel(labelGroupType, aggregationLabel)
+ const getLabel = useCallback(
+ (r: IndexedTrendResult): string =>
+ getTrendsSeriesDisplayLabel(r, {
+ breakdownFilter,
+ cohorts: allCohorts?.results,
+ formatPropertyValueForDisplay,
+ }),
+ [breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay]
+ )
+
const bucketCount = currentPeriodResult?.labels?.length ?? 0
const labels = useMemo(() => buildStickinessLabels(bucketCount, interval), [bucketCount, interval])
@@ -87,9 +102,10 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.
// With the quill legend on, hidden series stay listed (dimmed) and are excluded via
// config.legend.hiddenKeys instead of being dropped here, so the legend can restore them.
getHidden: quillLegendEnabled ? undefined : getTrendsHidden,
+ getLabel,
buildMeta: buildTrendsSeriesMeta,
}),
- [indexedResults, display, getTrendsColor, getTrendsHidden, showMultipleYAxes, quillLegendEnabled]
+ [indexedResults, display, getTrendsColor, getTrendsHidden, getLabel, showMultipleYAxes, quillLegendEnabled]
)
const chartConfig: TimeSeriesLineChartConfig = useMemo(
diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts
index 5cfda0009e2e..b42bf5cfd2c1 100644
--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts
+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/stickinessChartTransforms.ts
@@ -33,6 +33,9 @@ export interface BuildStickinessSeriesOpts<R extends StickinessResultLike, M = u
getColor: (r: R, index: number) => string
getHidden?: (r: R, index: number) => boolean
buildMeta?: (r: R, index: number) => M
+ // Resolves the legend/series label (custom name + breakdown formatting). Hosts that lack the
+ // breakdown/cohort deps (e.g. MCP) omit it and fall back to the raw humanized event name.
+ getLabel?: (r: R) => string
}
/** Convert raw counts to percentages of `count`. Mirrors the legacy `showPercentView`
@@ -57,7 +60,7 @@ export function buildStickinessMainSeries<R extends StickinessResultLike, M = un
const color = r.compare_label === 'previous' ? dimHexColor(baseColor, COMPARE_PREVIOUS_DIM_OPACITY) : baseColor
return {
key: String(r.id),
- label: humanizeSeriesLabel(r.label),
+ label: opts.getLabel ? opts.getLabel(r) : humanizeSeriesLabel(r.label),
data: toPercentData(r.data, r.count),
color,
yAxisId,
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
index 05f46897f296..75357d3a0d70 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
@@ -33,6 +33,7 @@ import { ChartDisplayType } from '~/types'
import { AnnotationsLayer } from '../shared/AnnotationsLayer'
import { makeChartErrorHandler } from '../shared/chartErrorHandler'
+import { getTrendsSeriesDisplayLabel } from '../shared/getTrendsSeriesDisplayLabel'
import { goalLinesToReferenceLines } from '../shared/goalLinesAdapter'
import { handleTrendsChartClick, type TrendsChartClickDeps } from '../shared/handleTrendsChartClick'
import { TrendsAlertOverlays } from '../shared/TrendsAlertOverlays'
@@ -150,6 +151,16 @@ export function TrendsBarChart({
[stackBreakdowns, breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay]
)
+ const getLabel = useCallback(
+ (r: IndexedTrendResult): string =>
+ getTrendsSeriesDisplayLabel(r, {
+ breakdownFilter,
+ cohorts: allCohorts?.results,
+ formatPropertyValueForDisplay,
+ }),
+ [breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay]
+ )
+
const { series, labels, displayLabels } = useMemo(() => {
if (isAggregated) {
return buildTrendsBarAggregatedSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {
@@ -165,6 +176,7 @@ export function TrendsBarChart({
// With the quill legend on, hidden series stay listed (dimmed) and are excluded via
// config.legend.hiddenKeys instead of being dropped here, so the legend can restore them.
getHidden: quillLegendEnabled ? undefined : getTrendsHidden,
+ getLabel,
buildMeta: buildTrendsSeriesMeta,
showMultipleYAxes: applyMultipleYAxes,
})
@@ -181,6 +193,7 @@ export function TrendsBarChart({
currentPeriodResult?.labels,
stackBreakdowns,
getAggregatedDisplayLabel,
+ getLabel,
applyMultipleYAxes,
quillLegendEnabled,
])
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.ts
index ab9f136dca6a..738fe405d13d 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/getAggregatedDisplayLabel.ts
@@ -5,6 +5,8 @@ import { FormatPropertyValueForDisplayFunction } from '~/models/propertyDefiniti
import { BreakdownFilter } from '~/queries/schema/schema-general'
import { CohortType } from '~/types'
+import { humanizeSeriesLabel } from '../shared/humanizeSeriesLabel'
+
export interface AggregatedDisplayLabelDeps {
stackBreakdowns: boolean
breakdownFilter: BreakdownFilter | null | undefined
@@ -16,7 +18,7 @@ export interface AggregatedDisplayLabelDeps {
export function getAggregatedDisplayLabel(r: IndexedTrendResult, deps: AggregatedDisplayLabelDeps): string {
if (deps.stackBreakdowns) {
// Breakdown values within the band are distinguished by color and the tooltip.
- return getDisplayNameFromEntityFilter(r.action) ?? r.label ?? ''
+ return getDisplayNameFromEntityFilter(r.action) ?? humanizeSeriesLabel(r.label)
}
if (r.breakdown_value != null) {
return formatBreakdownLabel(
@@ -31,5 +33,5 @@ export function getAggregatedDisplayLabel(r: IndexedTrendResult, deps: Aggregate
// Custom name wins over the event name, matching the legacy LineGraph y-axis. Series sharing
// an event are differentiated only by their custom name, so falling back to the event name
// would collapse them all onto the same label.
- return getDisplayNameFromEntityFilter(r.action) ?? r.label ?? ''
+ return getDisplayNameFromEntityFilter(r.action) ?? humanizeSeriesLabel(r.label)
}
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
index a32391a5804b..dd0be2439d4e 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
@@ -27,6 +27,9 @@ export interface BuildTrendsBarSeriesOpts<R extends TrendsBarResultLike, M = unk
getColor: (r: R, index: number) => string
getHidden?: (r: R, index: number) => boolean
buildMeta?: (r: R, index: number) => M
+ // Resolves the legend/series label (custom name + breakdown formatting). Hosts that lack the
+ // breakdown/cohort deps (e.g. MCP) omit it and fall back to the raw humanized event name.
+ getLabel?: (r: R) => string
// Scale each series past the first against its own y-axis. Grouped (unstacked) bars only —
// stacked layouts must share one axis, so the adapter never sets this for them.
showMultipleYAxes?: boolean
@@ -63,7 +66,7 @@ function buildMainTrendsBarSeries<R extends TrendsBarResultLike, M = unknown>(
const yAxisId = opts.showMultipleYAxes && index > 0 ? `y${index}` : DEFAULT_Y_AXIS_ID
return {
key: String(r.id),
- label: humanizeSeriesLabel(r.label),
+ label: opts.getLabel ? opts.getLabel(r) : humanizeSeriesLabel(r.label),
data,
color,
meta,
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
index eaa519da5480..c8edafc0dd1d 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
@@ -17,13 +17,16 @@ import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
import type { IndexedTrendResult } from 'scenes/trends/types'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+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 { ChartDisplayType } from '~/types'
import { AnnotationsLayer } from '../shared/AnnotationsLayer'
import { makeChartErrorHandler } from '../shared/chartErrorHandler'
+import { getTrendsSeriesDisplayLabel } from '../shared/getTrendsSeriesDisplayLabel'
import { handleTrendsChartClick } from '../shared/handleTrendsChartClick'
import { TrendsAlertOverlays } from '../shared/TrendsAlertOverlays'
import { buildTrendsSeriesMeta, resolveGroupTypeLabel, type TrendsSeriesMeta } from '../shared/trendsSeriesMeta'
@@ -78,6 +81,18 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
} = useValues(trendsDataLogic(insightProps))
const { timezone, weekStartDay, baseCurrency } = useValues(teamLogic)
const { aggregationLabel } = useValues(groupsModel)
+ const { allCohorts } = useValues(cohortsModel)
+ const { formatPropertyValueForDisplay } = useValues(propertyDefinitionsModel)
+
+ const getLabel = useCallback(
+ (r: IndexedTrendResult): string =>
+ getTrendsSeriesDisplayLabel(r, {
+ breakdownFilter,
+ cohorts: allCohorts?.results,
+ formatPropertyValueForDisplay,
+ }),
+ [breakdownFilter, allCohorts?.results, formatPropertyValueForDisplay]
+ )
const isPercentStackView = !!showPercentStackView && !!supportsPercentStackView
const resolvedGroupTypeLabel = context?.groupTypeLabel ?? resolveGroupTypeLabel(labelGroupType, aggregationLabel)
@@ -202,6 +217,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
// With the quill legend on, hidden series are listed (dimmed) and excluded via
// config.legend.hiddenKeys instead of being dropped here, so the legend can restore them.
getHidden: quillLegendEnabled ? undefined : getTrendsHidden,
+ getLabel,
buildMeta: buildTrendsSeriesMeta,
}),
[
@@ -212,6 +228,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
isStickiness,
getTrendsColor,
getTrendsHidden,
+ getLabel,
quillLegendEnabled,
]
)
@@ -233,6 +250,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
goalLines,
incompletenessOffsetFromEnd,
getHidden: getTrendsHidden,
+ getLabel,
showConfidenceIntervals: showConfidenceIntervals ?? undefined,
confidenceLevel: confidenceLevel ?? undefined,
ciRanges,
@@ -257,6 +275,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
goalLines,
incompletenessOffsetFromEnd,
getTrendsHidden,
+ getLabel,
showConfidenceIntervals,
confidenceLevel,
showMovingAverage,
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts
index 5f4d0525bae3..29a3ef23d57a 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts
@@ -37,6 +37,9 @@ export interface BuildTrendsSeriesOpts<R extends TrendsResultLike, M = unknown>
getColor: (r: R, index: number) => string
getHidden?: (r: R, index: number) => boolean
buildMeta?: (r: R, index: number) => M
+ // Resolves the legend/series label (custom name + breakdown formatting). Hosts that lack the
+ // breakdown/cohort deps (e.g. MCP) omit it and fall back to the raw humanized event name.
+ getLabel?: (r: R) => string
}
// Shared between buildMainTrendsSeries (stroke.partial.fromIndex) and buildDerivedConfigs
@@ -65,7 +68,7 @@ export function buildMainTrendsSeries<R extends TrendsResultLike, M = unknown>(
const meta: M | undefined = opts.buildMeta ? opts.buildMeta(r, index) : undefined
return {
key: String(r.id),
- label: humanizeSeriesLabel(r.label),
+ label: opts.getLabel ? opts.getLabel(r) : humanizeSeriesLabel(r.label),
data: r.data,
color: opts.getColor(r, index),
yAxisId,
@@ -94,6 +97,7 @@ export interface BuildDerivedConfigsOpts<R extends TrendsResultLike> {
isStickiness?: boolean
incompletenessOffsetFromEnd?: number
getHidden?: (r: R) => boolean
+ getLabel?: (r: R) => string
}
export interface DerivedConfigs {
@@ -142,7 +146,7 @@ export function buildDerivedConfigs<R extends TrendsResultLike>(
trendLines.push({
seriesKey: movingAverageKey(String(r.id)),
kind: 'linear',
- label: `${humanizeSeriesLabel(r.label)} (Moving avg)`,
+ label: `${opts.getLabel ? opts.getLabel(r) : humanizeSeriesLabel(r.label)} (Moving avg)`,
})
}
}
@@ -186,6 +190,7 @@ export interface BuildTrendsLineTimeSeriesConfigOpts<R extends TrendsResultLike>
goalLines?: GoalLineLike[] | null
incompletenessOffsetFromEnd?: number
getHidden?: (r: R) => boolean
+ getLabel?: (r: R) => string
showConfidenceIntervals?: boolean
confidenceLevel?: number
@@ -219,6 +224,7 @@ export function buildTrendsLineTimeSeriesConfig<R extends TrendsResultLike>(
isStickiness: opts.isStickiness,
incompletenessOffsetFromEnd: opts.incompletenessOffsetFromEnd,
getHidden: opts.getHidden,
+ getLabel: opts.getLabel,
})
return {
xAxis: {
diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.ts
index a521f716b34e..a1f3b2551ffe 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/trendsPieTransforms.ts
@@ -2,6 +2,7 @@ import type { Series } from '@posthog/quill-charts'
import type { IndexedTrendResult } from 'scenes/trends/types'
+import { humanizeSeriesLabel } from '../shared/humanizeSeriesLabel'
import type { TrendsSeriesMeta } from '../shared/trendsSeriesMeta'
export interface BuildTrendsPieSeriesOpts<R> {
@@ -10,7 +11,7 @@ export interface BuildTrendsPieSeriesOpts<R> {
/** True when the result should be excluded from rendering. */
getHidden?: (r: R, index: number) => boolean
/** Optional label override per result — used to format breakdown values. */
- getLabel?: (r: R, index: number) => string
+ getLabel?: (r: R) => string
}
/** Maps the kea-side `IndexedTrendResult` list to hog-charts `Series<TrendsSeriesMeta>[]`,
@@ -24,7 +25,7 @@ export function buildTrendsPieSeries<R extends IndexedTrendResult>(
): Series<TrendsSeriesMeta>[] {
return results.map((r, index) => {
const excluded = opts.getHidden ? opts.getHidden(r, index) : false
- const label = opts.getLabel ? opts.getLabel(r, index) : (r.label ?? '')
+ const label = opts.getLabel ? opts.getLabel(r) : humanizeSeriesLabel(r.label)
return {
// Match the line/bar adapters — keying by `${r.id}` lets the click handler resolve
// back to the source IndexedTrendResult without stashing it on meta.
diff --git a/products/product_analytics/frontend/insights/trends/shared/buildBaseLegendConfig.ts b/products/product_analytics/frontend/insights/trends/shared/buildBaseLegendConfig.ts
index 869332f04f22..c19a7c73ee02 100644
--- a/products/product_analytics/frontend/insights/trends/shared/buildBaseLegendConfig.ts
+++ b/products/product_analytics/frontend/insights/trends/shared/buildBaseLegendConfig.ts
@@ -16,7 +16,7 @@ export function buildBaseLegendConfig({
}): ChartLegendConfig {
return {
show,
- position: (legendPosition ?? 'bottom') as ChartLegendConfig['position'],
+ position: (legendPosition ?? 'right') as ChartLegendConfig['position'],
interactive: canEditInsight && !inSharedMode,
}
}
diff --git a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts
new file mode 100644
index 000000000000..47c955ebbf1b
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.test.ts
@@ -0,0 +1,46 @@
+import type { IndexedTrendResult } from 'scenes/trends/types'
+
+import { getTrendsSeriesDisplayLabel, type TrendsSeriesLabelDeps } from './getTrendsSeriesDisplayLabel'
+
+const NO_BREAKDOWN_DEPS: TrendsSeriesLabelDeps = {
+ breakdownFilter: null,
+ cohorts: undefined,
+ formatPropertyValueForDisplay: undefined,
+}
+
+const makeResult = (overrides: Partial<IndexedTrendResult>): IndexedTrendResult =>
+ ({ id: 0, label: '$pageview', data: [], ...overrides }) as IndexedTrendResult
+
+describe('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'],
+ ['uses the action name when not a built-in event', { action: { name: 'purchase' } }, 'purchase'],
+ [
+ 'falls back to the humanized label when there is no action (formula row)',
+ { action: null, label: 'A + B' },
+ 'A + B',
+ ],
+ ])('%s', (_name, overrides, expected) => {
+ expect(
+ getTrendsSeriesDisplayLabel(makeResult(overrides as Partial<IndexedTrendResult>), NO_BREAKDOWN_DEPS)
+ ).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.
+ const result = makeResult({
+ action: { custom_name: 'Signups' } as IndexedTrendResult['action'],
+ breakdown_value: 'Chrome',
+ })
+ const deps: TrendsSeriesLabelDeps = {
+ breakdownFilter: { breakdown_type: 'event', breakdown: '$browser' },
+ cohorts: undefined,
+ formatPropertyValueForDisplay: undefined,
+ }
+ expect(getTrendsSeriesDisplayLabel(result, deps)).toBe('Chrome')
+ })
+})
diff --git a/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts
new file mode 100644
index 000000000000..9e7f0cf78c2b
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/shared/getTrendsSeriesDisplayLabel.ts
@@ -0,0 +1,32 @@
+import { formatBreakdownLabel, getDisplayNameFromEntityFilter } from 'scenes/insights/utils'
+import type { IndexedTrendResult } from 'scenes/trends/types'
+
+import type { FormatPropertyValueForDisplayFunction } from '~/models/propertyDefinitionsModel'
+import type { BreakdownFilter } from '~/queries/schema/schema-general'
+import type { CohortType } from '~/types'
+
+import { humanizeSeriesLabel } from './humanizeSeriesLabel'
+
+export interface TrendsSeriesLabelDeps {
+ breakdownFilter: BreakdownFilter | null | undefined
+ cohorts: CohortType[] | undefined
+ formatPropertyValueForDisplay: FormatPropertyValueForDisplayFunction | undefined
+}
+
+/** 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 {
+ if (r.breakdown_value != null) {
+ return formatBreakdownLabel(
+ r.breakdown_value,
+ deps.breakdownFilter,
+ deps.cohorts,
+ deps.formatPropertyValueForDisplay,
+ undefined,
+ r.label
+ )
+ }
+ return getDisplayNameFromEntityFilter(r.action) ?? humanizeSeriesLabel(r.label)
+}
diff --git a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx
index c7dd1b492140..245d2715e2fe 100644
--- a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx
+++ b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx
@@ -50,7 +50,7 @@ export function useInsightsLegendConfig({
const showContextMenu = legendInteractive && legendSeriesIsolationMenuEligible
return {
show: !!showLegend,
- position: (legendPosition as ChartLegendConfig['position']) ?? 'bottom',
+ position: (legendPosition as ChartLegendConfig['position']) ?? 'right',
interactive: legendInteractive,
hiddenKeys,
onToggleSeries: (key: string) => {