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): quill legend and position option for SQL pie charts (#87870)

Sam Penningtonf8ec2dbc3661
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b94b9bef2de6..ac7be593d607 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3065,17 +3065,21 @@ snapshots:
insights-sqlbargraph--stacked-bar-with-negative-values--light:
hash: v1.k794b7964.e9f32e35e60194c76df1aad0e7963ca99bc76d2b6099437c5e679c4959feb976.3DeROLuvQPwEHmWPIxoY7SxfXAcAgX6gufInnDLnBh0
insights-sqlpiegraph--breakdown-colors--dark:
- hash: v1.k794b7964.459b2f2dad813b806560c40f292c41503482dcc864756aa5c27e936ef6ad5890.35VUrVQBDx9LxDWhN1L1896BV62m-OhK3d4ujQHrU5o
+ hash: v1.k794b7964.01928cb0ffb1554a01ffae8f214773557e22647fea676e40007a7803cec0af32.fk7qZ2CtcV_Ouq_6xOxJ7wqRdxmck-P18wvqRq1jLsc
insights-sqlpiegraph--breakdown-colors--light:
- hash: v1.k794b7964.85b6dc31bdb8ee361f89ab6c8b1df6c435e3e4b791fa982094ebd01a63b52cb7.LT735atGhIw513Hxuiqlqy2j0mRrsSlK5e__FssLlXo
+ hash: v1.k794b7964.2cdd1a0340ad18c1befb63f45f3019c9d169662d43abcf546087a6c076f04027.ZPiiGjgoY84m-UC9HiDkqnea5U12qN7NM0ijyMmK11M
insights-sqlpiegraph--default--dark:
hash: v1.k794b7964.5d9407311260cf6d60e52217801013baf5523971043d3a384399661606956094.gY3eS5hEKko3Uw025q_K8VD0OY4XUOo6iNkvdlzwrnA
insights-sqlpiegraph--default--light:
hash: v1.k794b7964.cb8ad5af06a0440258a2aad8b7a5531e83bed58ee3e1dfe019e9fcb549569b96.n6v4Nqqfp1KvW3ouAH4u2gEwzMI3eDb3hA3y2hHbBxY
+ insights-sqlpiegraph--legend-at-bottom--dark:
+ hash: v1.k794b7964.c47d48ad6a252d8a5dfc135b3d269bc028523df242a7b79c5b96d9d111ae0376._DhCXEiBO9wMl5fx3iWvB8BVIaxe19bUBzUQb55bkAo
+ insights-sqlpiegraph--legend-at-bottom--light:
+ hash: v1.k794b7964.edbf042650a6322573f4e64763cd4409162aca5fce5a35b2a51689d0b45a3867.KCSWIbrsWY4EZKnAeZHXdZXnZLEs0_oT1CnSBS-PmQE
insights-sqlpiegraph--with-legend--dark:
- hash: v1.k794b7964.41dfc4667fa9189fe499758412992668a572450ccd8efd81ebc5da0721e0a13f.IxIdKXrKk6F9AAvA7ZrkyjwOwobtpWR6PuJgvv_oSpo
+ hash: v1.k794b7964.d15af2bc969e9e442db3d5520d7b4c26a29f82dd001f9a3656da9cb838cd904e.HU5scx_5_NP2zMcUStE930Oaa1UgjhjHkEOUjAZ-u3w
insights-sqlpiegraph--with-legend--light:
- hash: v1.k794b7964.334268e3aeef84633d540830a5e1394e55a407118286053925f00e6eb378d806.zeqHqcf7h1Nihj7cEGiafCUbASLAmCZ28Z1xngTBl-0
+ hash: v1.k794b7964.e03eea04875a2046ced662098279559de6cfedb493840f3badf759e1a61a329b.Zkyv5NwjRftokqgfRfDPoMH62IXHvXLwEiQNGVkkoug
insights-sqlscattergraph--default--dark:
hash: v1.k794b7964.5ca16c3fa53c4fa08dfd7c540a2a6dda5ce63b1f9ebcb0e604a4f13e32c17af5.BC1sKBXJftn3jhHnOKFddv2XmlLtCTyZSfPw9c2yt_4
insights-sqlscattergraph--default--light:
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.test.tsx
index 1fea84c68c3d..526d5f33e761 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.test.tsx
@@ -63,7 +63,7 @@ describe('SqlBoxPlot', () => {
cleanup()
})
- it('renders grouped boxes with the standard axis defaults', async () => {
+ it('renders grouped boxes with the standard axis defaults and selected legend position', async () => {
render(
<SqlBoxPlot
rows={[
@@ -71,7 +71,7 @@ describe('SqlBoxPlot', () => {
['Mon', 'Paid', 7, 8, 9, 10, 11, 12],
]}
columns={columns}
- chartSettings={chartSettings}
+ chartSettings={{ ...chartSettings, showLegend: true, legendPosition: 'bottom' }}
analyticsKey="grouped-test"
/>
)
@@ -87,6 +87,7 @@ describe('SqlBoxPlot', () => {
config: {
showGrid: true,
showAxisLines: { x: true, y: true },
+ legend: { show: true, position: 'bottom' },
},
})
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.tsx
index 595cbb31df4b..d7f74c867ba9 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.tsx
@@ -67,7 +67,7 @@ export const SqlBoxPlot = ({
y: chartSettings.showYAxisBorder ?? true,
},
tooltip: { pinnable: true, placement: 'cursor' },
- legend: { show: chartSettings.showLegend ?? false, position: 'top' },
+ legend: { show: chartSettings.showLegend ?? false, position: chartSettings.legendPosition ?? 'top' },
}),
[chartSettings, yAxisSettings]
)
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.stories.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.stories.tsx
index d2eda91d72b3..383ae9e0f06f 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.stories.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.stories.tsx
@@ -76,6 +76,16 @@ export const WithLegend: Story = {
}),
}
+export const LegendAtBottom: Story = {
+ render: () =>
+ render({
+ xData,
+ yData: singleSeries,
+ visualizationType: ChartDisplayType.ActionsPie,
+ chartSettings: { ...baseSettings, showLegend: true, legendPosition: 'bottom' },
+ }),
+}
+
export const BreakdownColors: Story = {
render: () =>
render({
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.test.tsx
index f221667149dc..53fa026aaf13 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.test.tsx
@@ -1,6 +1,7 @@
import '@testing-library/jest-dom'
-import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { cleanup, render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'
@@ -149,13 +150,35 @@ describe('SqlPieGraph', () => {
expect(sliceLabelLines()).toEqual([])
})
- it('renders the side legend with per-slice values and shares', () => {
- // The legend is plain DOM (rendered for both responsive layouts), so it needs no canvas paint.
+ it("renders quill's legend with one row per slice", () => {
+ // The legend is plain DOM outside the canvas, so it needs no canvas paint.
render(<SqlPieGraph {...baseProps({ showLegend: true }, [60, 40, 0, 0])} />)
- expect(screen.getAllByText('alpha').length).toBeGreaterThan(0)
- expect(screen.getAllByText('60.0%').length).toBeGreaterThan(0)
- expect(screen.getAllByText('40.0%').length).toBeGreaterThan(0)
+ expect(document.querySelector('[data-attr="hog-chart-pie-legend"]')).toBeInTheDocument()
+ expect(screen.getByText('alpha')).toBeInTheDocument()
+ expect(screen.getByText('beta')).toBeInTheDocument()
+ })
+
+ it('restores all slices when the legend is hidden after isolating one', async () => {
+ const chartSettings: ChartSettings = { showLegend: true, pie: { sliceContent: 'labels', showTotal: true } }
+ const { rerender } = render(<SqlPieGraph {...baseProps(chartSettings, [60, 40, 0, 0])} />)
+ const user = userEvent.setup()
+
+ await waitForSlices()
+ await user.click(within(document.querySelector('[data-attr="hog-chart-pie-legend"]')!).getByText('alpha'))
+
+ await waitFor(() => {
+ expect(sliceLabelLines()).toEqual([['alpha']])
+ expect(screen.getByText('60')).toBeInTheDocument()
+ })
+
+ rerender(<SqlPieGraph {...baseProps({ ...chartSettings, showLegend: false }, [60, 40, 0, 0])} />)
+
+ await waitFor(() => {
+ expect(document.querySelector('[data-attr="hog-chart-pie-legend"]')).not.toBeInTheDocument()
+ expect(sliceLabelLines()).toEqual([['alpha'], ['beta']])
+ expect(screen.getByText('100')).toBeInTheDocument()
+ })
})
it('shows the empty state when there are no positive values', () => {
@@ -180,10 +203,10 @@ describe('SqlPieGraph', () => {
/>
)
- const swatchColors = Array.from(document.querySelectorAll<HTMLElement>('.LemonColorGlyph')).map(
- (el) => el.style.color
- )
- expect(screen.getAllByText('first').length).toBeGreaterThan(0)
+ const swatchColors = Array.from(
+ document.querySelectorAll<HTMLElement>('[data-attr="hog-chart-pie-legend"] span[aria-hidden="true"]')
+ ).map((el) => el.style.backgroundColor)
+ expect(screen.getByText('first')).toBeInTheDocument()
expect(swatchColors).toContain('rgb(170, 0, 0)')
expect(swatchColors).toContain('rgb(0, 170, 0)')
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx
index b97152a0994f..abf2951ce940 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx
@@ -1,11 +1,11 @@
import clsx from 'clsx'
-import { useCallback, useMemo } from 'react'
+import { useCallback, useMemo, useState } from 'react'
-import { LemonColorGlyph } from '@posthog/lemon-ui'
-import { PieChart, TooltipSurface, TooltipSwatch } from '@posthog/quill-charts'
-import type { PieChartConfig, TooltipContext } from '@posthog/quill-charts'
+import { ChartLegend, PieChart, TooltipSurface, TooltipSwatch, useChartLegend } from '@posthog/quill-charts'
+import type { ChartLegendConfig, PieChartConfig, TooltipContext } from '@posthog/quill-charts'
import { useChartTheme } from 'lib/charts/hooks'
+import { useChartLegendSeriesMenu } from 'lib/components/ChartLegendSeriesMenu/useChartLegendSeriesMenu'
import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
@@ -16,8 +16,10 @@ import { buildPieSeries, buildPieSlices, formatPieSliceCount } from './sqlPieGra
const handleChartError = makeChartErrorHandler('sql-pie-chart')
/**
- * SQL pie graph on @posthog/quill-charts' {@link PieChart}. The chart core lives in quill; the
- * aggregation total and side legend stay here as chrome.
+ * SQL pie graph on @posthog/quill-charts' {@link PieChart}. The chart core and the legend are
+ * quill's; the aggregation total stays here as chrome. The legend is driven from here rather than
+ * through `config.legend` so the total sits in the layout's chart slot, centered under the pie
+ * instead of under the pie-plus-legend pair.
*/
export const SqlPieGraph = ({
xData,
@@ -31,9 +33,17 @@ export const SqlPieGraph = ({
const slices = useMemo(() => buildPieSlices(xData, yData), [xData, yData])
const formattingSettings = yData[0]?.settings
const series = useMemo(() => buildPieSeries(slices), [slices])
- const total = useMemo(() => slices.reduce((sum, slice) => sum + slice.value, 0), [slices])
+ // Toggled-off slices aren't persisted (SQL insights have nowhere to save them), but the legend
+ // is controlled anyway so the total and the tooltip shares track the slices actually drawn.
+ const [hiddenKeys, setHiddenKeys] = useState<string[]>([])
const showLegend = chartSettings.showLegend ?? false
+ const visibleHiddenKeySet = useMemo(() => new Set(showLegend ? hiddenKeys : []), [showLegend, hiddenKeys])
+ const total = useMemo(
+ () => series.reduce((sum, s) => (visibleHiddenKeySet.has(s.key) ? sum : sum + (s.data[0] ?? 0)), 0),
+ [series, visibleHiddenKeySet]
+ )
+
// Unset means an existing chart from before the labels option — keep showing values. New pies
// are stamped with 'labels' when the type is picked (see dataVisualizationLogic).
const sliceContent = chartSettings.pie?.sliceContent ?? 'values'
@@ -47,8 +57,26 @@ export const SqlPieGraph = ({
[formattingSettings]
)
+ const legendRenderItem = useChartLegendSeriesMenu({ surface: 'sql', seriesCount: series.length })
+
+ const legendConfig: ChartLegendConfig = useMemo(
+ () => ({
+ show: showLegend,
+ position: chartSettings.legendPosition ?? 'right',
+ interactive: true,
+ hiddenKeys: showLegend ? hiddenKeys : [],
+ onToggleSeries: (key: string) =>
+ setHiddenKeys((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key])),
+ onSetHiddenSeries: setHiddenKeys,
+ renderItem: legendRenderItem,
+ }),
+ [showLegend, chartSettings.legendPosition, hiddenKeys, legendRenderItem]
+ )
+
+ const { visibleSeries, legendProps } = useChartLegend(series, theme, legendConfig)
+
// `isPercent` makes the chart render on-slice values and tooltips as a share of the total; the
- // total below the chart and the absolute legend line keep using the raw value formatter.
+ // total below the chart keeps using the raw value formatter.
// Labels sit toward the rim (on the wider part of each wedge) and skip slices under 10% so a
// long tail of thin slices doesn't pile labels up at the center.
const pieConfig: PieChartConfig = useMemo(
@@ -91,83 +119,40 @@ export const SqlPieGraph = ({
)
}
- const chart = (
- <PieChart
- series={series}
- theme={theme}
- config={pieConfig}
- tooltip={renderTooltip}
- valueFormatter={absoluteFormatter}
- dataAttr="sql-pie-chart"
- onError={handleChartError}
- />
- )
-
const totalDisplay = showPieTotal ? (
<div className="pt-4 text-center shrink-0">
<div className="text-5xl font-bold">{absoluteFormatter(total)}</div>
</div>
) : null
- const legend = showLegend ? (
- <div className="w-full xl:w-80 shrink-0 border border-border rounded bg-surface-secondary overflow-visible xl:overflow-auto">
- <div className="divide-y divide-border">
- {slices.map((slice) => {
- const percent = total > 0 ? ((slice.value / total) * 100).toFixed(1) : '0.0'
-
- return (
- <div key={slice.label} className="flex items-center justify-between gap-3 px-3 py-2 text-sm">
- <div className="flex items-center gap-2 min-w-0">
- <LemonColorGlyph color={slice.color} className="shrink-0" />
- <span className="truncate">{slice.label}</span>
- </div>
- <div className="text-right shrink-0">
- <div className="font-semibold">
- {asPercent ? `${percent}%` : absoluteFormatter(slice.value)}
- </div>
- <div className="text-xs text-secondary">
- {asPercent ? absoluteFormatter(slice.value) : `${percent}%`}
- </div>
- </div>
- </div>
- )
- })}
- </div>
- </div>
- ) : null
+ // A side legend narrows the chart column, so the total belongs inside it to stay centered under
+ // the pie. A top/bottom legend leaves the column full-width, and the total goes below both.
+ const legendAtSide = legendProps.show && (legendProps.position === 'left' || legendProps.position === 'right')
return (
<div
- className={clsx(className, 'rounded bg-surface-primary flex flex-1 p-4 gap-4', {
+ className={clsx(className, 'rounded bg-surface-primary flex flex-col flex-1 min-h-0 p-4', {
'h-[60vh]': presetChartHeight,
'h-full': !presetChartHeight,
})}
>
- {!showLegend ? (
- <div className="flex flex-1 min-h-0">
- <div className="flex flex-1 flex-col min-h-0">
- <div className="flex flex-col flex-1 min-h-[18rem]">{chart}</div>
- {totalDisplay}
- </div>
+ <ChartLegend {...legendProps} legendDataAttr="hog-chart-pie-legend">
+ {/* min-h-0, not a fixed floor: in a short panel the pie has to shrink, or its box
+ runs over the legend and the total below it. */}
+ <div className="flex flex-col flex-1 min-h-0">
+ <PieChart
+ series={visibleSeries}
+ theme={theme}
+ config={pieConfig}
+ tooltip={renderTooltip}
+ valueFormatter={absoluteFormatter}
+ dataAttr="sql-pie-chart"
+ onError={handleChartError}
+ />
</div>
- ) : (
- <>
- <div className="flex flex-col gap-4 w-full xl:hidden">
- <div className="flex flex-col">
- <div className="flex flex-col h-[18rem]">{chart}</div>
- {totalDisplay}
- </div>
- {legend}
- </div>
- <div className="hidden xl:flex flex-1 gap-4 min-h-0">
- <div className="flex flex-1 flex-col min-h-0">
- <div className="flex flex-col flex-1 min-h-[18rem]">{chart}</div>
- {totalDisplay}
- </div>
- {legend}
- </div>
- </>
- )}
+ {legendAtSide && totalDisplay}
+ </ChartLegend>
+ {!legendAtSide && totalDisplay}
</div>
)
}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
index e2c97f4937fb..5ff7b819facd 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
@@ -718,6 +718,18 @@ describe('sqlLineGraphAdapter', () => {
expect(config.legend).toEqual({ show: expected, position: 'top', interactive: true })
})
+ it.each([
+ ['defaults to the top', undefined, 'top'],
+ ['follows legendPosition', 'bottom', 'bottom'],
+ ] as const)('%s for the legend position', (_name, legendPosition, expected) => {
+ const config = buildLineChartConfig({
+ xData: dateXData,
+ chartSettings: { showLegend: true, legendPosition },
+ timezone: 'UTC',
+ })
+ expect(config.legend?.position).toBe(expected)
+ })
+
it('forwards legendRenderItem, which carries the row right-click menu', () => {
const legendRenderItem = jest.fn()
const config = buildLineChartConfig({
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
index 2ef12ac55b8e..ddaaf116e50f 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
@@ -377,7 +377,12 @@ function buildLegendConfig(
): ChartLegendConfig {
// No `hiddenKeys`, so the legend is uncontrolled: quill owns which series are toggled off, and
// isolating a series works without SQL charts having to persist anything.
- return { show: chartSettings.showLegend ?? false, position: 'top', interactive: true, renderItem }
+ return {
+ show: chartSettings.showLegend ?? false,
+ position: chartSettings.legendPosition ?? 'top',
+ interactive: true,
+ renderItem,
+ }
}
/** The X/Y axis-border toggles map onto quill's per-edge axis lines — undefined when both are on
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.ts
index 0b79d7848b5c..d7f2d266981c 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.ts
@@ -102,7 +102,11 @@ export function buildScatterConfig({
},
showGrid: yAxisSettings?.showGridLines ?? true,
showBestFit: chartSettings.scatter?.showBestFit ?? false,
- legend: { show: chartSettings.showLegend ?? false, position: 'top', interactive: true },
+ legend: {
+ show: chartSettings.showLegend ?? false,
+ position: chartSettings.legendPosition ?? 'top',
+ interactive: true,
+ },
tooltip: {
xFormatter: (value: number): string => value.toLocaleString(),
yFormatter: (value: number, point): string => formatSqlSeriesValue(value, point.meta?.settings),
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
index 63b2ebf93a24..cb587e1e9fa9 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
@@ -30,6 +30,13 @@ const PIE_VALUE_DISPLAY_OPTIONS: { value: 'absolute' | 'percentage'; label: stri
{ value: 'percentage', label: 'Percentage' },
]
+const LEGEND_POSITION_OPTIONS: { value: 'top' | 'bottom' | 'left' | 'right'; label: string }[] = [
+ { value: 'top', label: 'Top' },
+ { value: 'bottom', label: 'Bottom' },
+ { value: 'left', label: 'Left' },
+ { value: 'right', label: 'Right' },
+]
+
const LINE_STYLE_OPTIONS: { value: 'smooth' | 'linear'; label: string }[] = [
{ value: 'smooth', label: 'Smooth' },
{ value: 'linear', label: 'Straight' },
@@ -142,6 +149,21 @@ export const DisplayTab = (): JSX.Element => {
updateChartSettings({ showLegend: value })
}}
/>
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Legend position</LemonLabel>
+ <LemonSelect
+ className="w-full"
+ value={chartSettings.legendPosition ?? (isPieChart ? 'right' : 'top')}
+ options={LEGEND_POSITION_OPTIONS}
+ disabledReason={
+ chartSettings.showLegend
+ ? undefined
+ : 'Turn the legend on to set its position'
+ }
+ onChange={(value) => updateChartSettings({ legendPosition: value })}
+ fullWidth
+ />
+ </div>
{isBoxPlot && (
<LemonSwitch
className="flex-1 w-full"
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 320f22964786..a62ae003f775 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -16485,6 +16485,11 @@
"leftYAxisSettings": {
"$ref": "#/definitions/YAxisSettings"
},
+ "legendPosition": {
+ "description": "Where the legend sits relative to the chart. Unset falls back per chart type: right for pie, top for the rest.",
+ "enum": ["top", "bottom", "left", "right"],
+ "type": "string"
+ },
"pie": {
"$ref": "#/definitions/PieChartSettings"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 5620ca0c4703..27b05bfaea1c 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1400,6 +1400,8 @@ export interface ChartSettings {
showYAxisBorder?: boolean
showLegend?: boolean
showAnnotations?: boolean
+ /** Where the legend sits relative to the chart. Unset falls back per chart type: right for pie, top for the rest. */
+ legendPosition?: 'top' | 'bottom' | 'left' | 'right'
showValuesOnSeries?: boolean
// Deprecated: superseded by `pie.showTotal`. Retained so pre-existing pie-chart insights still
// validate (ChartSettings is `extra="forbid"`). Read as a fallback in the pie chart components.
diff --git a/posthog/schema.py b/posthog/schema.py
index ca6d1c47e2da..f9dd66592fa2 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -15566,6 +15566,13 @@ class ChartSettings(BaseModel):
goalLines: list[GoalLine] | None = None
heatmap: HeatmapSettings | None = None
leftYAxisSettings: YAxisSettings | None = None
+ legendPosition: LegendPosition | None = Field(
+ default=None,
+ description=(
+ "Where the legend sits relative to the chart. Unset falls back per chart"
+ " type: right for pie, top for the rest."
+ ),
+ )
pie: PieChartSettings | None = None
resultCustomizations: dict[str, ResultCustomizationByValue] | None = Field(
default=None,
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 94e8500cdc82..18fc4cd13853 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -695,6 +695,13 @@ class ChartDisplayType(StrEnum):
SCATTER_PLOT = "ScatterPlot"
+class LegendPosition(StrEnum):
+ TOP = "top"
+ BOTTOM = "bottom"
+ LEFT = "left"
+ RIGHT = "right"
+
+
class Curve(StrEnum):
LINEAR = "linear"
SMOOTH = "smooth"
@@ -2786,13 +2793,6 @@ class FunnelVizType(StrEnum):
FLOW = "flow"
-class LegendPosition(StrEnum):
- TOP = "top"
- BOTTOM = "bottom"
- LEFT = "left"
- RIGHT = "right"
-
-
class Position(StrEnum):
START = "start"
END = "end"
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 63e725c0a492..f3e51c26d4b2 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -8981,6 +8981,8 @@ export interface ChartSettingsApi {
goalLines?: GoalLineApi[] | null
heatmap?: HeatmapSettingsApi | null
leftYAxisSettings?: YAxisSettingsApi | null
+ /** Where the legend sits relative to the chart. Unset falls back per chart type: right for pie, top for the rest. */
+ legendPosition?: LegendPositionApi | null
pie?: PieChartSettingsApi | null
/** Per-breakdown-value color customizations. Keyed by the raw breakdown column value. */
resultCustomizations?: ChartSettingsApiResultCustomizations
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index f0e31e97f494..d4254e489ad1 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8036,6 +8036,8 @@ export interface ChartSettingsApi {
goalLines?: GoalLineApi[] | null
heatmap?: HeatmapSettingsApi | null
leftYAxisSettings?: YAxisSettingsApi | null
+ /** Where the legend sits relative to the chart. Unset falls back per chart type: right for pie, top for the rest. */
+ legendPosition?: LegendPositionApi | null
pie?: PieChartSettingsApi | null
/** Per-breakdown-value color customizations. Keyed by the raw breakdown column value. */
resultCustomizations?: ChartSettingsApiResultCustomizations
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e597014190b7..9ff9d70f1746 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8794,6 +8794,8 @@ export namespace Schemas {
goalLines?: GoalLine[] | null;
heatmap?: HeatmapSettings | null;
leftYAxisSettings?: YAxisSettings | null;
+ /** Where the legend sits relative to the chart. Unset falls back per chart type: right for pie, top for the rest. */
+ legendPosition?: LegendPosition | null;
pie?: PieChartSettings | null;
/** Per-breakdown-value color customizations. Keyed by the raw breakdown column value. */
resultCustomizations?: ChartSettingsResultCustomizations;