: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): make trends in-chart legend position configurable (#64839)
Sam Penningtonb50c935f1681
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsxindex ea2beda72dbd..055d735853a8 100644--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx@@ -23,6 +23,7 @@ import { axisLabel } from 'scenes/insights/aggregationAxisFormat'import { AxisLabelsFilter } from 'scenes/insights/EditorFilters/AxisLabelsFilter'import { HideIncompleteConversionWindowPeriodsFilter } from 'scenes/insights/EditorFilters/HideIncompleteConversionWindowPeriodsFilter'import { HideWeekendsFilter } from 'scenes/insights/EditorFilters/HideWeekendsFilter'+import { LegendPositionFilter } from 'scenes/insights/EditorFilters/LegendPositionFilter'import { LifecyclePercentagesFilter } from 'scenes/insights/EditorFilters/LifecyclePercentagesFilter'import { LifecycleStackingFilter } from 'scenes/insights/EditorFilters/LifecycleStackingFilter'import {@@ -120,6 +121,7 @@ export function InsightDisplayConfig(): JSX.Element {)const { featureFlags } = useValues(featureFlagLogic)const hideWeekendsEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HIDE_WEEKENDS]+ const quillLegendEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND]// The slope graph shows the first vs last interval, so it keeps the group-by interval picker but// drops the options that need the points between them (compare, smoothing, multiple axes,// alert/annotation overlays, statistical analysis).@@ -251,6 +253,11 @@ export function InsightDisplayConfig(): JSX.Element {...(hasLegend || showFunnelLegendConfig? [{ label: () => <ShowLegendFilter /> }]: []),+ // The in-chart quill legend supports placement; the legacy side+ // legend doesn't, so only offer it for trends line/area/cumulative.+ ...(quillLegendEnabled && isTrends && isLineDisplay && showLegend+ ? [{ label: () => <LegendPositionFilter /> }]+ : []),...(display === ChartDisplayType.ActionsPie? [{ label: () => <ShowPieTotalFilter /> }]: []),diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 866ce23ba2e1..417063116210 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -43606,6 +43606,12 @@"default": false,"type": "boolean"},+ "legendPosition": {+ "default": "bottom",+ "description": "Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.",+ "enum": ["top", "bottom", "left", "right"],+ "type": "string"+ },"metricChangeDecreaseColor": {"description": "Metric display: change pill color when the metric decreased. Defaults to red.","type": "string"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 8e8fc9fecaf5..0e6933157537 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -1425,6 +1425,9 @@ export type TrendsFilter = {display?: TrendsFilterLegacy['display']/** @default false */showLegend?: TrendsFilterLegacy['show_legend']+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.+ * @default bottom */+ legendPosition?: 'top' | 'bottom' | 'left' | 'right'/** @default false */showAlertThresholdLines?: booleanbreakdown_histogram_bin_count?: TrendsFilterLegacy['breakdown_histogram_bin_count'] // TODO: fully move into BreakdownFilter@@ -1532,6 +1535,7 @@ export const TRENDS_FILTER_PROPERTIES = new Set<keyof TrendsFilter>(['formula','display','showLegend',+ 'legendPosition','breakdown_histogram_bin_count','aggregationAxisFormat','aggregationAxisPrefix',diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.tsindex 6fd69f0b2fdb..da4303e337bd 100644--- a/frontend/src/queries/utils.ts+++ b/frontend/src/queries/utils.ts@@ -574,6 +574,15 @@ export const getShowLegend = (query: InsightQueryNode): boolean | undefined => {return undefined}+// Widened to `string` (not the literal union) to match getYAxisScaleType — kea-typegen can't+// serialize an inline string-literal union and emits a broken type; consumers narrow as needed.+export const getLegendPosition = (query: InsightQueryNode): string | undefined => {+ if (isTrendsQuery(query)) {+ return query.trendsFilter?.legendPosition+ }+ return undefined+}+export const getShowAlertThresholdLines = (query: InsightQueryNode): boolean | undefined => {if (isTrendsQuery(query)) {return query.trendsFilter?.showAlertThresholdLinesdiff --git a/frontend/src/scenes/insights/EditorFilters/LegendPositionFilter.tsx b/frontend/src/scenes/insights/EditorFilters/LegendPositionFilter.tsxnew file mode 100644index 000000000000..73023497cadd--- /dev/null+++ b/frontend/src/scenes/insights/EditorFilters/LegendPositionFilter.tsx@@ -0,0 +1,36 @@+import { useActions, useValues } from 'kea'++import { LemonSelect } from '@posthog/lemon-ui'++import { insightLogic } from 'scenes/insights/insightLogic'++import type { TrendsFilter } from '~/queries/schema/schema-general'++import { insightVizDataLogic } from '../insightVizDataLogic'++type LegendPosition = NonNullable<TrendsFilter['legendPosition']>++const OPTIONS: { value: LegendPosition; label: string }[] = [+ { value: 'bottom', label: 'Bottom' },+ { value: 'top', label: 'Top' },+ { value: 'left', label: 'Left' },+ { value: 'right', label: 'Right' },+]++export function LegendPositionFilter(): JSX.Element {+ const { insightProps } = useValues(insightLogic)+ const { legendPosition } = useValues(insightVizDataLogic(insightProps))+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))++ return (+ <div className="flex items-center justify-between gap-2 p-1 px-2">+ <span className="font-normal">Legend position</span>+ <LemonSelect+ size="small"+ value={legendPosition ?? 'bottom'}+ options={OPTIONS}+ onChange={(value) => updateInsightFilter({ legendPosition: value as LegendPosition })}+ />+ </div>+ )+}diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.tsindex 8c1c51ab654c..340837d0a82e 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts@@ -68,6 +68,7 @@ import {getFormulas,getGoalLines,getInterval,+ getLegendPosition,getResultCustomizationBy,getSeries,getShowAlertThresholdLines,@@ -288,6 +289,7 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([showAlertThresholdLines: [(s) => [s.querySource], (q) => (q ? getShowAlertThresholdLines(q) : null)],showAnnotations: [(s) => [s.querySource], (q) => (q ? getShowAnnotations(q) : null)],showLegend: [(s) => [s.querySource], (q) => (q ? getShowLegend(q) : null)],+ legendPosition: [(s) => [s.querySource], (q) => (q ? getLegendPosition(q) : null)],showValuesOnSeries: [(s) => [s.querySource], (q) => (q ? getShowValuesOnSeries(q) : null)],showPercentagesOnSeries: [(s) => [s.querySource], (q) => (q ? getShowPercentagesOnSeries(q) : null)],showLabelOnSeries: [(s) => [s.querySource], (q) => (q ? getShowLabelsOnSeries(q) : null)],diff --git a/frontend/src/scenes/trends/trendsDataLogic.ts b/frontend/src/scenes/trends/trendsDataLogic.tsindex 0072d42928bf..a0a8664e0d52 100644--- a/frontend/src/scenes/trends/trendsDataLogic.ts+++ b/frontend/src/scenes/trends/trendsDataLogic.ts@@ -105,6 +105,7 @@ export const trendsDataLogic = kea<trendsDataLogicType>(['isBreakdownSeries','hasLegend','showLegend',+ 'legendPosition','showAnnotations','vizSpecificOptions','yAxisScaleType',diff --git a/posthog/schema.py b/posthog/schema.pyindex 4b49000be899..09296bdf8d20 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -138,6 +138,7 @@ from posthog.schema_enums import (Key10 as Key10,Kind as Kind,Kind1 as Kind1,+ LegendPosition as LegendPosition,LifecycleToggle as LifecycleToggle,LimitContext as LimitContext,LinkedinAdsDefaultSources as LinkedinAdsDefaultSources,@@ -7777,6 +7778,10 @@ class TrendsFilter(BaseModel):goalLines: list[GoalLine] | None = Field(default=None, description="Goal Lines")hiddenLegendIndexes: list[int] | None = NonehideWeekends: bool | None = False+ legendPosition: LegendPosition | None = Field(+ default=LegendPosition.BOTTOM,+ description=("Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend."),+ )metricChangeDecreaseColor: str | None = Field(default=None,description=("Metric display: change pill color when the metric decreased. Defaults to red."),diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex f33d8a96ab06..70c89718567a 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3280,6 +3280,13 @@ class DetailedResultsAggregationType(StrEnum):MEDIAN = "median"+class LegendPosition(StrEnum):+ TOP = "top"+ BOTTOM = "bottom"+ LEFT = "left"+ RIGHT = "right"++class UsageMetricDisplay(StrEnum):NUMBER = "number"SPARKLINE = "sparkline"diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex f97a4abf3eb4..068db8d11c2d 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -2056,6 +2056,15 @@ export interface GoalLineApi {value: number}+export type LegendPositionApi = (typeof LegendPositionApi)[keyof typeof LegendPositionApi]++export const LegendPositionApi = {+ Top: 'top',+ Bottom: 'bottom',+ Left: 'left',+ Right: 'right',+} as const+export type MetricSummaryApi = (typeof MetricSummaryApi)[keyof typeof MetricSummaryApi]export const MetricSummaryApi = {@@ -2149,6 +2158,8 @@ export interface TrendsFilterApi {goalLines?: GoalLineApi[] | nullhiddenLegendIndexes?: number[] | nullhideWeekends?: boolean | null+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | null/** Metric display: change pill color when the metric decreased. Defaults to red. */metricChangeDecreaseColor?: string | null/** Metric display: change pill color when the metric increased. Defaults to green. */diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex a5480b836761..4ec09a2461ef 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -1481,6 +1481,15 @@ export interface GoalLineApi {value: number}+export type LegendPositionApi = (typeof LegendPositionApi)[keyof typeof LegendPositionApi]++export const LegendPositionApi = {+ Top: 'top',+ Bottom: 'bottom',+ Left: 'left',+ Right: 'right',+} as const+export type MetricSummaryApi = (typeof MetricSummaryApi)[keyof typeof MetricSummaryApi]export const MetricSummaryApi = {@@ -1574,6 +1583,8 @@ export interface TrendsFilterApi {goalLines?: GoalLineApi[] | nullhiddenLegendIndexes?: number[] | nullhideWeekends?: boolean | null+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPositionApi | null/** Metric display: change pill color when the metric decreased. Defaults to red. */metricChangeDecreaseColor?: string | null/** Metric display: change pill color when the metric increased. Defaults to green. */diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsxindex 6d4e81b08dcb..470a5fcde0fb 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx@@ -875,5 +875,28 @@ describe('TrendsLineChart', () => {expect(legendEl.textContent).toContain('Napped')expect(legendEl.querySelector('button')).not.toBeInTheDocument()})++ it.each(['left', 'right'] as const)(+ 'lays the legend out vertically when legendPosition is %s',+ async (position) => {+ const { container } = renderInsight({+ query: buildTrendsQuery({+ series: [+ { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },+ { kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' },+ ],+ trendsFilter: { showLegend: true, legendPosition: position },+ }),+ featureFlags: quillLegendFlag,+ })++ await waitFor(() => {+ expect(screen.getByRole('img', { name: /chart with 2 data series/i })).toBeInTheDocument()+ })++ const legendEl = getInChartLegend(container)+ expect(legendEl.className).toContain('flex-col')+ }+ )})})diff --git a/products/product_analytics/frontend/insights/trends/shared/useTrendsLegendConfig.tsx b/products/product_analytics/frontend/insights/trends/shared/useTrendsLegendConfig.tsxindex c49dcbfa4ce7..9797ef7563bb 100644--- a/products/product_analytics/frontend/insights/trends/shared/useTrendsLegendConfig.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/useTrendsLegendConfig.tsx@@ -29,9 +29,8 @@ export function useTrendsLegendConfig({const { featureFlags } = useValues(featureFlagLogic)const quillLegendEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_LEGEND]const { canEditInsight } = useValues(insightLogic)- const { indexedResults, getTrendsHidden, showLegend, legendSeriesIsolationMenuEligible } = useValues(- trendsDataLogic(insightProps)- )+ const { indexedResults, getTrendsHidden, showLegend, legendPosition, legendSeriesIsolationMenuEligible } =+ useValues(trendsDataLogic(insightProps))const { toggleResultHidden } = useActions(trendsDataLogic(insightProps))const resultById = useMemo(() => {@@ -50,6 +49,7 @@ export function useTrendsLegendConfig({const showContextMenu = legendInteractive && legendSeriesIsolationMenuEligiblereturn {show: !!showLegend,+ position: (legendPosition as ChartLegendConfig['position']) ?? 'bottom',interactive: legendInteractive,hiddenKeys,onToggleSeries: (key: string) => {@@ -77,6 +77,7 @@ export function useTrendsLegendConfig({indexedResults,getTrendsHidden,showLegend,+ legendPosition,legendInteractive,legendSeriesIsolationMenuEligible,resultById,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7546286495ea..c1b44456acca 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -2299,6 +2299,16 @@ export namespace Schemas {value: number;}+ export type LegendPosition = typeof LegendPosition[keyof typeof LegendPosition];+++ export const LegendPosition = {+ Top: 'top',+ Bottom: 'bottom',+ Left: 'left',+ Right: 'right',+ } as const;+export type MetricSummary = typeof MetricSummary[keyof typeof MetricSummary];@@ -2393,6 +2403,8 @@ export namespace Schemas {goalLines?: GoalLine[] | null;hiddenLegendIndexes?: number[] | null;hideWeekends?: boolean | null;+ /** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend. */+ legendPosition?: LegendPosition | null;/** Metric display: change pill color when the metric decreased. Defaults to red. */metricChangeDecreaseColor?: string | null;/** Metric display: change pill color when the metric increased. Defaults to green. */