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 scatter plot chart type to SQL insights (#82558)

Sam Penningtonde1c3efd38d3
diff --git a/ee/hogai/chat_agent/sql/prompts.py b/ee/hogai/chat_agent/sql/prompts.py
index d3cc985156e6..2ce332af6b64 100644
--- a/ee/hogai/chat_agent/sql/prompts.py
+++ b/ee/hogai/chat_agent/sql/prompts.py
@@ -112,6 +112,7 @@ Visualization guidance:
- Use `ActionsStackedBar` only when a categorical breakdown column should split each x-axis category into colored series.
- Use `ActionsPie` when the user asks for a pie chart or wants to see proportions of a whole across a small set of categories; set `x_axis` to the category column and `y_axis` to the single numeric value column.
- Use `TwoDimensionalHeatmap` only when the query returns x, y, and numeric value columns for a matrix-style result.
+- Use `ScatterPlot` when the user asks how two numeric measures relate, such as a correlation between duration and revenue; set `x_axis` to one numeric column and `y_axis` to the other.
- Use `ActionsTable` for lists, raw event/person rows, or when multiple text columns are the point of the result.
Axis guidance:
diff --git a/ee/hogai/chat_agent/sql/toolkit.py b/ee/hogai/chat_agent/sql/toolkit.py
index 3fc189573ad8..3f979d4621ec 100644
--- a/ee/hogai/chat_agent/sql/toolkit.py
+++ b/ee/hogai/chat_agent/sql/toolkit.py
@@ -20,14 +20,16 @@ def generate_sql_schema() -> dict:
"ActionsStackedBar",
"ActionsPie",
"TwoDimensionalHeatmap",
+ "ScatterPlot",
],
"description": (
"The visualization type for the query results. Use ActionsLineGraph or ActionsAreaGraph for "
"time-based data, BoldNumber for a single value, ActionsBar for categorical comparisons, "
"ActionsStackedBar when a breakdown column should split bars into series, "
"ActionsPie for part-of-a-whole proportions across a small number of categories, "
- "TwoDimensionalHeatmap for x/y/value grids, and ActionsTable only when rows are the intended "
- "output."
+ "TwoDimensionalHeatmap for x/y/value grids, "
+ "ScatterPlot for the relationship between two numeric measures, "
+ "and ActionsTable only when rows are the intended output."
),
},
"x_axis": {
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e68869f4a596..d08df68a50e1 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2772,6 +2772,14 @@ snapshots:
hash: v1.k794b7964.41dfc4667fa9189fe499758412992668a572450ccd8efd81ebc5da0721e0a13f.IxIdKXrKk6F9AAvA7ZrkyjwOwobtpWR6PuJgvv_oSpo
insights-sqlpiegraph--with-legend--light:
hash: v1.k794b7964.334268e3aeef84633d540830a5e1394e55a407118286053925f00e6eb378d806.zeqHqcf7h1Nihj7cEGiafCUbASLAmCZ28Z1xngTBl-0
+ insights-sqlscattergraph--default--dark:
+ hash: v1.k794b7964.5ca16c3fa53c4fa08dfd7c540a2a6dda5ce63b1f9ebcb0e604a4f13e32c17af5.BC1sKBXJftn3jhHnOKFddv2XmlLtCTyZSfPw9c2yt_4
+ insights-sqlscattergraph--default--light:
+ hash: v1.k794b7964.42662c534fc2de368e6186a34b48d2edfc885319dfee2eb45e4e0a3492ccc5f4.KAGJRu5kvpyRw6OOXeh1OnWZqwaEWjZNVpzxl3d2BgQ
+ insights-sqlscattergraph--multiple-series-with-legend--dark:
+ hash: v1.k794b7964.c346d0d12b3a08459a54069df77d2523c5e0eae807a731a658ff367790c94398.hi2HsYRBa30xD64mJJ78jIjFcmrcTM9Y37K1Rg4fyZ4
+ insights-sqlscattergraph--multiple-series-with-legend--light:
+ hash: v1.k794b7964.126c1ab8792efb2eb2067a114290f8b15d0c6d8101e7a9f6ab03421ccf09d7b3.H-ayjpYGiaEvQ22GkDbmDuI1dBPgmvemo9RLaS7j8Vc
insights-stickinessbarchart--stacked--dark:
hash: v1.k794b7964.d5be1db7b3a836f2079373df9e450e82c6ce0f3b0527a9293037f1191289004f.PSzZmvwfQYG3q0lT4lis8t8f_4y7NfSJZu-FY9RQIGA
insights-stickinessbarchart--stacked--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 73b4c206128e..913b6ac2aff8 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -19,6 +19,7 @@ export const DISPLAY_TYPES_TO_CATEGORIES: Record<ChartDisplayType, ChartDisplayC
[ChartDisplayType.WorldMap]: ChartDisplayCategory.TotalValue,
[ChartDisplayType.CalendarHeatmap]: ChartDisplayCategory.TotalValue,
[ChartDisplayType.TwoDimensionalHeatmap]: ChartDisplayCategory.TotalValue,
+ [ChartDisplayType.ScatterPlot]: ChartDisplayCategory.TotalValue,
[ChartDisplayType.BoxPlot]: ChartDisplayCategory.TimeSeries,
// The slope's two points are the first and last interval bucket, so it's time-series at heart;
// it keeps the group-by interval and InsightDisplayConfig hides the options between the ends.
@@ -34,6 +35,7 @@ export const NON_BREAKDOWN_DISPLAY_TYPES = [
ChartDisplayType.Metric,
ChartDisplayType.CalendarHeatmap,
ChartDisplayType.TwoDimensionalHeatmap,
+ ChartDisplayType.ScatterPlot,
ChartDisplayType.BoxPlot,
]
/** Display types which only work with a single series. */
@@ -52,6 +54,7 @@ export const NON_VALUES_ON_SERIES_DISPLAY_TYPES = [
ChartDisplayType.Metric,
ChartDisplayType.CalendarHeatmap,
ChartDisplayType.TwoDimensionalHeatmap,
+ ChartDisplayType.ScatterPlot,
]
/** Display types for which a percent stack view is available. */
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlScatterGraph.stories.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlScatterGraph.stories.tsx
new file mode 100644
index 000000000000..9682e2dfa28b
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlScatterGraph.stories.tsx
@@ -0,0 +1,66 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { ReactNode } from 'react'
+
+import { ChartSettings } from '~/queries/schema/schema-general'
+
+import { AxisSeries } from '../../dataVisualizationLogic'
+import { SqlScatterGraph, SqlScatterGraphProps } from './SqlScatterGraph'
+
+const meta: Meta<typeof SqlScatterGraph> = {
+ title: 'Insights/SqlScatterGraph',
+ component: SqlScatterGraph,
+ parameters: {
+ layout: 'centered',
+ testOptions: { snapshotBrowsers: ['chromium'] },
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof SqlScatterGraph>
+
+const DURATIONS = [12, 34, 55, 61, 78, 90, 104, 130, 152, 171, 194, 210, 245, 280, 320]
+
+const xData: AxisSeries<string> = {
+ column: { name: 'session_duration', type: { name: 'INTEGER', isNumerical: true }, label: 'duration', dataIndex: 0 },
+ data: DURATIONS as unknown as string[],
+}
+
+const yData: AxisSeries<number | null>[] = [
+ {
+ column: { name: 'revenue', type: { name: 'FLOAT', isNumerical: true }, label: 'revenue', dataIndex: 1 },
+ data: [4, 11, 9, 22, 18, 31, 27, 44, 39, 58, 51, 72, 66, 88, 95],
+ settings: {},
+ },
+]
+
+const twoSeries: AxisSeries<number | null>[] = [
+ ...yData,
+ {
+ column: { name: 'refunds', type: { name: 'FLOAT', isNumerical: true }, label: 'refunds', dataIndex: 2 },
+ data: [1, 3, 2, 6, 4, 9, 5, 12, 8, 15, 11, 19, 14, 22, 25],
+ settings: {},
+ },
+]
+
+// The chart fills its flex parent, so the story needs a column container with a definite height —
+// otherwise it resolves to height 0 and quill paints a 0-size canvas (mirrors SqlPieGraph).
+function Stage({ children }: { children: ReactNode }): JSX.Element {
+ // eslint-disable-next-line react/forbid-dom-props
+ return <div style={{ height: 420, width: 760, display: 'flex', flexDirection: 'column' }}>{children}</div>
+}
+
+const render = (props: SqlScatterGraphProps): JSX.Element => (
+ <Stage>
+ <SqlScatterGraph {...props} />
+ </Stage>
+)
+
+const baseSettings: ChartSettings = { leftYAxisSettings: { label: 'Revenue' } }
+
+export const Default: Story = {
+ render: () => render({ xData, yData, chartSettings: baseSettings }),
+}
+
+export const MultipleSeriesWithLegend: Story = {
+ render: () => render({ xData, yData: twoSeries, chartSettings: { ...baseSettings, showLegend: true } }),
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlScatterGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlScatterGraph.test.tsx
new file mode 100644
index 000000000000..99b6bb7af1bb
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlScatterGraph.test.tsx
@@ -0,0 +1,71 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+
+import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'
+
+import { ChartSettings } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { AxisSeries } from '../../dataVisualizationLogic'
+import { SqlScatterGraph } from './SqlScatterGraph'
+
+let cleanupJsdom: () => void
+let cleanupRaf: () => void
+
+beforeEach(() => {
+ initKeaTests()
+ cleanupJsdom = setupJsdom()
+ cleanupRaf = setupSyncRaf()
+})
+
+afterEach(() => {
+ cleanupRaf()
+ cleanupJsdom()
+ cleanup()
+})
+
+const numericColumn = (name: string, dataIndex: number): AxisSeries<number | null>['column'] => ({
+ name,
+ type: { name: 'INTEGER', isNumerical: true },
+ label: name,
+ dataIndex,
+})
+
+const xData = (data: (number | null)[]): AxisSeries<string> => ({
+ column: numericColumn('session_duration', 0),
+ data: data as unknown as string[],
+})
+
+const yData = (data: (number | null)[]): AxisSeries<number | null>[] => [
+ { column: numericColumn('revenue', 1), data, settings: {} },
+]
+
+const chartSettings: ChartSettings = {}
+
+describe('SqlScatterGraph', () => {
+ it('renders the chart when points are present', async () => {
+ render(<SqlScatterGraph xData={xData([1, 2, 3])} yData={yData([10, 20, 30])} chartSettings={chartSettings} />)
+
+ await waitFor(() => expect(document.querySelector('canvas')).toBeInTheDocument())
+ expect(screen.queryByText(/No points to plot/i)).not.toBeInTheDocument()
+ })
+
+ it('shows the empty state when no y-series is selected', () => {
+ render(<SqlScatterGraph xData={xData([1, 2, 3])} yData={[]} chartSettings={chartSettings} />)
+
+ expect(screen.getByText(/No points to plot/i)).toBeInTheDocument()
+ })
+
+ it('shows the empty state when every row is missing a coordinate', () => {
+ render(
+ <SqlScatterGraph
+ xData={xData([1, null, 3])}
+ yData={yData([null, 20, null])}
+ chartSettings={chartSettings}
+ />
+ )
+
+ expect(screen.getByText(/No points to plot/i)).toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlScatterGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlScatterGraph.tsx
new file mode 100644
index 000000000000..42dc04a04e8f
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlScatterGraph.tsx
@@ -0,0 +1,73 @@
+import clsx from 'clsx'
+import { useMemo } from 'react'
+
+import { ScatterChart } from '@posthog/quill-charts'
+
+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
+
+import { ChartSettings } from '~/queries/schema/schema-general'
+
+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
+
+import { AxisSeries } from '../../dataVisualizationLogic'
+import { buildScatterConfig, buildScatterSeries } from './sqlScatterGraphAdapter'
+
+const handleChartError = makeChartErrorHandler('sql-scatter-chart')
+
+export interface SqlScatterGraphProps {
+ /** The x column. Both axes are continuous, so a non-numeric column has nothing to plot. */
+ xData: AxisSeries<string> | null
+ yData: AxisSeries<number | null>[]
+ chartSettings: ChartSettings
+ presetChartHeight?: boolean
+ className?: string
+}
+
+/** SQL scatter plot on @posthog/quill-charts' {@link ScatterChart} — one series per selected Y
+ * column, one marker per result row. */
+export const SqlScatterGraph = ({
+ xData,
+ yData,
+ chartSettings,
+ presetChartHeight,
+ className,
+}: SqlScatterGraphProps): JSX.Element => {
+ const theme = useChartTheme()
+
+ const series = useMemo(() => buildScatterSeries(xData, yData), [xData, yData])
+ const config = useChartConfig(
+ () => (xData ? buildScatterConfig({ xData, yData, chartSettings }) : undefined),
+ [xData, yData, chartSettings]
+ )
+
+ const hasPoints = series.some((s) => s.points.length > 0)
+
+ if (!hasPoints || !config) {
+ return (
+ <div className={clsx(className, 'rounded bg-surface-primary flex flex-1 items-center justify-center p-6')}>
+ <span className="text-secondary text-sm">
+ No points to plot. Pick a numeric column for each axis, and make sure some rows have a value in
+ both.
+ </span>
+ </div>
+ )
+ }
+
+ return (
+ <div
+ className={clsx(
+ className,
+ 'rounded bg-surface-primary w-full grow relative overflow-hidden flex flex-col',
+ { 'h-[60vh]': presetChartHeight, 'h-full': !presetChartHeight }
+ )}
+ >
+ <ScatterChart
+ series={series}
+ theme={theme}
+ config={config}
+ dataAttr="sql-scatter-chart"
+ onError={handleChartError}
+ />
+ </div>
+ )
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.test.ts
new file mode 100644
index 000000000000..ac2d27baeb1a
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.test.ts
@@ -0,0 +1,113 @@
+import { ChartSettings } from '~/queries/schema/schema-general'
+
+import { AxisSeries } from '../../dataVisualizationLogic'
+import { buildScatterConfig, buildScatterSeries } from './sqlScatterGraphAdapter'
+
+const numericColumn = (name: string, dataIndex: number): AxisSeries<number | null>['column'] => ({
+ name,
+ type: { name: 'INTEGER', isNumerical: true },
+ label: name,
+ dataIndex,
+})
+
+const xData = (data: any[]): AxisSeries<string> => ({
+ column: numericColumn('duration', 0),
+ data: data as string[],
+})
+
+const ySeries = (
+ name: string,
+ data: (number | null)[],
+ settings?: AxisSeries<number | null>['settings']
+): AxisSeries<number | null> => ({
+ column: numericColumn(name, 1),
+ data,
+ settings,
+})
+
+describe('sqlScatterGraphAdapter', () => {
+ describe('buildScatterSeries', () => {
+ it('pairs each row with the x column, one series per y column', () => {
+ const series = buildScatterSeries(xData([1, 2, 3]), [
+ ySeries('revenue', [10, 20, 30]),
+ ySeries('refunds', [1, 2, 3]),
+ ])
+
+ expect(series.map((s) => s.label)).toEqual(['revenue', 'refunds'])
+ expect(series[0].points.map(({ x, y }) => [x, y])).toEqual([
+ [1, 10],
+ [2, 20],
+ [3, 30],
+ ])
+ })
+
+ it('drops rows missing either coordinate rather than plotting them at zero', () => {
+ const series = buildScatterSeries(xData([1, null, 3, 'not a number']), [
+ ySeries('revenue', [10, 20, null, 40]),
+ ])
+
+ expect(series[0].points.map(({ x, y }) => [x, y])).toEqual([[1, 10]])
+ })
+
+ it('reads numeric strings, which is how decimal columns arrive', () => {
+ const series = buildScatterSeries(xData(['1.5']), [ySeries('revenue', ['2.5' as any])])
+
+ expect(series[0].points.map(({ x, y }) => [x, y])).toEqual([[1.5, 2.5]])
+ })
+
+ it('honors a column display label and color, and leaves color unset otherwise', () => {
+ const [labeled, plain] = buildScatterSeries(xData([1]), [
+ ySeries('revenue', [10], { display: { label: 'Revenue (USD)', color: '#ff0000' } }),
+ ySeries('refunds', [1]),
+ ])
+
+ expect(labeled.label).toEqual('Revenue (USD)')
+ expect(labeled.color).toEqual('#ff0000')
+ expect(plain.color).toBeUndefined()
+ })
+
+ it('returns nothing without an x column', () => {
+ expect(buildScatterSeries(null, [ySeries('revenue', [10])])).toEqual([])
+ })
+ })
+
+ describe('buildScatterConfig', () => {
+ const build = (chartSettings: ChartSettings): ReturnType<typeof buildScatterConfig> =>
+ buildScatterConfig({ xData: xData([1]), yData: [ySeries('revenue', [10])], chartSettings })
+
+ it('floats both axes and labels the x axis from its column by default', () => {
+ const config = build({})
+
+ expect(config.xAxis).toMatchObject({ label: 'duration', scaleType: 'linear', startAtZero: false })
+ expect(config.yAxis).toMatchObject({ scaleType: 'linear', startAtZero: false })
+ })
+
+ it('applies the scatter and y-axis settings', () => {
+ const config = build({
+ xAxisLabel: 'Session duration',
+ scatter: { xScale: 'logarithmic', xStartAtZero: true },
+ leftYAxisSettings: { label: 'Revenue', scale: 'logarithmic', startAtZero: true, showGridLines: false },
+ })
+
+ expect(config.xAxis).toMatchObject({
+ label: 'Session duration',
+ scaleType: 'log',
+ startAtZero: true,
+ })
+ expect(config.yAxis).toMatchObject({ label: 'Revenue', scaleType: 'log', startAtZero: true })
+ expect(config.showGrid).toBe(false)
+ })
+
+ it('formats y values with the column settings', () => {
+ const config = buildScatterConfig({
+ xData: xData([1]),
+ yData: [ySeries('revenue', [10], { formatting: { style: 'number', prefix: '$' } })],
+ chartSettings: {},
+ })
+
+ const point = { x: 1, y: 1234.5, meta: { settings: { formatting: { prefix: '$' as const } } } } as any
+ expect(config.tooltip?.yFormatter?.(1234.5, point)).toEqual('$1234.5')
+ expect(config.yAxis?.tickFormatter?.(1234.5)).toEqual('$1,234.5')
+ })
+ })
+})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.ts
new file mode 100644
index 000000000000..ba2b438420d5
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlScatterGraphAdapter.ts
@@ -0,0 +1,110 @@
+import { type ScatterChartConfig, type ScatterSeries } from '@posthog/quill-charts'
+
+import { ChartSettings } from '~/queries/schema/schema-general'
+
+import { AxisSeries, AxisSeriesSettings } from '../../dataVisualizationLogic'
+import { formatSqlSeriesValue, hasAxisTickFormatting } from './sqlLineGraphAdapter'
+
+/** Per-point display settings carried into quill's `meta` so the tooltip formats each point with its
+ * own column's currency/percent/prefix/suffix settings — the same trick the line path uses. */
+export interface SqlScatterPointMeta {
+ settings?: AxisSeriesSettings
+}
+
+export type SqlScatterSeries = ScatterSeries<SqlScatterPointMeta>
+
+/** X values reach us as raw response cells — a number for an INTEGER column, a string for a DECIMAL.
+ * Anything that isn't a finite number can't be a coordinate. */
+function toCoordinate(value: unknown): number | null {
+ if (value === null || value === undefined || value === '') {
+ return null
+ }
+ const parsed = typeof value === 'number' ? value : parseFloat(String(value))
+ return Number.isFinite(parsed) ? parsed : null
+}
+
+/** Honors a column's custom display label, matching the line/bar path. `||` so a blank label falls
+ * through to the column name. */
+const getSeriesLabel = (series: AxisSeries<number | null>): string =>
+ series.settings?.display?.label || series.column.name
+
+/**
+ * One quill scatter series per selected Y column, each row of the result a point at
+ * `(x column, y column)`. Rows missing either coordinate are dropped rather than zeroed: a scatter
+ * has no ordering along x to interpolate a gap across, so a null is an absent reading, not a zero.
+ */
+export function buildScatterSeries(
+ xData: AxisSeries<string> | null,
+ yData: AxisSeries<number | null>[]
+): SqlScatterSeries[] {
+ if (!xData) {
+ return []
+ }
+
+ return yData.map((series, index) => {
+ const color = series.settings?.display?.color
+ const points: SqlScatterSeries['points'] = []
+
+ for (let row = 0; row < xData.data.length; row++) {
+ const x = toCoordinate(xData.data[row])
+ const y = toCoordinate(series.data[row])
+ if (x === null || y === null) {
+ continue
+ }
+ points.push({ x, y, meta: { settings: series.settings } })
+ }
+
+ return {
+ key: `${series.column.name}-${index}`,
+ label: getSeriesLabel(series),
+ points,
+ // Only pin an explicit color; otherwise let quill assign palette colors by index.
+ ...(color ? { color } : {}),
+ }
+ })
+}
+
+export interface BuildScatterConfigArgs {
+ xData: AxisSeries<string>
+ yData: AxisSeries<number | null>[]
+ chartSettings: ChartSettings
+}
+
+export function buildScatterConfig({
+ xData,
+ yData,
+ chartSettings,
+}: BuildScatterConfigArgs): ScatterChartConfig<SqlScatterPointMeta> {
+ const yAxisSettings = chartSettings.leftYAxisSettings
+ // Every series shares one gutter here (a scatter has no second axis), so the first column speaks
+ // for the tick format — the same choice the line path makes per gutter.
+ const tickSettings = yData[0]?.settings
+
+ return {
+ xAxis: {
+ // Unlike a trend's self-describing date axis, a scatter's x is a measure, so fall back to
+ // the column name rather than leaving the axis unlabeled.
+ label: chartSettings.xAxisLabel || xData.column.name,
+ scaleType: chartSettings.scatter?.xScale === 'logarithmic' ? 'log' : 'linear',
+ // Neither axis starts at zero unless asked: both are independent measures, and forcing
+ // one to zero squashes the cloud into a corner.
+ startAtZero: chartSettings.scatter?.xStartAtZero ?? false,
+ hide: chartSettings.showXAxisTicks === false,
+ },
+ yAxis: {
+ label: yAxisSettings?.label,
+ scaleType: yAxisSettings?.scale === 'logarithmic' ? 'log' : 'linear',
+ startAtZero: yAxisSettings?.startAtZero ?? false,
+ hide: yAxisSettings?.showTicks === false,
+ tickFormatter: hasAxisTickFormatting(tickSettings)
+ ? (value: number): string => formatSqlSeriesValue(value, tickSettings)
+ : undefined,
+ },
+ showGrid: yAxisSettings?.showGridLines ?? true,
+ legend: { show: chartSettings.showLegend ?? false, position: '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.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
index a2f0196a18a5..d33c1089721b 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
@@ -130,4 +130,55 @@ describe('DisplayTab', () => {
)
})
})
+ it('offers scatter axis settings and drops the panels a scatter has no support for', async () => {
+ initKeaTests()
+
+ const key = 'display-tab-scatter-test'
+ let query: DataVisualizationNode = {
+ kind: NodeKind.DataVisualizationNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: 'select session_duration, revenue from numbers(2)',
+ },
+ display: ChartDisplayType.ScatterPlot,
+ chartSettings: {},
+ }
+
+ const props: DataVisualizationLogicProps = {
+ key,
+ query,
+ dataNodeCollectionId: key,
+ setQuery: (setter) => {
+ query = setter(query)
+ },
+ }
+
+ dataVisualizationLogic(props).mount()
+ displayLogic({ key }).mount()
+
+ render(
+ <BindLogic logic={dataVisualizationLogic} props={props}>
+ <BindLogic logic={displayLogic} props={{ key }}>
+ <DisplayTab />
+ </BindLogic>
+ </BindLogic>
+ )
+
+ const user = userEvent.setup()
+
+ // One gutter per axis, and quill's scatter takes no goal lines.
+ expect(await screen.findByText('X-axis')).toBeInTheDocument()
+ expect(screen.getByText('Y-axis')).toBeInTheDocument()
+ expect(screen.queryByText('Right Y-axis')).not.toBeInTheDocument()
+ expect(screen.queryByText('Goals')).not.toBeInTheDocument()
+
+ await user.click(screen.getByText('X-axis'))
+ await user.click(await screen.findByText('Begin at zero'))
+
+ await waitFor(() => {
+ expect(query.chartSettings).toEqual(
+ expect.objectContaining({ scatter: expect.objectContaining({ xStartAtZero: true }) })
+ )
+ })
+ })
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
index 8c8732ff003d..b9f1999eeef0 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
@@ -42,12 +42,14 @@ export const DisplayTab = (): JSX.Element => {
const isStackedBarChart = effectiveVisualizationType === ChartDisplayType.ActionsStackedBar
const isPieChart = effectiveVisualizationType === ChartDisplayType.ActionsPie
+ const isScatterPlot = effectiveVisualizationType === ChartDisplayType.ScatterPlot
const isLineChart =
effectiveVisualizationType === ChartDisplayType.ActionsLineGraph ||
effectiveVisualizationType === ChartDisplayType.ActionsAreaGraph
const renderYAxisSettings = (name: 'leftYAxisSettings' | 'rightYAxisSettings'): JSX.Element => {
- const labelPlaceholder = name === 'leftYAxisSettings' ? 'Left Y-axis label' : 'Right Y-axis label'
+ const leftPlaceholder = isScatterPlot ? 'Y-axis label' : 'Left Y-axis label'
+ const labelPlaceholder = name === 'leftYAxisSettings' ? leftPlaceholder : 'Right Y-axis label'
return (
<>
@@ -88,7 +90,10 @@ export const DisplayTab = (): JSX.Element => {
<LemonSwitch
className="flex-1 w-full"
label="Begin at zero"
- checked={chartSettings[name]?.startAtZero ?? chartSettings.yAxisAtZero ?? true}
+ checked={
+ chartSettings[name]?.startAtZero ??
+ (isScatterPlot ? false : (chartSettings.yAxisAtZero ?? true))
+ }
onChange={(value) => {
updateChartSettings({ [name]: { startAtZero: value } })
}}
@@ -166,30 +171,34 @@ export const DisplayTab = (): JSX.Element => {
</>
) : (
<>
- <LemonSwitch
- className="flex-1 w-full"
- label="Show total row"
- checked={chartSettings.showTotalRow ?? true}
- onChange={(value) => {
- updateChartSettings({ showTotalRow: value })
- }}
- />
- <LemonSwitch
- className="flex-1 w-full"
- label="Show nulls as zero"
- checked={chartSettings.showNullsAsZero ?? false}
- onChange={(value) => {
- updateChartSettings({ showNullsAsZero: value })
- }}
- />
- <LemonSwitch
- className="flex-1 w-full"
- label="Show values on series"
- checked={chartSettings.showValuesOnSeries ?? false}
- onChange={(value) => {
- updateChartSettings({ showValuesOnSeries: value })
- }}
- />
+ {!isScatterPlot && (
+ <>
+ <LemonSwitch
+ className="flex-1 w-full"
+ label="Show total row"
+ checked={chartSettings.showTotalRow ?? true}
+ onChange={(value) => {
+ updateChartSettings({ showTotalRow: value })
+ }}
+ />
+ <LemonSwitch
+ className="flex-1 w-full"
+ label="Show nulls as zero"
+ checked={chartSettings.showNullsAsZero ?? false}
+ onChange={(value) => {
+ updateChartSettings({ showNullsAsZero: value })
+ }}
+ />
+ <LemonSwitch
+ className="flex-1 w-full"
+ label="Show values on series"
+ checked={chartSettings.showValuesOnSeries ?? false}
+ onChange={(value) => {
+ updateChartSettings({ showValuesOnSeries: value })
+ }}
+ />
+ </>
+ )}
{isLineChart && (
<div className="flex flex-col gap-1">
<LemonLabel>Line style</LemonLabel>
@@ -224,36 +233,76 @@ export const DisplayTab = (): JSX.Element => {
updateChartSettings({ showXAxisTicks: value })
}}
/>
- <LemonSwitch
- className="flex-1 w-full"
- label="Show X-axis border"
- checked={chartSettings.showXAxisBorder ?? true}
- onChange={(value) => {
- updateChartSettings({ showXAxisBorder: value })
- }}
- />
- <LemonSwitch
- className="flex-1 w-full"
- label="Show Y-axis border"
- checked={chartSettings.showYAxisBorder ?? true}
- onChange={(value) => {
- updateChartSettings({ showYAxisBorder: value })
- }}
- />
+ {/* Quill's scatter draws both axis lines together, so a
+ per-edge toggle can't be honored there. */}
+ {!isScatterPlot && (
+ <>
+ <LemonSwitch
+ className="flex-1 w-full"
+ label="Show X-axis border"
+ checked={chartSettings.showXAxisBorder ?? true}
+ onChange={(value) => {
+ updateChartSettings({ showXAxisBorder: value })
+ }}
+ />
+ <LemonSwitch
+ className="flex-1 w-full"
+ label="Show Y-axis border"
+ checked={chartSettings.showYAxisBorder ?? true}
+ onChange={(value) => {
+ updateChartSettings({ showYAxisBorder: value })
+ }}
+ />
+ </>
+ )}
</>
)}
</>
),
},
+ isScatterPlot
+ ? {
+ key: 'x-axis',
+ header: 'X-axis',
+ className: 'p-2 flex flex-col gap-2',
+ content: (
+ <>
+ <div className="flex gap-2 items-center justify-between">
+ <span className="font-medium">Scale</span>
+ <LemonSelect
+ size="xsmall"
+ value={chartSettings.scatter?.xScale ?? 'linear'}
+ options={[
+ { value: 'linear', label: 'Linear' },
+ { value: 'logarithmic', label: 'Logarithmic' },
+ ]}
+ onChange={(value) => {
+ updateChartSettings({ scatter: { xScale: value } })
+ }}
+ />
+ </div>
+ <LemonSwitch
+ className="flex-1 w-full"
+ label="Begin at zero"
+ checked={chartSettings.scatter?.xStartAtZero ?? false}
+ onChange={(value) => {
+ updateChartSettings({ scatter: { xStartAtZero: value } })
+ }}
+ />
+ </>
+ ),
+ }
+ : null,
!isPieChart
? {
key: 'left-y-axis',
- header: 'Left Y-axis',
+ header: isScatterPlot ? 'Y-axis' : 'Left Y-axis',
className: 'p-2 flex flex-col gap-2',
content: renderYAxisSettings('leftYAxisSettings'),
}
: null,
- !isPieChart
+ // A scatter has one gutter per axis, so there is no second Y axis to configure.
+ !isPieChart && !isScatterPlot
? {
key: 'right-y-axis',
header: 'Right Y-axis',
@@ -278,7 +327,7 @@ export const DisplayTab = (): JSX.Element => {
),
}
: null,
- !isPieChart
+ !isPieChart && !isScatterPlot
? {
key: 'goals',
header: (
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsx b/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsx
index 6cfdade11f0e..601eb6ad4e3d 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsx
@@ -26,7 +26,7 @@ import { INSIGHT_UNIT_OPTIONS_SHORT } from 'scenes/insights/aggregationAxisForma
import { ResultCustomizationBy } from '~/queries/schema/schema-general'
import { ChartDisplayType } from '~/types'
-import { AxisSeries, dataVisualizationLogic } from '../dataVisualizationLogic'
+import { AxisSeries, Column, dataVisualizationLogic } from '../dataVisualizationLogic'
import { HeatmapSeriesTab } from './Heatmap/HeatmapSeriesTab'
import { AxisBreakdownSeries, BREAKDOWN_LIMIT_LABEL, seriesBreakdownLogic } from './seriesBreakdownLogic'
import { getAvailableSeriesBreakdownColumns } from './seriesBreakdownUtils'
@@ -53,11 +53,15 @@ export const SeriesTab = (): JSX.Element => {
const { selectedSeriesBreakdownColumn, showSeriesBreakdown } = useValues(breakdownLogic)
const { addSeriesBreakdown } = useActions(breakdownLogic)
+ const isScatterPlot = effectiveVisualizationType === ChartDisplayType.ScatterPlot
const availableBreakdownColumns = getAvailableSeriesBreakdownColumns(columns, selectedXAxis, selectedYAxis)
const hideAddYSeries = yData.length >= numericalColumns.length
+ // A breakdown buckets rows by x value, which a point cloud can't survive — a scatter reads the x
+ // column's own values instead, so the option does nothing there.
const hideAddSeriesBreakdown =
- showSeriesBreakdown || selectedXAxis === null || availableBreakdownColumns.length === 0
+ isScatterPlot || showSeriesBreakdown || selectedXAxis === null || availableBreakdownColumns.length === 0
const showSeriesBreakdownSelector =
+ !isScatterPlot &&
selectedXAxis !== null &&
showSeriesBreakdown &&
(selectedSeriesBreakdownColumn !== null || availableBreakdownColumns.length > 0)
@@ -88,7 +92,7 @@ export const SeriesTab = (): JSX.Element => {
)
}
- const options = columns.map(({ name, type }) => ({
+ const toColumnOption = ({ name, type }: Column): { value: string; label: JSX.Element } => ({
value: name,
label: (
<div className="items-center flex-1">
@@ -98,7 +102,11 @@ export const SeriesTab = (): JSX.Element => {
</LemonTag>
</div>
),
- }))
+ })
+
+ const options = columns.map(toColumnOption)
+ // A scatter's x axis holds a second measure rather than a category, so only numeric columns fit.
+ const xAxisOptions = isScatterPlot ? numericalColumns.map(toColumnOption) : options
if (effectiveVisualizationType === ChartDisplayType.ActionsPie) {
const valueColumn = selectedYAxis?.find((series) => series !== null)?.name ?? null
@@ -166,7 +174,7 @@ export const SeriesTab = (): JSX.Element => {
<LemonSelect
className="w-full"
value={xData !== null ? xData.column.name : 'None'}
- options={options}
+ options={xAxisOptions}
disabledReason={responseLoading ? 'Query loading...' : undefined}
onChange={(value) => {
const column = columns.find((n) => n.name === value)
@@ -486,6 +494,8 @@ export const YSeriesDisplayTab = ({ ySeriesLogicProps }: { ySeriesLogicProps: YS
const { updateSeriesIndex } = useActions(dataVisualizationLogic)
const isPieChart = effectiveVisualizationType === ChartDisplayType.ActionsPie
+ // Neither a pie nor a scatter has a second gutter, a trend line, or a bar/line/area choice.
+ const hideChartSpecificOptions = isPieChart || effectiveVisualizationType === ChartDisplayType.ScatterPlot
const showColorPicker = !showTableSettings && !selectedSeriesBreakdownColumn
const showLabelInput = showTableSettings || !selectedSeriesBreakdownColumn
@@ -542,7 +552,7 @@ export const YSeriesDisplayTab = ({ ySeriesLogicProps }: { ySeriesLogicProps: YS
)}
</div>
)}
- {!showTableSettings && !isPieChart && (
+ {!showTableSettings && !hideChartSpecificOptions && (
<>
{!selectedSeriesBreakdownColumn && (
<LemonField name="trendLine" label="Trend line">
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
index 2808d3751476..afa177922e80 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { IconGraph, IconLifecycle, IconPieChart, IconTrends } from '@posthog/icons'
+import { IconGraph, IconLifecycle, IconPieChart, IconScatter, IconTrends } from '@posthog/icons'
import { LemonSelect, LemonSelectOptions, LemonSelectProps } from '@posthog/lemon-ui'
import { Icon123, IconAreaChart, IconHeatmap, IconTableChart } from 'lib/lemon-ui/icons'
@@ -16,6 +16,8 @@ export const TableDisplay = ({ disabledReason }: TableDisplayProps): JSX.Element
const { autoVisualizationType, columns, numericalColumns, visualizationType } = useValues(dataVisualizationLogic)
const canDisplayContinuousChart = columns.length > 1 && numericalColumns.length > 0
+ // Both scatter axes are numeric measures, so one numeric column can't fill both.
+ const canDisplayScatterPlot = numericalColumns.length > 1
const displayTypeLabels: Record<ChartDisplayType, string> = {
[ChartDisplayType.Auto]: 'Auto',
@@ -35,6 +37,7 @@ export const TableDisplay = ({ disabledReason }: TableDisplayProps): JSX.Element
[ChartDisplayType.TwoDimensionalHeatmap]: '2d heatmap',
[ChartDisplayType.BoxPlot]: 'Box plot',
[ChartDisplayType.SlopeGraph]: 'Slope graph',
+ [ChartDisplayType.ScatterPlot]: 'Scatter plot',
}
const renderDisplayTypeLabel = (displayType: ChartDisplayType): string => {
@@ -108,6 +111,14 @@ export const TableDisplay = ({ disabledReason }: TableDisplayProps): JSX.Element
icon: <IconPieChart />,
label: 'Pie chart',
},
+ {
+ value: ChartDisplayType.ScatterPlot,
+ icon: <IconScatter />,
+ label: 'Scatter plot',
+ disabledReason: !canDisplayScatterPlot
+ ? 'Requires at least two numeric columns, one for each axis'
+ : undefined,
+ },
{
value: ChartDisplayType.TwoDimensionalHeatmap,
icon: <IconHeatmap />,
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index feeaf008e739..8b41d747ce45 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -36,6 +36,7 @@ import { Reload } from '../DataNode/Reload'
import { QueryFeature } from '../DataTable/queryFeatures'
import { PieChart } from './Components/Charts/PieChart'
import { SqlChart } from './Components/Charts/SqlChart'
+import { SqlScatterGraph } from './Components/Charts/SqlScatterGraph'
import { TwoDimensionalHeatmap } from './Components/Heatmap/TwoDimensionalHeatmap'
import { seriesBreakdownLogic } from './Components/seriesBreakdownLogic'
import { SideBar } from './Components/SideBar'
@@ -287,6 +288,18 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
presetChartHeight={presetChartHeight}
/>
)
+ } else if (effectiveVisualizationType === ChartDisplayType.ScatterPlot) {
+ // Both axes are continuous, so a scatter reads the x column's own values rather than the
+ // breakdown path's categorical labels (which dedupe x — fatal for a point cloud).
+ component = (
+ <SqlScatterGraph
+ className="p-3"
+ xData={xData}
+ yData={yData}
+ chartSettings={chartSettings}
+ presetChartHeight={presetChartHeight}
+ />
+ )
} else if (effectiveVisualizationType === ChartDisplayType.TwoDimensionalHeatmap) {
component = <TwoDimensionalHeatmap allowSorting={!(props.embedded && readOnly)} />
} else if (effectiveVisualizationType === ChartDisplayType.BoldNumber) {
diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts
index 04afdb84bc98..5941e85a2d65 100644
--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts
@@ -375,6 +375,80 @@ describe('dataVisualizationLogic', () => {
})
})
+ it('moves a scatter plot onto a numeric x-axis when the selected one has no coordinates', async () => {
+ dataNodeLogic({ key: testKey, query: defaultQuery.source, dataNodeCollectionId }).actions.setResponse({
+ columns: ['country', 'session_duration', 'revenue'],
+ types: [
+ ['country', 'String'],
+ ['session_duration', 'Int64'],
+ ['revenue', 'Float64'],
+ ],
+ results: [['US', 120, 42.5]],
+ })
+
+ // Auto put the string column on the x-axis and both numeric columns on the y-axis.
+ await expectLogic(logic).toMatchValues({ selectedXAxis: 'country' })
+
+ logic.actions.setVisualizationType(ChartDisplayType.ScatterPlot)
+
+ await expectLogic(logic).toMatchValues({
+ selectedXAxis: 'session_duration',
+ selectedYAxis: [expect.objectContaining({ name: 'revenue' })],
+ })
+ })
+
+ it('keeps a numeric x-axis and drops it from the y-series when a scatter plot is picked', async () => {
+ dataNodeLogic({ key: testKey, query: defaultQuery.source, dataNodeCollectionId }).actions.setResponse({
+ columns: ['session_duration', 'revenue'],
+ types: [
+ ['session_duration', 'Int64'],
+ ['revenue', 'Float64'],
+ ],
+ results: [[120, 42.5]],
+ })
+
+ logic.actions.updateXSeries('revenue')
+ logic.actions.setVisualizationType(ChartDisplayType.ScatterPlot)
+
+ // The numeric x is kept, but must be removed from the y-series so it doesn't plot against itself.
+ await expectLogic(logic).toMatchValues({
+ selectedXAxis: 'revenue',
+ selectedYAxis: [expect.objectContaining({ name: 'session_duration' })],
+ })
+ })
+
+ it('re-resolves a scatter x-axis when an all-numeric query changes columns', async () => {
+ const dataNode = dataNodeLogic({ key: testKey, query: defaultQuery.source, dataNodeCollectionId })
+ dataNode.actions.setResponse({
+ columns: ['a', 'b'],
+ types: [
+ ['a', 'Int64'],
+ ['b', 'Int64'],
+ ],
+ results: [[1, 2]],
+ })
+
+ logic.actions.setVisualizationType(ChartDisplayType.ScatterPlot)
+ await expectLogic(logic).toMatchValues({ selectedXAxis: 'a' })
+
+ // Editing the query to add another numeric column re-runs the columns subscription. Without an
+ // explicit scatter resolution there, x would be left null and every point would drop.
+ dataNode.actions.setResponse({
+ columns: ['a', 'b', 'c'],
+ types: [
+ ['a', 'Int64'],
+ ['b', 'Int64'],
+ ['c', 'Int64'],
+ ],
+ results: [[1, 2, 3]],
+ })
+
+ await expectLogic(logic).toMatchValues({
+ selectedXAxis: 'a',
+ selectedYAxis: [expect.objectContaining({ name: 'b' }), expect.objectContaining({ name: 'c' })],
+ })
+ })
+
it('auto-fills 2d heatmap columns when selecting auto on heatmap data', async () => {
dataNodeLogic({ key: testKey, query: defaultQuery.source, dataNodeCollectionId }).actions.setResponse({
columns: ['region', 'segment', 'count'],
diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
index 3f65aabd01e1..15008ebc1f94 100644
--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
@@ -369,6 +369,13 @@ const mergeChartSettings = (state: ChartSettings, settings: ChartSettings): Char
...settings.pie,
}
: undefined,
+ scatter:
+ state.scatter || settings.scatter
+ ? {
+ ...state.scatter,
+ ...settings.scatter,
+ }
+ : undefined,
leftYAxisSettings:
state.leftYAxisSettings || settings.leftYAxisSettings
? {
@@ -416,6 +423,66 @@ const shouldUseFirstNumericColumnAsContinuousChartXAxis = (
return numericalColumns.every((column) => selectedYAxisNames.has(column.name))
}
+/**
+ * A scatter plots two measures against each other, so its x axis has to hold a numeric column.
+ * Returns the column that should sit on the x axis: the current one when it's already numeric,
+ * otherwise a numeric column to move there, preferring one that isn't already a y-series so the
+ * chart isn't left with nothing on either axis. Returns null only when a scatter can't be plotted
+ * (fewer than two numeric columns). The caller drops the chosen column from the y-series if it's
+ * also there, so a column never plots against itself.
+ */
+const resolveScatterXAxisColumn = (
+ columns: Column[],
+ numericalColumns: Column[],
+ selectedXAxis: string | null,
+ selectedYAxis: (SelectedYAxis | null)[] | null
+): Column | null => {
+ // Two numeric columns at minimum — taking the only one for the x axis leaves nothing to plot.
+ if (numericalColumns.length < 2) {
+ return null
+ }
+
+ const currentXAxis = columns.find((column) => column.name === selectedXAxis)
+ if (currentXAxis?.type.isNumerical) {
+ return currentXAxis
+ }
+
+ const selectedYAxisNames = new Set((selectedYAxis ?? []).map((series) => series?.name))
+ return numericalColumns.find((column) => !selectedYAxisNames.has(column.name)) ?? numericalColumns[0]
+}
+
+/**
+ * Establishes the scatter x-axis invariant: a numeric column on the x axis that isn't also a
+ * y-series. Runs from every entry path a scatter can arrive through — the type being picked, the
+ * query's columns changing, and a persisted/assistant-created insight loading — so the chart never
+ * renders blank or plots a column against itself. A no-op when there's nothing to fix.
+ */
+const applyScatterXAxis = (
+ actions: {
+ updateXSeries: (columnName: string) => void
+ deleteYSeries: (seriesIndex: number) => void
+ },
+ columns: Column[],
+ selectedXAxis: string | null,
+ selectedYAxis: (SelectedYAxis | null)[] | null
+): void => {
+ const numericalColumns = columns.filter((column) => column.type.isNumerical)
+ const xAxisColumn = resolveScatterXAxisColumn(columns, numericalColumns, selectedXAxis, selectedYAxis)
+ if (!xAxisColumn) {
+ return
+ }
+
+ if (xAxisColumn.name !== selectedXAxis) {
+ actions.updateXSeries(xAxisColumn.name)
+ }
+
+ // updateXSeries doesn't touch the y-series array, so this index stays valid.
+ const xAxisSeriesIndex = selectedYAxis?.findIndex((series) => series?.name === xAxisColumn.name) ?? -1
+ if (xAxisSeriesIndex > -1) {
+ actions.deleteYSeries(xAxisSeriesIndex)
+ }
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataVisualizationLogicValues {
hasMoreData: boolean // dataNodeLogic
@@ -1783,6 +1850,10 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([
}
}
+ if (visualizationType === ChartDisplayType.ScatterPlot) {
+ applyScatterXAxis(actions, values.columns, values.selectedXAxis, values.selectedYAxis)
+ }
+
const isAutoHeatmap =
visualizationType === ChartDisplayType.Auto &&
getAutoVisualizationType(values.columns, values.response) === ChartDisplayType.TwoDimensionalHeatmap
@@ -1899,6 +1970,13 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([
if (values.effectiveVisualizationType === ChartDisplayType.TwoDimensionalHeatmap) {
applyAutoHeatmapSettings(actions, value, values.chartSettings.heatmap ?? {})
}
+
+ // The generic setup above only lands a numeric x for a scatter by luck (a DATE column or a
+ // non-numeric first column). Resolve it explicitly so an all-numeric query, a column change,
+ // or a persisted/assistant-created scatter still gets a plottable x axis.
+ if (values.effectiveVisualizationType === ChartDisplayType.ScatterPlot) {
+ applyScatterXAxis(actions, value, values.selectedXAxis, values.selectedYAxis)
+ }
},
})),
])
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 5a99233f6e0b..81925cf27637 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -2224,7 +2224,7 @@
"type": "object"
},
"AssistantDataVisualizationDisplayType": {
- "description": "Subset of `ChartDisplayType` values supported by `AssistantDataVisualizationNode`.\n\n- `ActionsTable` — render rows as a data table. This is the default when `display` is omitted.\n- `BoldNumber` — big-number display for single-value results (first numeric column of the first row).\n- `ActionsLineGraph` — line chart. Requires at least two columns, including one numeric column.\n- `ActionsBar` — bar chart with one bar per X-axis value.\n- `ActionsPie` — pie chart for categorical proportions. Requires one label column and one numeric column.\n- `ActionsStackedBar` — bar chart stacked by a series breakdown column.\n- `ActionsAreaGraph` — area chart. Requires at least two columns, including one numeric column.\n- `TwoDimensionalHeatmap` — 2D heatmap. Requires an X column, a Y column, and a numeric value column.",
+ "description": "Subset of `ChartDisplayType` values supported by `AssistantDataVisualizationNode`.\n\n- `ActionsTable` — render rows as a data table. This is the default when `display` is omitted.\n- `BoldNumber` — big-number display for single-value results (first numeric column of the first row).\n- `ActionsLineGraph` — line chart. Requires at least two columns, including one numeric column.\n- `ActionsBar` — bar chart with one bar per X-axis value.\n- `ActionsPie` — pie chart for categorical proportions. Requires one label column and one numeric column.\n- `ActionsStackedBar` — bar chart stacked by a series breakdown column.\n- `ActionsAreaGraph` — area chart. Requires at least two columns, including one numeric column.\n- `TwoDimensionalHeatmap` — 2D heatmap. Requires an X column, a Y column, and a numeric value column.\n- `ScatterPlot` — scatter plot of one measure against another. Requires two numeric columns, one per axis.",
"enum": [
"ActionsTable",
"BoldNumber",
@@ -2233,7 +2233,8 @@
"ActionsPie",
"ActionsStackedBar",
"ActionsAreaGraph",
- "TwoDimensionalHeatmap"
+ "TwoDimensionalHeatmap",
+ "ScatterPlot"
],
"type": "string"
},
@@ -5083,6 +5084,10 @@
"const": "SlopeGraph",
"type": "string"
},
+ {
+ "const": "ScatterPlot",
+ "type": "string"
+ },
{
"not": {}
}
@@ -5182,7 +5187,8 @@
"CalendarHeatmap",
"TwoDimensionalHeatmap",
"BoxPlot",
- "SlopeGraph"
+ "SlopeGraph",
+ "ScatterPlot"
],
"type": "string"
},
@@ -15265,7 +15271,8 @@
"CalendarHeatmap",
"TwoDimensionalHeatmap",
"BoxPlot",
- "SlopeGraph"
+ "SlopeGraph",
+ "ScatterPlot"
],
"type": "string"
},
@@ -15301,6 +15308,9 @@
"rightYAxisSettings": {
"$ref": "#/definitions/YAxisSettings"
},
+ "scatter": {
+ "$ref": "#/definitions/ScatterChartSettings"
+ },
"seriesBreakdownColumn": {
"type": ["string", "null"]
},
@@ -47698,6 +47708,21 @@
"required": ["kind", "shortId"],
"type": "object"
},
+ "ScatterChartSettings": {
+ "additionalProperties": false,
+ "properties": {
+ "xScale": {
+ "description": "X-axis scale. A `logarithmic` axis can't place a non-positive value, so those points are dropped.",
+ "enum": ["linear", "logarithmic"],
+ "type": "string"
+ },
+ "xStartAtZero": {
+ "description": "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.",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
"SchemaMap": {
"additionalProperties": {
"anyOf": [
diff --git a/frontend/src/queries/schema/schema-assistant-queries.ts b/frontend/src/queries/schema/schema-assistant-queries.ts
index 25a6228baafb..daf0bd418b17 100644
--- a/frontend/src/queries/schema/schema-assistant-queries.ts
+++ b/frontend/src/queries/schema/schema-assistant-queries.ts
@@ -1711,6 +1711,7 @@ export interface AssistantInsightVizNode {
* - `ActionsStackedBar` — bar chart stacked by a series breakdown column.
* - `ActionsAreaGraph` — area chart. Requires at least two columns, including one numeric column.
* - `TwoDimensionalHeatmap` — 2D heatmap. Requires an X column, a Y column, and a numeric value column.
+ * - `ScatterPlot` — scatter plot of one measure against another. Requires two numeric columns, one per axis.
*/
export type AssistantDataVisualizationDisplayType =
| ChartDisplayType.ActionsTable
@@ -1721,6 +1722,7 @@ export type AssistantDataVisualizationDisplayType =
| ChartDisplayType.ActionsStackedBar
| ChartDisplayType.ActionsAreaGraph
| ChartDisplayType.TwoDimensionalHeatmap
+ | ChartDisplayType.ScatterPlot
export interface AssistantDataVisualizationAxisDisplaySettings {
/** Which Y axis this numeric series should use. Use `right` for a secondary Y axis. */
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 4b5c97eb08be..fba0a2e43b47 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1282,6 +1282,14 @@ export interface PieChartSettings {
showTotal?: boolean
}
+export interface ScatterChartSettings {
+ /** X-axis scale. A `logarithmic` axis can't place a non-positive value, so those points are dropped. */
+ xScale?: 'linear' | 'logarithmic'
+ /** 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
+}
+
export interface YAxisSettings {
label?: string
scale?: 'linear' | 'logarithmic'
@@ -1315,6 +1323,7 @@ export interface ChartSettings {
showNullsAsZero?: boolean
heatmap?: HeatmapSettings
pie?: PieChartSettings
+ scatter?: ScatterChartSettings
/** Per-breakdown-value color customizations. Keyed by the raw breakdown column value. */
resultCustomizations?: Record<string, ResultCustomizationByValue>
/** Chart rendering style overrides (line shape). Only applies to line and area charts. */
diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.ts
index 4c101fdc2d8e..fc9de62458ab 100644
--- a/frontend/src/queries/utils.ts
+++ b/frontend/src/queries/utils.ts
@@ -502,6 +502,7 @@ const CANVAS_CHART_DISPLAY_TYPES = new Set<ChartDisplayType>([
ChartDisplayType.BoxPlot,
ChartDisplayType.SlopeGraph,
ChartDisplayType.TwoDimensionalHeatmap,
+ ChartDisplayType.ScatterPlot,
])
type QueryVizCanvasClassification = 'canvas' | 'non-canvas' | 'unknown'
diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
index 099c84da98e9..dde452be9f07 100644
--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
@@ -46,6 +46,7 @@ import { QueryExecutionDetails } from '~/queries/nodes/DataNode/QueryExecutionDe
import { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
import { PieChart } from '~/queries/nodes/DataVisualization/Components/Charts/PieChart'
import { SqlChart } from '~/queries/nodes/DataVisualization/Components/Charts/SqlChart'
+import { SqlScatterGraph } from '~/queries/nodes/DataVisualization/Components/Charts/SqlScatterGraph'
import { TwoDimensionalHeatmap } from '~/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap'
import { seriesBreakdownLogic } from '~/queries/nodes/DataVisualization/Components/seriesBreakdownLogic'
import { SideBar } from '~/queries/nodes/DataVisualization/Components/SideBar'
@@ -981,6 +982,16 @@ function InternalDataTableVisualization(
presetChartHeight={presetChartHeight}
/>
)
+ } else if (effectiveVisualizationType === ChartDisplayType.ScatterPlot) {
+ component = (
+ <SqlScatterGraph
+ className="p-2"
+ xData={xData}
+ yData={yData}
+ chartSettings={chartSettings}
+ presetChartHeight={presetChartHeight}
+ />
+ )
} else if (effectiveVisualizationType === ChartDisplayType.TwoDimensionalHeatmap) {
component = <TwoDimensionalHeatmap />
} else if (effectiveVisualizationType === ChartDisplayType.BoldNumber) {
diff --git a/frontend/src/scenes/insights/utils/queryUtils.ts b/frontend/src/scenes/insights/utils/queryUtils.ts
index 64701702bb35..ebab270049bf 100644
--- a/frontend/src/scenes/insights/utils/queryUtils.ts
+++ b/frontend/src/scenes/insights/utils/queryUtils.ts
@@ -240,6 +240,7 @@ const groupedChartDisplayTypes: Record<ChartDisplayType, ChartDisplayType> = {
[ChartDisplayType.ActionsUnstackedBar]: ChartDisplayType.ActionsLineGraph,
[ChartDisplayType.ActionsStackedBar]: ChartDisplayType.ActionsLineGraph,
[ChartDisplayType.TwoDimensionalHeatmap]: ChartDisplayType.ActionsLineGraph,
+ [ChartDisplayType.ScatterPlot]: ChartDisplayType.ActionsLineGraph,
[ChartDisplayType.Metric]: ChartDisplayType.ActionsLineGraph,
// cumulative time series
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 43b43810116a..c2b2779feb5a 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -3030,6 +3030,7 @@ export enum ChartDisplayType {
TwoDimensionalHeatmap = 'TwoDimensionalHeatmap',
BoxPlot = 'BoxPlot',
SlopeGraph = 'SlopeGraph',
+ ScatterPlot = 'ScatterPlot',
}
export enum ChartDisplayCategory {
TimeSeries = 'TimeSeries',
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index b53fd2e93d02..8e5cc62c45fb 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, and 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.
## Testing
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.test.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.test.tsx
index 0505457a631b..602bd5d42dd8 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterChart.test.tsx
@@ -78,6 +78,26 @@ describe('ScatterChart', () => {
expect(tooltip.value('Writes')).toBe('80')
})
+ it('names the y row after the series when the y axis is untitled, without repeating it as a header', async () => {
+ const { chart } = renderScatter({
+ series: [
+ {
+ key: 'writes',
+ label: 'Writes',
+ points: [
+ { x: 0, y: 0 },
+ { x: 25, y: 80 },
+ { x: 100, y: 100 },
+ ],
+ },
+ ],
+ config: { margins: MARGINS, xAxis: { label: 'Reads' } },
+ })
+ const tooltip = createDefaultTooltipAccessor(await hoverPoint(chart.element, 25, 80))
+ expect(tooltip.value('Writes')).toBe('80')
+ expect(tooltip.label()).toBe('')
+ })
+
it.each<[string, ScatterChartConfig, string, string[]]>([
[
'pins each axis to a caller domain',
diff --git a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterTooltip.tsx b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterTooltip.tsx
index a72dc6074fea..70fa22382b73 100644
--- a/packages/quill/packages/charts/src/charts/ScatterChart/ScatterTooltip.tsx
+++ b/packages/quill/packages/charts/src/charts/ScatterChart/ScatterTooltip.tsx
@@ -36,10 +36,14 @@ export function ScatterTooltip<Meta = unknown>({
xValue,
yValue,
}: ScatterTooltipProps<Meta>): React.ReactElement {
+ // The y row names the measure, so the series label serves when the axis is untitled — a chart
+ // whose y axis holds one column per series has that name nowhere else.
+ const yRowLabel = yLabel || point.seriesLabel || 'Y'
const title = header ?? point.label ?? point.seriesLabel
+ const showTitle = Boolean(title) && title !== yRowLabel
return (
<TooltipSurface>
- {title ? (
+ {showTitle ? (
<div
data-attr="hog-chart-tooltip-label"
className="flex items-center gap-2 min-w-0 font-semibold mb-1 opacity-60"
@@ -49,7 +53,7 @@ export function ScatterTooltip<Meta = unknown>({
</div>
) : null}
<Row label={xLabel || 'X'} value={xValue ?? point.x.toLocaleString()} />
- <Row label={yLabel || 'Y'} value={yValue ?? point.y.toLocaleString()} />
+ <Row label={yRowLabel} value={yValue ?? point.y.toLocaleString()} />
</TooltipSurface>
)
}
diff --git a/posthog/schema.py b/posthog/schema.py
index 3d089f08163e..983f83789e5e 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -285,6 +285,7 @@ from posthog.schema_enums import (
WebVitalsMetricBand as WebVitalsMetricBand,
WebVitalsPercentile as WebVitalsPercentile,
WindowDays as WindowDays,
+ XScale as XScale,
YAxisPosition as YAxisPosition,
YAxisScaleType as YAxisScaleType,
)
@@ -2578,6 +2579,26 @@ class SamplingRate(BaseModel):
numerator: float
+class ScatterChartSettings(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ xScale: XScale | None = Field(
+ default=None,
+ description=(
+ "X-axis scale. A `logarithmic` axis can't place a non-positive value, so those points are dropped."
+ ),
+ )
+ xStartAtZero: bool | None = Field(
+ default=None,
+ description=(
+ "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."
+ ),
+ )
+
+
class SessionData(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -14724,6 +14745,7 @@ class ChartSettings(BaseModel):
description=("Per-breakdown-value color customizations. Keyed by the raw breakdown column value."),
)
rightYAxisSettings: YAxisSettings | None = None
+ scatter: ScatterChartSettings | None = None
seriesBreakdownColumn: str | None = None
showLegend: bool | None = None
showNullsAsZero: bool | None = None
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index de5bb80097e1..d7aba1e74d1e 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -207,6 +207,7 @@ class AssistantDataVisualizationDisplayType(StrEnum):
ACTIONS_STACKED_BAR = "ActionsStackedBar"
ACTIONS_AREA_GRAPH = "ActionsAreaGraph"
TWO_DIMENSIONAL_HEATMAP = "TwoDimensionalHeatmap"
+ SCATTER_PLOT = "ScatterPlot"
class Scale(StrEnum):
@@ -524,6 +525,7 @@ class Display(StrEnum):
TWO_DIMENSIONAL_HEATMAP = "TwoDimensionalHeatmap"
BOX_PLOT = "BoxPlot"
SLOPE_GRAPH = "SlopeGraph"
+ SCATTER_PLOT = "ScatterPlot"
class MetricSummary(StrEnum):
@@ -654,6 +656,7 @@ class ChartDisplayType(StrEnum):
TWO_DIMENSIONAL_HEATMAP = "TwoDimensionalHeatmap"
BOX_PLOT = "BoxPlot"
SLOPE_GRAPH = "SlopeGraph"
+ SCATTER_PLOT = "ScatterPlot"
class Curve(StrEnum):
@@ -3756,6 +3759,11 @@ class RetentionType(StrEnum):
RETENTION_FIRST_EVER_OCCURRENCE = "retention_first_ever_occurrence"
+class XScale(StrEnum):
+ LINEAR = "linear"
+ LOGARITHMIC = "logarithmic"
+
+
class SessionAttributionGroupBy(StrEnum):
CHANNEL_TYPE = "ChannelType"
MEDIUM = "Medium"
diff --git a/posthog/schema_helpers.py b/posthog/schema_helpers.py
index 9829af66a686..112a6ebfece7 100644
--- a/posthog/schema_helpers.py
+++ b/posthog/schema_helpers.py
@@ -177,6 +177,7 @@ def grouped_chart_display_types(display: ChartDisplayType) -> ChartDisplayType:
| ChartDisplayType.ACTIONS_UNSTACKED_BAR
| ChartDisplayType.ACTIONS_STACKED_BAR
| ChartDisplayType.TWO_DIMENSIONAL_HEATMAP
+ | ChartDisplayType.SCATTER_PLOT
| ChartDisplayType.METRIC
):
# standard time series
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 070d50d97d53..84a8c3e419d1 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -2379,6 +2379,7 @@ export const ChartDisplayTypeApi = {
TwoDimensionalHeatmap: 'TwoDimensionalHeatmap',
BoxPlot: 'BoxPlot',
SlopeGraph: 'SlopeGraph',
+ ScatterPlot: 'ScatterPlot',
} as const
export interface TrendsFormulaNodeApi {
@@ -8467,6 +8468,20 @@ export interface PieChartSettingsApi {
valueDisplay?: ValueDisplayApi | null
}
+export type XScaleApi = (typeof XScaleApi)[keyof typeof XScaleApi]
+
+export const XScaleApi = {
+ Linear: 'linear',
+ Logarithmic: 'logarithmic',
+} as const
+
+export interface ScatterChartSettingsApi {
+ /** 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. */
+ xStartAtZero?: boolean | null
+}
+
export type DisplayTypeApi = (typeof DisplayTypeApi)[keyof typeof DisplayTypeApi]
export const DisplayTypeApi = {
@@ -8532,6 +8547,7 @@ export interface ChartSettingsApi {
/** Per-breakdown-value color customizations. Keyed by the raw breakdown column value. */
resultCustomizations?: ChartSettingsApiResultCustomizations
rightYAxisSettings?: YAxisSettingsApi | null
+ scatter?: ScatterChartSettingsApi | null
seriesBreakdownColumn?: string | null
showLegend?: boolean | null
showNullsAsZero?: boolean | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 599f7a266268..7e32dc350fb9 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -1618,6 +1618,7 @@ export const ChartDisplayTypeApi = {
TwoDimensionalHeatmap: 'TwoDimensionalHeatmap',
BoxPlot: 'BoxPlot',
SlopeGraph: 'SlopeGraph',
+ ScatterPlot: 'ScatterPlot',
} as const
export interface TrendsFormulaNodeApi {
@@ -7706,6 +7707,20 @@ export interface PieChartSettingsApi {
valueDisplay?: ValueDisplayApi | null
}
+export type XScaleApi = (typeof XScaleApi)[keyof typeof XScaleApi]
+
+export const XScaleApi = {
+ Linear: 'linear',
+ Logarithmic: 'logarithmic',
+} as const
+
+export interface ScatterChartSettingsApi {
+ /** 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. */
+ xStartAtZero?: boolean | null
+}
+
export type DisplayTypeApi = (typeof DisplayTypeApi)[keyof typeof DisplayTypeApi]
export const DisplayTypeApi = {
@@ -7771,6 +7786,7 @@ export interface ChartSettingsApi {
/** Per-breakdown-value color customizations. Keyed by the raw breakdown column value. */
resultCustomizations?: ChartSettingsApiResultCustomizations
rightYAxisSettings?: YAxisSettingsApi | null
+ scatter?: ScatterChartSettingsApi | null
seriesBreakdownColumn?: string | null
showLegend?: boolean | null
showNullsAsZero?: boolean | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e56c42d286f6..ed5d2e3f7c7e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -3054,6 +3054,7 @@ export namespace Schemas {
TwoDimensionalHeatmap: 'TwoDimensionalHeatmap',
BoxPlot: 'BoxPlot',
SlopeGraph: 'SlopeGraph',
+ ScatterPlot: 'ScatterPlot',
} as const;
export interface TrendsFormulaNode {
@@ -8121,6 +8122,21 @@ export namespace Schemas {
valueDisplay?: ValueDisplay | null;
}
+ export type XScale = typeof XScale[keyof typeof XScale];
+
+
+ export const XScale = {
+ Linear: 'linear',
+ Logarithmic: 'logarithmic',
+ } as const;
+
+ export interface ScatterChartSettings {
+ /** 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. */
+ xStartAtZero?: boolean | null;
+ }
+
export type DisplayType = typeof DisplayType[keyof typeof DisplayType];
@@ -8189,6 +8205,7 @@ export namespace Schemas {
/** Per-breakdown-value color customizations. Keyed by the raw breakdown column value. */
resultCustomizations?: ChartSettingsResultCustomizations;
rightYAxisSettings?: YAxisSettings | null;
+ scatter?: ScatterChartSettings | null;
seriesBreakdownColumn?: string | null;
showLegend?: boolean | null;
showNullsAsZero?: boolean | null;
diff --git a/services/mcp/src/tools/generated/product_analytics.ts b/services/mcp/src/tools/generated/product_analytics.ts
index cbe8697936ef..ff063ca53ec2 100644
--- a/services/mcp/src/tools/generated/product_analytics.ts
+++ b/services/mcp/src/tools/generated/product_analytics.ts
@@ -141,6 +141,7 @@ const AssistantDataVisualizationDisplayType = z.enum([
'ActionsStackedBar',
'ActionsAreaGraph',
'TwoDimensionalHeatmap',
+ 'ScatterPlot',
])
const AssistantDataVisualizationTableSettings = z.object({
diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.ts
index 36fe077aac5f..d9f1e3bff36d 100644
--- a/services/mcp/src/tools/generated/query-wrappers.ts
+++ b/services/mcp/src/tools/generated/query-wrappers.ts
@@ -512,6 +512,7 @@ const AssistantTrendsFilter = z.object({
'TwoDimensionalHeatmap',
'BoxPlot',
'SlopeGraph',
+ 'ScatterPlot',
])
.describe(
'Visualization type. Available values: `ActionsLineGraph` - time-series line chart; most common option, as it shows change over time. `ActionsBar` - time-series bar chart. `ActionsAreaGraph` - time-series area chart. `ActionsLineGraphCumulative` - cumulative time-series line chart; good for cumulative metrics. `BoldNumber` - total value single large number. Use when user explicitly asks for a single output number. You CANNOT use this with breakdown or if the insight has more than one series. `Metric` - single large number with a period-over-period change pill and a sparkline. Like `BoldNumber` but trend-aware; configure it with the `metric*` fields below. Single series, no breakdown. `ActionsBarValue` - total value (NOT time-series) bar chart; good for categorical data. `ActionsPie` - total value pie chart; good for visualizing proportions. `ActionsTable` - total value table; good when using breakdown to list users or other entities. `WorldMap` - total value world map; use when breaking down by country name using property `$geoip_country_name`, and only then.'
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json
index f9e8d8de6d8a..e6191e74be67 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-create.json
@@ -319,7 +319,8 @@
"ActionsPie",
"ActionsStackedBar",
"ActionsAreaGraph",
- "TwoDimensionalHeatmap"
+ "TwoDimensionalHeatmap",
+ "ScatterPlot"
],
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json
index 1000c5a4f11d..79f6e4751734 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-update.json
@@ -330,7 +330,8 @@
"ActionsPie",
"ActionsStackedBar",
"ActionsAreaGraph",
- "TwoDimensionalHeatmap"
+ "TwoDimensionalHeatmap",
+ "ScatterPlot"
],
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
index 5e4113ee5493..86e41cd77a41 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
@@ -3833,7 +3833,8 @@
"CalendarHeatmap",
"TwoDimensionalHeatmap",
"BoxPlot",
- "SlopeGraph"
+ "SlopeGraph",
+ "ScatterPlot"
],
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
index e9322816ab6f..1d880999a3a1 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
@@ -3644,7 +3644,8 @@
"CalendarHeatmap",
"TwoDimensionalHeatmap",
"BoxPlot",
- "SlopeGraph"
+ "SlopeGraph",
+ "ScatterPlot"
],
"type": "string"
},