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): add a line of best fit to SQL scatter plots (#83155)

Sam Penningtonb208eddf1395
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ec2164c2e1c1..d5554e2ae07d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -20,6 +20,10 @@ snapshots:
hash: v1.k794b7964.8e7770037014d788ef5b7299b6b2f834c2afcad14dd6c6033ddd8ac885faa1c6.buSflXKIcQC5dcm7fbQWsczrZY8TleOkvO86ugYW8yw
charts-heatmap--linear-color-scale--light:
hash: v1.k794b7964.c94c02704b7f9b4972f811336d019e15b77cff047551902ca74d65c1571ea6ff.PA6k_wyPYr-SNYm1-Mv8sa0DFCLb2-8QxOVNlDn4hE8
+ charts-scatterchart--best-fit--dark:
+ hash: v1.k794b7964.16cd70cbd14b6b074187753443b03c278fe2c1232a3964fb3cecc43db143022a.cW424mhub6jtCjmXr_ka4Tpy1H103wjp5syvHYhLkGk
+ charts-scatterchart--best-fit--light:
+ hash: v1.k794b7964.512d62c420b1c1cd4859e3f5b54b3c143790ffe97dbf612a0433d176815bbb9d.SDshqmWYkWbvkPR0uVwaM-eSys8hE9549vav7A3m96w
charts-scatterchart--clusters-with-centroids--dark:
hash: v1.k794b7964.21db57f09c276546fb27d3a6ba87bdb6e91c323ea1070df94f9ab87a8c1945d3.tANHwlLV16_HsvrEm1NqaeZNbmXRJRRk1P26nJ1hH6c
charts-scatterchart--clusters-with-centroids--light:
@@ -6121,7 +6125,7 @@ snapshots:
scenes-app-experiments--experiment-stopped-with-conclusion--light:
hash: v1.k794b7964.793a4b6109b2c0ab65b07d9eaefd1c8862f12bfc7f33b2f452ad20044396b2a7.6B0Meq7yO75vBEoBmuP2dNl2oKTugzzr_IKTcJHhEi0
scenes-app-experiments--experiment-with-funnel-metric--dark:
- hash: v1.k794b7964.bd425da753ec6f788f968fb15c6a7783af3c8479103849bf3ab4fad4f4276287.KPZegtTwokdMxA6_KV2bsmFYxTZO1AYRlPZp4tZ6y7E
+ hash: v1.k794b7964.fd0d0ad7569f50079a322a8901513f854823ce694796a2a24a1e6714ac9c5902.fBtAQkm1LZ7xYp6DTXoQSDqDFjsUkxMCP-aNAZJ1Fmc
scenes-app-experiments--experiment-with-funnel-metric--light:
hash: v1.k794b7964.a608f24a82fc56569fb7029e98bab3121baa3fd6c5c63492fe9952aa6a43afc5.ZgTLiUZPjDNcaChht0ijSp2F7HoqRkdn__-6JKI7p4A
scenes-app-experiments--experiment-with-legacy-funnels-query--dark:
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.test.ts
index ac2d27baeb1a..749655f5a0c2 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.test.ts
@@ -80,12 +80,13 @@ describe('sqlScatterGraphAdapter', () => {
expect(config.xAxis).toMatchObject({ label: 'duration', scaleType: 'linear', startAtZero: false })
expect(config.yAxis).toMatchObject({ scaleType: 'linear', startAtZero: false })
+ expect(config.showBestFit).toBe(false)
})
it('applies the scatter and y-axis settings', () => {
const config = build({
xAxisLabel: 'Session duration',
- scatter: { xScale: 'logarithmic', xStartAtZero: true },
+ scatter: { xScale: 'logarithmic', xStartAtZero: true, showBestFit: true },
leftYAxisSettings: { label: 'Revenue', scale: 'logarithmic', startAtZero: true, showGridLines: false },
})
@@ -96,6 +97,7 @@ describe('sqlScatterGraphAdapter', () => {
})
expect(config.yAxis).toMatchObject({ label: 'Revenue', scaleType: 'log', startAtZero: true })
expect(config.showGrid).toBe(false)
+ expect(config.showBestFit).toBe(true)
})
it('formats y values with the column settings', () => {
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.ts
index ba2b438420d5..0b79d7848b5c 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.ts
@@ -101,6 +101,7 @@ export function buildScatterConfig({
: undefined,
},
showGrid: yAxisSettings?.showGridLines ?? true,
+ showBestFit: chartSettings.scatter?.showBestFit ?? false,
legend: { show: chartSettings.showLegend ?? false, position: 'top', interactive: true },
tooltip: {
xFormatter: (value: number): string => value.toLocaleString(),
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
index d33c1089721b..3d92bb18adac 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
@@ -172,12 +172,17 @@ describe('DisplayTab', () => {
expect(screen.queryByText('Right Y-axis')).not.toBeInTheDocument()
expect(screen.queryByText('Goals')).not.toBeInTheDocument()
+ await user.click(screen.getByText('Show line of best fit'))
+
await user.click(screen.getByText('X-axis'))
await user.click(await screen.findByText('Begin at zero'))
+ // Both live under `scatter`, so the second write must merge into the first rather than replace it.
await waitFor(() => {
expect(query.chartSettings).toEqual(
- expect.objectContaining({ scatter: expect.objectContaining({ xStartAtZero: true }) })
+ expect.objectContaining({
+ scatter: expect.objectContaining({ showBestFit: true, xStartAtZero: true }),
+ })
)
})
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
index b9f1999eeef0..fee2e17fd653 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
@@ -171,6 +171,16 @@ export const DisplayTab = (): JSX.Element => {
</>
) : (
<>
+ {isScatterPlot && (
+ <LemonSwitch
+ className="flex-1 w-full"
+ label="Show line of best fit"
+ checked={chartSettings.scatter?.showBestFit ?? false}
+ onChange={(value) => {
+ updateChartSettings({ scatter: { showBestFit: value } })
+ }}
+ />
+ )}
{!isScatterPlot && (
<>
<LemonSwitch
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index de4431c9ba7b..80803acaca1c 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -47711,6 +47711,10 @@
"ScatterChartSettings": {
"additionalProperties": false,
"properties": {
+ "showBestFit": {
+ "description": "Whether to draw a least-squares fit line through each series' points.",
+ "type": "boolean"
+ },
"xScale": {
"description": "X-axis scale. A `logarithmic` axis can't place a non-positive value, so those points are dropped.",
"enum": ["linear", "logarithmic"],
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index fba0a2e43b47..736ac41cd6b7 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1288,6 +1288,8 @@ export interface ScatterChartSettings {
/** Whether the X axis should start at zero. Off by default, because pinning either axis of two
* independent measures to zero squashes the correlation into a corner. */
xStartAtZero?: boolean
+ /** Whether to draw a least-squares fit line through each series' points. */
+ showBestFit?: boolean
}
export interface YAxisSettings {
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 8e5cc62c45fb..339398ea4672 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -106,7 +106,7 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the
- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. Duration formatters accept seconds (`duration`), milliseconds (`duration_ms`), or nanoseconds (`duration_ns`). `hide` and `startAtZero` are honored per entry (bar-series axes keep their zero baseline). A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. More than two axes work too (trends `showMultipleYAxes`): they stack outward per side and alternate sides. Each entry's `label` renders that axis's title at its own gutter — every axis is titled the same way (a single-object `yAxis`/scalar `yAxisLabel` is just the one left axis), driven by the shared `computeYAxisGutters` layout that `AxisLabels` (ticks) and `AxisTitles` (titles) both read so the two can't drift. `TimeSeriesBarChart`/`TimeSeriesComboChart` take the same `yAxis` array; a sole axis pinned `right` renders on the right on every chart type.
- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/`BarChart`/`TimeSeriesBarChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. Despite the name it is label-generic — it resolves the drag against label positions, so it works the same on categorical labels (weekdays, duration buckets) as on dates. A drag whose edges both snap to the same label (common on sparse charts, e.g. a 3-bar monthly chart) selects that single bucket, provided the drag spans enough horizontal distance to read as intentional. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis (`axisOrientation: 'horizontal'` bars, where the core disables the gesture).
- `onAreaSelect` (base `Chart`, chart-type adapters only) is the 2D-brush sibling of `onDateRangeZoom`: the drag tracks both axes, the selection rect clamps to the dragged vertical range, and the completed gesture reports the x label range plus the raw x and y pixel spans (with the committed scales, so the adapter maps pixels onto its own bands). `Heatmap` exposes it as `onBrush` with row/column index ranges; a near-horizontal drag (<8px vertical) spans every row. `ScatterChart` exposes it as its own `onAreaSelect`, inverting the pixel spans through its continuous scales — the label range is meaningless there, since it snaps to whichever points sit near the drag edges. Each edge is clamped to its axis first, so a drag that overshoots the plot (routine when brushing into a corner) reports the rectangle the user saw rather than an extrapolated one. Takes precedence over `onDateRangeZoom` when both are set.
-- `ScatterChart` takes `series: ScatterSeries[]` — each `{ key, label, points: { x, y, label?, radius?, color?, meta? }[], color?, pointRadius?, shape? }` — and no `labels`, since both axes are continuous. `config.xAxis` / `config.yAxis` are symmetric `ScatterAxisConfig`s (`scaleType: 'linear' | 'log'`, `domain` to pin the range, `label`, `tickFormatter`, `hide`, `startAtZero`); unlike a trend, both axes float to their data range by default, because forcing either to zero squashes the correlation into a corner. On a log axis, points with a non-positive coordinate can't be placed and are dropped from the chart. A pinned `domain` narrows the chart rather than just its viewport: points outside it are dropped too, so nothing is drawn out in the axis gutters or piled onto the plot edge at a value it doesn't have. `shape` (`circle` | `square` | `triangle` | `cross`) separates series without relying on color alone, and markers fill at `config.fillOpacity` (0.7) over an opaque outline so a dense cloud reads as density. Hit-testing is 2D and edge-based: the tooltip resolves the marker nearest the cursor in both axes (a large marker the cursor sits inside beats a small one whose center is nearer), and empty plot area resolves to nothing at all rather than to the nearest column. `onPointClick` and the `tooltip` render prop both receive the resolved point (`ScatterPointDatum`, with its series and `meta`) rather than a data index; `config.legend` and `config.tooltip` (`enabled`, `placement`, `labelFormatter`, `xFormatter`, `yFormatter`) work as elsewhere. The default tooltip labels its two rows from the axis titles, falling back to the hovered point's series label for y (so a chart with one column per series still names the measure) and to `X` for x; a header that would just repeat the y row is dropped, leaving a single-series scatter reading as two labeled coordinates. The chrome toggles are the same keys every other chart takes — `showGrid`, `showAxisLines`, `showTickMarks`, `showCrosshair`, all off by default — so a host's shared config defaults reach a scatter the same way they reach a line chart. Its x ticks are resolved once per layout, so the grid lines, the tick marks, and the labels are the same set rather than three that can drift.
+- `ScatterChart` takes `series: ScatterSeries[]` — each `{ key, label, points: { x, y, label?, radius?, color?, meta? }[], color?, pointRadius?, shape? }` — and no `labels`, since both axes are continuous. `config.xAxis` / `config.yAxis` are symmetric `ScatterAxisConfig`s (`scaleType: 'linear' | 'log'`, `domain` to pin the range, `label`, `tickFormatter`, `hide`, `startAtZero`); unlike a trend, both axes float to their data range by default, because forcing either to zero squashes the correlation into a corner. On a log axis, points with a non-positive coordinate can't be placed and are dropped from the chart. A pinned `domain` narrows the chart rather than just its viewport: points outside it are dropped too, so nothing is drawn out in the axis gutters or piled onto the plot edge at a value it doesn't have. `shape` (`circle` | `square` | `triangle` | `cross`) separates series without relying on color alone, and markers fill at `config.fillOpacity` (0.7) over an opaque outline so a dense cloud reads as density. Hit-testing is 2D and edge-based: the tooltip resolves the marker nearest the cursor in both axes (a large marker the cursor sits inside beats a small one whose center is nearer), and empty plot area resolves to nothing at all rather than to the nearest column. `onPointClick` and the `tooltip` render prop both receive the resolved point (`ScatterPointDatum`, with its series and `meta`) rather than a data index; `config.legend` and `config.tooltip` (`enabled`, `placement`, `labelFormatter`, `xFormatter`, `yFormatter`) work as elsewhere. The default tooltip labels its two rows from the axis titles, falling back to the hovered point's series label for y (so a chart with one column per series still names the measure) and to `X` for x; a header that would just repeat the y row is dropped, leaving a single-series scatter reading as two labeled coordinates. The chrome toggles are the same keys every other chart takes — `showGrid`, `showAxisLines`, `showTickMarks`, `showCrosshair`, all off by default — so a host's shared config defaults reach a scatter the same way they reach a line chart. Its x ticks are resolved once per layout, so the grid lines, the tick marks, and the labels are the same set rather than three that can drift. `showBestFit` draws a dashed least-squares line per series, in that series' color, spanning only that series' own points so it doesn't extrapolate a relationship over empty space. It is canvas (over the markers, clipped to the plot), not the SVG `TrendLineOverlay`, whose regression fits y against the array index and so means nothing where x is a measure. The fit runs over the points' pixel positions, which minimizes the same residuals as fitting the raw values on a linear axis and the log values on a log one, and it sees only drawn points — so a series left with fewer than two, or with all of them stacked at a single x, gets no line.
## Testing
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.stories.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.stories.tsx
index c217f0fbe152..c05866954ba6 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.stories.tsx
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.stories.tsx
@@ -72,6 +72,26 @@ export const MultipleSeries: Story = {
},
}
+/** A dashed least-squares fit per series, over the same clouds `MultipleSeries` plots. */
+export const BestFit: Story = {
+ render: function Render() {
+ const theme = useReactiveTheme()
+ const series: ScatterSeries[] = [
+ { key: 'enterprise', label: 'Enterprise', points: makeCloud(60, 3, 0.9, 200) },
+ { key: 'free', label: 'Free', points: makeCloud(60, 11, 0.2, 160), shape: 'cross' },
+ ]
+ return (
+ <Stage width={620} height={380}>
+ <ScatterChart
+ series={series}
+ theme={theme}
+ config={{ ...AXES, showBestFit: true, legend: { show: true } }}
+ />
+ </Stage>
+ )
+ },
+}
+
/** Heavy-tailed data — the reason both axes take a log scale. */
export const LogScales: Story = {
render: function Render() {
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx
index d7b3f18bd900..611e9a87b188 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.tsx
@@ -23,7 +23,8 @@ import type {
Series,
TooltipContext,
} from '../../core/types'
-import { drawScatterHoverMarker, drawScatterMarkers } from './draw-scatter'
+import { computeBestFitSegments } from './best-fit'
+import { drawBestFitLines, drawScatterHoverMarker, drawScatterMarkers } from './draw-scatter'
import { findNearestPointIndex } from './nearest-point'
import { flattenScatterPoints, toAdapterSeries, toPointDatum } from './scatter-data'
import type { FlatScatterPoint } from './scatter-data'
@@ -92,6 +93,7 @@ function ScatterChartInner<Meta = unknown>({
showAxisLines = false,
showTickMarks = false,
showCrosshair = false,
+ showBestFit = false,
margins,
} = config ?? {}
// Destructured to primitives, so an inline `config` literal can't re-run the scale build.
@@ -162,11 +164,17 @@ function ScatterChartInner<Meta = unknown>({
drawScatterMarkers(ctx, layout.positions, fillOpacity)
+ // Over the markers: in a dense cloud, which is where a fit line earns its place, drawing
+ // it underneath would bury it.
+ if (showBestFit) {
+ drawBestFitLines(ctx, computeBestFitSegments(layout.positions, layout.seriesColors), dimensions)
+ }
+
if (axisLineColor) {
drawAxes(drawCtx, { axisColor: axisLineColor })
}
},
- [showGrid, showAxisLines, showTickMarks, fillOpacity]
+ [showGrid, showAxisLines, showTickMarks, fillOpacity, showBestFit]
)
const drawHover = useCallback(({ ctx, scales, hoverIndex, hoverProgress, theme: drawTheme }: ChartDrawArgs) => {
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/best-fit.test.ts b/packages/quill/packages/charts/src/charts/ScatterChart/best-fit.test.ts
new file mode 100644
index 000000000000..06f314b26d81
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/best-fit.test.ts
@@ -0,0 +1,80 @@
+import { computeBestFitSegments } from './best-fit'
+import type { BestFitSegment } from './best-fit'
+import type { ScatterPointPosition } from './scatter-layout'
+
+const positions = (seriesIndex: number, color: string, coords: [number, number][]): ScatterPointPosition[] =>
+ coords.map(([x, y], i) => ({ index: i, seriesIndex, x, y, radius: 3, color, shape: 'circle' }))
+
+describe('computeBestFitSegments', () => {
+ it.each<[string, [number, number][], BestFitSegment]>([
+ [
+ // Off-line middle point, so a join of the outermost two would give y0: 0, y1: 3 instead.
+ 'least squares rather than a join of the outermost points',
+ [
+ [0, 0],
+ [1, 0],
+ [2, 3],
+ ],
+ { seriesIndex: 0, color: '#f00', x0: 0, y0: -0.5, x1: 2, y1: 2.5 },
+ ],
+ [
+ 'a line ending on the outermost of the points',
+ [
+ [10, 20],
+ [20, 40],
+ [30, 60],
+ ],
+ { seriesIndex: 0, color: '#f00', x0: 10, y0: 20, x1: 30, y1: 60 },
+ ],
+ ])('fits %s', (_, coords, expected) => {
+ expect(computeBestFitSegments(positions(0, '#f00', coords), ['#f00'])).toEqual([expected])
+ })
+
+ it('fits each series on its own, so one cloud cannot flatten another', () => {
+ const rising: [number, number][] = [
+ [0, 0],
+ [10, 10],
+ ]
+ const falling: [number, number][] = [
+ [0, 10],
+ [10, 0],
+ ]
+
+ const segments = computeBestFitSegments(
+ [...positions(0, '#f00', rising), ...positions(1, '#00f', falling)],
+ ['#f00', '#00f']
+ )
+
+ // Fitted together these cancel into one flat line through both.
+ expect(segments).toEqual([
+ { seriesIndex: 0, color: '#f00', x0: 0, y0: 0, x1: 10, y1: 10 },
+ { seriesIndex: 1, color: '#00f', x0: 0, y0: 10, x1: 10, y1: 0 },
+ ])
+ })
+
+ it('takes its color from the series, so a highlighted point cannot repaint the line', () => {
+ const highlighted = positions(0, '#f00', [
+ [0, 0],
+ [10, 10],
+ ])
+ highlighted[0].color = '#0f0'
+
+ expect(computeBestFitSegments(highlighted, ['#f00'])).toEqual([
+ { seriesIndex: 0, color: '#f00', x0: 0, y0: 0, x1: 10, y1: 10 },
+ ])
+ })
+
+ // Both leave the gradient undefined, which reaches the canvas as NaN coordinates.
+ it.each<[string, [number, number][]]>([
+ ['has a single point', [[5, 5]]],
+ [
+ 'stacks every point at one x',
+ [
+ [5, 1],
+ [5, 9],
+ ],
+ ],
+ ])('draws no line for a series that %s', (_, coords) => {
+ expect(computeBestFitSegments(positions(0, '#f00', coords), ['#f00'])).toEqual([])
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/best-fit.ts b/packages/quill/packages/charts/src/charts/ScatterChart/best-fit.ts
new file mode 100644
index 000000000000..ee979905a98c
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/best-fit.ts
@@ -0,0 +1,54 @@
+import { group } from 'd3-array'
+
+import { linearRegression } from '../../utils/statistics'
+import type { ScatterPointPosition } from './scatter-layout'
+
+/** A fit line's endpoints, already in pixels. */
+export interface BestFitSegment {
+ seriesIndex: number
+ color: string
+ x0: number
+ y0: number
+ x1: number
+ y1: number
+}
+
+/**
+ * Least squares fit per series, computed over the points' pixel positions rather than their values.
+ * Each axis scale is affine in its own space, so fitting the pixels minimizes the same residuals as
+ * fitting the values on a linear axis, and the log values on a log one — the power-law fit a log
+ * axis implies. Either way the result is straight on screen, which is what a fit line has to be.
+ *
+ * Working off `positions` also means the fit sees exactly the drawn points: those a log axis or a
+ * pinned domain dropped, and those a legend toggle hid, are already gone.
+ *
+ * `seriesColors` is indexed by series index. The color comes from the series rather than one of its
+ * points, so a point-level override — which highlights that one marker — can't repaint the whole
+ * line and put it out of step with the legend.
+ */
+export function computeBestFitSegments(positions: ScatterPointPosition[], seriesColors: string[]): BestFitSegment[] {
+ const bySeries = group(positions, (position) => position.seriesIndex)
+
+ const segments: BestFitSegment[] = []
+ for (const [seriesIndex, seriesPositions] of bySeries) {
+ if (seriesPositions.length < 2) {
+ continue
+ }
+ const { m, b } = linearRegression(seriesPositions.map((position): [number, number] => [position.x, position.y]))
+ // Points stacked at a single x leave the gradient a 0/0, which is a vertical line rather than
+ // a function of x. Nothing to draw.
+ if (!isFinite(m) || !isFinite(b)) {
+ continue
+ }
+ let x0 = Infinity
+ let x1 = -Infinity
+ for (const position of seriesPositions) {
+ x0 = Math.min(x0, position.x)
+ x1 = Math.max(x1, position.x)
+ }
+ // Spans the series' own points instead of the plot, so the line doesn't extrapolate a
+ // relationship out over empty space.
+ segments.push({ seriesIndex, color: seriesColors[seriesIndex], x0, y0: m * x0 + b, x1, y1: m * x1 + b })
+ }
+ return segments
+}
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/draw-scatter.ts b/packages/quill/packages/charts/src/charts/ScatterChart/draw-scatter.ts
index 1365a13ee7e7..c190f7ff7496 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/draw-scatter.ts
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/draw-scatter.ts
@@ -1,10 +1,14 @@
import { traceScatterMarker } from '../../core/canvas-renderer'
import { dimColor } from '../../core/color-utils'
+import type { ChartDimensions } from '../../core/types'
+import type { BestFitSegment } from './best-fit'
import type { ScatterPointPosition } from './scatter-layout'
const MARKER_STROKE_WIDTH = 1.25
const HOVER_HALO_WIDTH = 3
const HOVER_HALO_RADIUS_PX = 2
+const BEST_FIT_WIDTH = 2
+const BEST_FIT_DASH = [6, 4]
/** Fills translucent and strokes opaque, so an overlapping cloud reads as density while each marker
* keeps a crisp edge. A `cross` is strokes only, so it skips the fill. */
@@ -33,6 +37,31 @@ export function drawScatterMarkers(
ctx.restore()
}
+/** Dashed so it reads as derived rather than as data, and in each series' own color so a multi-series
+ * cloud says which fit belongs to which. Clipped to the plot, because a fit that ends on an outlier
+ * can leave the axes' range at either end. */
+export function drawBestFitLines(
+ ctx: CanvasRenderingContext2D,
+ segments: BestFitSegment[],
+ dimensions: ChartDimensions
+): void {
+ ctx.save()
+ ctx.beginPath()
+ ctx.rect(dimensions.plotLeft, dimensions.plotTop, dimensions.plotWidth, dimensions.plotHeight)
+ ctx.clip()
+ ctx.lineWidth = BEST_FIT_WIDTH
+ ctx.lineCap = 'round'
+ ctx.setLineDash(BEST_FIT_DASH)
+ for (const segment of segments) {
+ ctx.strokeStyle = segment.color
+ ctx.beginPath()
+ ctx.moveTo(segment.x0, segment.y0)
+ ctx.lineTo(segment.x1, segment.y1)
+ ctx.stroke()
+ }
+ ctx.restore()
+}
+
export function drawScatterHoverMarker(
ctx: CanvasRenderingContext2D,
position: ScatterPointPosition,
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/nearest-point.test.ts b/packages/quill/packages/charts/src/charts/ScatterChart/nearest-point.test.ts
index 5b620d6a4214..1c1567ad1824 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/nearest-point.test.ts
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/nearest-point.test.ts
@@ -1,8 +1,9 @@
import { findNearestPointIndex } from './nearest-point'
import type { ScatterPointPosition } from './scatter-layout'
+// The hit test doesn't care which series a point came from, so they all sit in one here.
function position(index: number, x: number, y: number, radius = 4): ScatterPointPosition {
- return { index, x, y, radius, color: '#000', shape: 'circle' }
+ return { index, seriesIndex: 0, x, y, radius, color: '#000', shape: 'circle' }
}
describe('findNearestPointIndex', () => {
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/scatter-layout.ts b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-layout.ts
index 2c9d31d36f5d..d5ff8a4fc5d8 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/scatter-layout.ts
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/scatter-layout.ts
@@ -10,6 +10,8 @@ import type { ScatterSeries } from './types'
export interface ScatterPointPosition {
/** Global index into the flattened point list. */
index: number
+ /** Which series drew this point, so per-series work (the best-fit line) can group by it. */
+ seriesIndex: number
x: number
y: number
radius: number
@@ -24,6 +26,9 @@ export interface ScatterLayout {
yScale: D3YScale
/** Visible, drawable points in ascending x-pixel order, which the hit test binary-searches. */
positions: ScatterPointPosition[]
+ /** Canvas-ready series colors by series index, for per-series chrome (the best-fit line) that has
+ * to match the legend rather than whichever override a marker happens to carry. */
+ seriesColors: string[]
/** Resolved once, so the grid lines, the tick marks, and the labels are the same set. */
xTicks: ScatterXTick[]
maxRadius: number
@@ -105,6 +110,7 @@ export function createScatterScales({
maxRadius = Math.max(maxRadius, radius)
positions.push({
index: i,
+ seriesIndex: point.seriesIndex,
x,
y,
radius,
@@ -123,6 +129,7 @@ export function createScatterScales({
xScale,
yScale,
positions,
+ seriesColors: coloredSeries.map((series) => resolveCssColor(series.color ?? fallbackColor)),
xTicks: resolveXTicks(xScale, xTickCount, xTickFormatter),
maxRadius,
},
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/types.ts b/packages/quill/packages/charts/src/charts/ScatterChart/types.ts
index 9f3c4dab4699..a64171605a0b 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/types.ts
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/types.ts
@@ -66,6 +66,9 @@ export interface ScatterChartConfig<Meta = unknown> {
showAxisLines?: boolean
showTickMarks?: boolean
showCrosshair?: boolean
+ /** Draws a dashed least-squares fit line per series, spanning that series' own points. Fitted in
+ * the axes' own space, so a log axis fits the log values. */
+ showBestFit?: boolean
legend?: ChartLegendConfig
tooltip?: ScatterTooltipConfig<Meta>
/** Applied over the computed margins. Should be referentially stable (a module-level constant). */
diff --git a/posthog/schema.py b/posthog/schema.py
index f528a571994a..0140d6150887 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2583,6 +2583,10 @@ class ScatterChartSettings(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
+ showBestFit: bool | None = Field(
+ default=None,
+ description=("Whether to draw a least-squares fit line through each series' points."),
+ )
xScale: XScale | None = Field(
default=None,
description=(
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 84a8c3e419d1..56438d7acf9b 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -8476,6 +8476,8 @@ export const XScaleApi = {
} as const
export interface ScatterChartSettingsApi {
+ /** Whether to draw a least-squares fit line through each series' points. */
+ showBestFit?: boolean | null
/** X-axis scale. A `logarithmic` axis can't place a non-positive value, so those points are dropped. */
xScale?: XScaleApi | null
/** Whether the X axis should start at zero. Off by default, because pinning either axis of two independent measures to zero squashes the correlation into a corner. */
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 7e32dc350fb9..b4eeca15320b 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -7715,6 +7715,8 @@ export const XScaleApi = {
} as const
export interface ScatterChartSettingsApi {
+ /** Whether to draw a least-squares fit line through each series' points. */
+ showBestFit?: boolean | null
/** X-axis scale. A `logarithmic` axis can't place a non-positive value, so those points are dropped. */
xScale?: XScaleApi | null
/** Whether the X axis should start at zero. Off by default, because pinning either axis of two independent measures to zero squashes the correlation into a corner. */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c4b10afe46ce..615dc9d23ba4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8131,6 +8131,8 @@ export namespace Schemas {
} as const;
export interface ScatterChartSettings {
+ /** Whether to draw a least-squares fit line through each series' points. */
+ showBestFit?: boolean | null;
/** X-axis scale. A `logarithmic` axis can't place a non-positive value, so those points are dropped. */
xScale?: XScale | null;
/** Whether the X axis should start at zero. Off by default, because pinning either axis of two independent measures to zero squashes the correlation into a corner. */