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(data-visualization): add the proportion bar to the sql editor behind a flag (#113528)

Paul D'Ambra49a20b11ecce
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 79aeb4595692..12a02c08e12a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3936,6 +3936,10 @@ snapshots:
hash: v1.k794b7964.d15af2bc969e9e442db3d5520d7b4c26a29f82dd001f9a3656da9cb838cd904e.HU5scx_5_NP2zMcUStE930Oaa1UgjhjHkEOUjAZ-u3w
insights-sqlpiegraph--with-legend--light:
hash: v1.k794b7964.e03eea04875a2046ced662098279559de6cfedb493840f3badf759e1a61a329b.Zkyv5NwjRftokqgfRfDPoMH62IXHvXLwEiQNGVkkoug
+ insights-sqlproportionbar--default--dark:
+ hash: v1.k794b7964.b54d88ba1bebf8f892bbd9af25cd5bd521b460f944501807767ebd14e921a0c3.MGorQmGvepwhhFGOgah4NNRjEw_vZjl45wYrJnst_Uw
+ insights-sqlproportionbar--default--light:
+ hash: v1.k794b7964.2b96a3584008203d1a2c8c12cbb647ec356fedf2975a93a7d402b80a22a73a9a.KaD0osaSl1FeRk0nZkHu1vQrHamGeVau_c_Rc6niWWY
insights-sqlscattergraph--default--dark:
hash: v1.k794b7964.5ca16c3fa53c4fa08dfd7c540a2a6dda5ce63b1f9ebcb0e604a4f13e32c17af5.BC1sKBXJftn3jhHnOKFddv2XmlLtCTyZSfPw9c2yt_4
insights-sqlscattergraph--default--light:
diff --git a/frontend/src/lib/components/Cards/InsightCard/sqlVisualizationSupport.test.ts b/frontend/src/lib/components/Cards/InsightCard/sqlVisualizationSupport.test.ts
index 8d556d690b93..74f000f8a111 100644
--- a/frontend/src/lib/components/Cards/InsightCard/sqlVisualizationSupport.test.ts
+++ b/frontend/src/lib/components/Cards/InsightCard/sqlVisualizationSupport.test.ts
@@ -1,3 +1,5 @@
+import { PART_OF_WHOLE_DISPLAY_TYPES } from 'lib/constants'
+
import { getTableDisplayOptions } from '~/queries/nodes/DataVisualization/Components/TableDisplay'
import {
applyVisualizationType,
@@ -90,13 +92,35 @@ describe('dashboard SQL visualization support', () => {
for (const displayType of chartTypes) {
const saved = applyVisualizationType(baseQuery, displayType, columns, response.result.length)
+ // A part-of-whole chart draws one part per value column, so it needs no X-axis.
+ const needsXAxis = !PART_OF_WHOLE_DISPLAY_TYPES.includes(displayType)
- expect(saved.chartSettings?.xAxis?.column).toEqual(expect.any(String))
+ expect(!needsXAxis || typeof saved.chartSettings?.xAxis?.column === 'string').toBe(true)
expect(saved.chartSettings?.yAxis?.length ?? 0).toBeGreaterThan(0)
}
}
)
+ it.each([ChartDisplayType.ActionsPie, ChartDisplayType.ActionsDonut, ChartDisplayType.ActionsProportionBar])(
+ 'the SQL editor picker disables %s when the results have no numeric column',
+ (displayType) => {
+ const columns = columnsFromResponse({
+ columns: ['country', 'browser'],
+ types: [
+ ['country', 'String'],
+ ['browser', 'String'],
+ ],
+ result: [['US', 'Chrome']],
+ })
+
+ const option = getTableDisplayOptions(columns, [], ChartDisplayType.ActionsTable, undefined, false, true)
+ .flatMap((group: any) => (Array.isArray(group.options) ? group.options : []))
+ .find((candidate: any) => candidate.value === displayType)
+
+ expect(option?.disabledReason).toBe('Requires at least one numeric column')
+ }
+ )
+
it.each([responses['date and numeric'], responses['a single numeric column']])(
'sets up a dashboard Metric from numeric results',
(response) => {
@@ -118,6 +142,60 @@ describe('dashboard SQL visualization support', () => {
}
)
+ it.each([responses['date and numeric'], responses['a single numeric column']])(
+ 'sets up a dashboard proportion bar from numeric results, like Metric',
+ (response) => {
+ const columns = columnsFromResponse(response)
+ const autoVisualizationType = getAutoVisualizationType(columns, response.result.length)
+
+ expect(
+ sqlVisualizationDisabledReason(
+ ChartDisplayType.ActionsProportionBar,
+ baseQuery,
+ columns,
+ response.result.length,
+ autoVisualizationType
+ )
+ ).toBeUndefined()
+ }
+ )
+
+ it.each([ChartDisplayType.ActionsProportionBar, ChartDisplayType.ActionsPie, ChartDisplayType.ActionsDonut])(
+ 'allows a dashboard %s from numeric-only results, with one part per column',
+ (displayType) => {
+ const response =
+ responses['all numeric, which the editor plots by promoting the first column to the x axis']
+ const columns = columnsFromResponse(response)
+ const autoVisualizationType = getAutoVisualizationType(columns, response.result.length)
+
+ expect(
+ sqlVisualizationDisabledReason(
+ displayType,
+ baseQuery,
+ columns,
+ response.result.length,
+ autoVisualizationType
+ )
+ ).toBeUndefined()
+ }
+ )
+
+ it('still requires a numeric column for a proportion bar', () => {
+ const response = responses['all string, so nothing is left to plot']
+ const columns = columnsFromResponse(response)
+ const autoVisualizationType = getAutoVisualizationType(columns, response.result.length)
+
+ expect(
+ sqlVisualizationDisabledReason(
+ ChartDisplayType.ActionsProportionBar,
+ baseQuery,
+ columns,
+ response.result.length,
+ autoVisualizationType
+ )
+ ).toEqual('This insight has no numeric column to plot')
+ })
+
it('sets up a dashboard horizontal bar chart from category and numeric columns', () => {
const response = responses['date and numeric']
const columns = columnsFromResponse(response)
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PartOfWholeChart.test.tsx
similarity index 75%
rename from frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.test.tsx
rename to frontend/src/queries/nodes/DataVisualization/Components/Charts/PartOfWholeChart.test.tsx
index 2d05e49aec96..866d58235ded 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PartOfWholeChart.test.tsx
@@ -8,7 +8,7 @@ import { initKeaTests } from '~/test/init'
import { ChartDisplayType } from '~/types'
import { AxisSeries } from '../../dataVisualizationLogic'
-import { PieChart, PieChartProps } from './PieChart'
+import { PartOfWholeChart, PartOfWholeChartProps } from './PartOfWholeChart'
let cleanupJsdom: () => void
let cleanupRaf: () => void
@@ -25,7 +25,7 @@ afterEach(() => {
cleanup()
})
-const props: PieChartProps = {
+const props: PartOfWholeChartProps = {
xData: {
column: { name: 'category', type: { name: 'STRING', isNumerical: false }, label: 'category', dataIndex: 0 },
data: ['alpha', 'beta'],
@@ -41,9 +41,9 @@ const props: PieChartProps = {
chartSettings: {},
}
-describe('PieChart wrapper', () => {
+describe('PartOfWholeChart', () => {
it('renders the quill SqlPieGraph', async () => {
- render(<PieChart {...props} />)
+ render(<PartOfWholeChart {...props} />)
// The quill PieChart canvas carries this accessible name.
expect(await screen.findByLabelText(/pie chart with/i, {}, { timeout: 5000 })).toBeInTheDocument()
@@ -51,7 +51,7 @@ describe('PieChart wrapper', () => {
it('renders a donut total in the chart center', async () => {
render(
- <PieChart
+ <PartOfWholeChart
{...props}
visualizationType={ChartDisplayType.ActionsDonut}
chartSettings={{ pie: { sliceContent: 'labels', showTotal: true } }}
@@ -62,4 +62,12 @@ describe('PieChart wrapper', () => {
expect((await screen.findByText('100')).closest('[data-attr="sql-pie-chart"]')).toBeInTheDocument()
})
+
+ it('renders a proportion bar for the proportion bar display', () => {
+ const { container } = render(
+ <PartOfWholeChart {...props} visualizationType={ChartDisplayType.ActionsProportionBar} />
+ )
+
+ expect(container.querySelector('[data-attr="sql-proportion-bar"]')).toBeInTheDocument()
+ })
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PartOfWholeChart.tsx
similarity index 52%
rename from frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.tsx
rename to frontend/src/queries/nodes/DataVisualization/Components/Charts/PartOfWholeChart.tsx
index 3bcaf60efd9c..8cc0804ea1b9 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/PieChart.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/PartOfWholeChart.tsx
@@ -3,10 +3,10 @@ import { ChartDisplayType } from '~/types'
import { AxisSeries } from '../../dataVisualizationLogic'
import { AxisBreakdownSeries } from '../seriesBreakdownLogic'
-import { SqlChartProps } from './SqlChart'
import { SqlPieGraph } from './SqlPieGraph'
+import { SqlProportionBar } from './SqlProportionBar'
-export interface PieChartProps {
+export interface PartOfWholeChartProps {
xData: AxisSeries<string> | null
yData: AxisSeries<number | null>[] | AxisBreakdownSeries<number | null>[]
visualizationType: ChartDisplayType
@@ -15,15 +15,10 @@ export interface PieChartProps {
className?: string
}
-export function PieChart(props: PieChartProps): JSX.Element {
- const sqlPieProps: SqlChartProps = {
- xData: props.xData,
- yData: props.yData,
- visualizationType: props.visualizationType,
- chartSettings: props.chartSettings,
- presetChartHeight: props.presetChartHeight,
- className: props.className,
- }
-
- return <SqlPieGraph {...sqlPieProps} />
+export function PartOfWholeChart(props: PartOfWholeChartProps): JSX.Element {
+ return props.visualizationType === ChartDisplayType.ActionsProportionBar ? (
+ <SqlProportionBar {...props} />
+ ) : (
+ <SqlPieGraph {...props} />
+ )
}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.test.ts
index 892c8aec7853..b5446a0bf06a 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.test.ts
@@ -38,7 +38,7 @@ describe('sqlChartComponentFor', () => {
['bar', ChartDisplayType.ActionsBar, 'SqlBarGraph'],
['horizontal bar', ChartDisplayType.ActionsBarValue, 'SqlBarGraph'],
// Pie is not routed here — it has its own wrapper (see PieChart.test.tsx).
- ['pie (handled by the PieChart wrapper, not here)', ChartDisplayType.ActionsPie, 'SqlLineGraph'],
+ ['pie (handled by PartOfWholeChart, not here)', ChartDisplayType.ActionsPie, 'SqlLineGraph'],
])('routes %s to the right component', (_name, visualizationType, expected) => {
expect(sqlChartComponentFor(baseProps(visualizationType)).name).toBe(expected)
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsx
index f15f6daadeef..5b0e67b9ac58 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsx
@@ -39,7 +39,7 @@ export type SqlChartProps = {
/**
* Picks the @posthog/quill-charts renderer for a SQL insight: combo for mixed bar + line/area
- * series, bar for bar-only, line/area otherwise. (Pie has its own wrapper — see PieChart.)
+ * series, bar for bar-only, line/area otherwise. (Pie, donut and proportion bar have their own wrapper — see PartOfWholeChart.)
*/
export function sqlChartComponentFor(props: SqlChartProps): (props: SqlChartProps) => JSX.Element {
switch (sqlChartKind(props)) {
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx
index f427ce90ae38..83fc16397907 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlPieGraph.tsx
@@ -1,11 +1,8 @@
import clsx from 'clsx'
-import { useCallback, useMemo, useState } from 'react'
+import { useCallback, useMemo } from 'react'
import { ChartLegend, PieChart, TooltipSurface, TooltipSwatch, useChartLegend } from '@posthog/quill-charts'
-import type { ChartLegendConfig, PieChartConfig, TooltipContext } from '@posthog/quill-charts'
-
-import { useChartTheme } from 'lib/charts/hooks'
-import { useChartLegendSeriesMenu } from 'lib/components/ChartLegendSeriesMenu/useChartLegendSeriesMenu'
+import type { PieChartConfig, TooltipContext } from '@posthog/quill-charts'
import { ChartDisplayType } from '~/types'
@@ -13,8 +10,8 @@ import { makeChartErrorHandler } from 'products/product_analytics/frontend/insig
import { DonutCenterLabel } from 'products/product_analytics/frontend/insights/trends/TrendsPieChart/DonutCenterLabel'
import { SqlChartProps } from './SqlChart'
-import { formatSqlSeriesValue } from './sqlLineGraphAdapter'
-import { buildPieSeries, buildPieSlices, formatPieSliceCount } from './sqlPieGraphAdapter'
+import { formatPieSliceCount } from './sqlPieGraphAdapter'
+import { useSqlPartOfWholeChart } from './useSqlPartOfWholeChart'
const handleChartError = makeChartErrorHandler('sql-pie-chart')
@@ -32,52 +29,15 @@ export const SqlPieGraph = ({
presetChartHeight,
className,
}: SqlChartProps): JSX.Element => {
- const theme = useChartTheme()
const isDonut = visualizationType === ChartDisplayType.ActionsDonut
-
- const slices = useMemo(() => buildPieSlices(xData, yData), [xData, yData])
- const formattingSettings = yData[0]?.settings
- const series = useMemo(() => buildPieSeries(slices), [slices])
-
- // Toggled-off slices aren't persisted (SQL insights have nowhere to save them), but the legend
- // is controlled anyway so the total and the tooltip shares track the slices actually drawn.
- const [hiddenKeys, setHiddenKeys] = useState<string[]>([])
- const showLegend = chartSettings.showLegend ?? false
- const visibleHiddenKeySet = useMemo(() => new Set(showLegend ? hiddenKeys : []), [showLegend, hiddenKeys])
- const total = useMemo(
- () => series.reduce((sum, s) => (visibleHiddenKeySet.has(s.key) ? sum : sum + (s.data[0] ?? 0)), 0),
- [series, visibleHiddenKeySet]
- )
+ const { theme, series, legendConfig, total, showTotal, formattingSettings, valueFormatter } =
+ useSqlPartOfWholeChart({ xData, yData, chartSettings }, false)
// Unset means an existing chart from before the labels option — keep showing values. New pies
// are stamped with 'labels' when the type is picked (see dataVisualizationLogic).
const sliceContent = chartSettings.pie?.sliceContent ?? 'values'
- // The total is a sum-of-values readout, so default it on only when slices show values.
- // `showPieTotal` is the legacy top-level toggle — honor it for charts saved before `pie`.
- const showPieTotal = chartSettings.pie?.showTotal ?? chartSettings.showPieTotal ?? sliceContent === 'values'
const asPercent = (chartSettings.pie?.valueDisplay ?? 'absolute') === 'percentage'
- const absoluteFormatter = useCallback(
- (value: number) => formatSqlSeriesValue(value, formattingSettings),
- [formattingSettings]
- )
-
- const legendRenderItem = useChartLegendSeriesMenu({ surface: 'sql', seriesCount: series.length })
-
- const legendConfig: ChartLegendConfig = useMemo(
- () => ({
- show: showLegend,
- position: chartSettings.legendPosition ?? 'right',
- interactive: true,
- hiddenKeys: showLegend ? hiddenKeys : [],
- onToggleSeries: (key: string) =>
- setHiddenKeys((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key])),
- onSetHiddenSeries: setHiddenKeys,
- renderItem: legendRenderItem,
- }),
- [showLegend, chartSettings.legendPosition, hiddenKeys, legendRenderItem]
- )
-
const { visibleSeries, legendProps } = useChartLegend(series, theme, legendConfig)
// `isPercent` makes the chart render on-slice values and tooltips as a share of the total; the
@@ -117,7 +77,7 @@ export const SqlPieGraph = ({
[total, formattingSettings, asPercent]
)
- if (!slices.length) {
+ if (!series.length) {
return (
<div className={clsx(className, 'rounded bg-surface-primary flex flex-1 items-center justify-center p-6')}>
<span className="text-secondary text-sm">Pie charts require at least one positive value.</span>
@@ -125,13 +85,12 @@ export const SqlPieGraph = ({
)
}
- const centerLabel =
- isDonut && showPieTotal ? <DonutCenterLabel>{absoluteFormatter(total)}</DonutCenterLabel> : undefined
+ const centerLabel = isDonut && showTotal ? <DonutCenterLabel>{valueFormatter(total)}</DonutCenterLabel> : undefined
const totalDisplay =
- !isDonut && showPieTotal ? (
+ !isDonut && showTotal ? (
<div className="pt-4 text-center shrink-0">
- <div className="text-5xl font-bold">{absoluteFormatter(total)}</div>
+ <div className="text-5xl font-bold">{valueFormatter(total)}</div>
</div>
) : null
@@ -155,7 +114,7 @@ export const SqlPieGraph = ({
theme={theme}
config={pieConfig}
tooltip={renderTooltip}
- valueFormatter={absoluteFormatter}
+ valueFormatter={valueFormatter}
centerLabel={centerLabel}
dataAttr="sql-pie-chart"
onError={handleChartError}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.stories.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.stories.tsx
new file mode 100644
index 000000000000..d1c4a61a7390
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.stories.tsx
@@ -0,0 +1,45 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { ChartDisplayType } from '~/types'
+
+import { AxisSeries } from '../../dataVisualizationLogic'
+import { SqlProportionBar } from './SqlProportionBar'
+
+const meta: Meta<typeof SqlProportionBar> = {
+ title: 'Insights/SqlProportionBar',
+ component: SqlProportionBar,
+ parameters: {
+ layout: 'centered',
+ testOptions: { snapshotBrowsers: ['chromium'] },
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof SqlProportionBar>
+
+const xData: AxisSeries<string> = {
+ column: { name: 'month', type: { name: 'STRING', isNumerical: false }, label: 'month', dataIndex: 0 },
+ data: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
+}
+
+const yData: AxisSeries<number | null>[] = [
+ {
+ column: { name: 'events', type: { name: 'INTEGER', isNumerical: true }, label: 'events', dataIndex: 1 },
+ data: [4200, 1800, 620, 410, 80],
+ settings: {},
+ },
+]
+
+export const Default: Story = {
+ render: () => (
+ // eslint-disable-next-line react/forbid-dom-props
+ <div style={{ height: 420, width: 760, display: 'flex', flexDirection: 'column' }}>
+ <SqlProportionBar
+ xData={xData}
+ yData={yData}
+ visualizationType={ChartDisplayType.ActionsProportionBar}
+ chartSettings={{}}
+ />
+ </div>
+ ),
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.test.tsx
new file mode 100644
index 000000000000..ab05ba78efb2
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.test.tsx
@@ -0,0 +1,107 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { getHogChart, mockRect, setupJsdom, setupSyncRaf, waitForHogChartTooltip } from '@posthog/quill-charts/testing'
+
+import { ChartSettings } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { ChartDisplayType } from '~/types'
+
+import { AxisSeries } from '../../dataVisualizationLogic'
+import { SqlChartProps } from './SqlChart'
+import { SqlProportionBar } from './SqlProportionBar'
+
+let cleanupJsdom: () => void
+let cleanupRaf: () => void
+
+beforeEach(() => {
+ initKeaTests()
+ cleanupJsdom = setupJsdom()
+ cleanupRaf = setupSyncRaf()
+})
+
+afterEach(() => {
+ cleanupRaf()
+ cleanupJsdom()
+ cleanup()
+})
+
+const xData: AxisSeries<string> = {
+ column: { name: 'category', type: { name: 'STRING', isNumerical: false }, label: 'category', dataIndex: 0 },
+ data: ['alpha', 'beta', 'gamma', 'delta'],
+}
+
+const barProps = (chartSettings: ChartSettings, data: (number | null)[]): SqlChartProps => ({
+ xData,
+ yData: [
+ {
+ column: { name: 'value', type: { name: 'INTEGER', isNumerical: true }, label: 'value', dataIndex: 1 },
+ data,
+ settings: {},
+ },
+ ],
+ visualizationType: ChartDisplayType.ActionsProportionBar,
+ chartSettings,
+})
+
+const withParts = (count: number): SqlChartProps => ({
+ ...barProps({}, Array(count).fill(100 / count)),
+ xData: { ...xData, data: Array.from({ length: count }, (_, i) => `part ${i}`) },
+})
+
+describe('SqlProportionBar', () => {
+ it.each([
+ {
+ name: 'shows its legend shares and the total by default',
+ chartSettings: {},
+ expectedShares: ['40% · 40', '30% · 30', '20% · 20', '10% · 10'],
+ showsTotal: true,
+ },
+ {
+ name: 'hides its legend when the user turns it off',
+ chartSettings: { showLegend: false },
+ expectedShares: [],
+ showsTotal: true,
+ },
+ {
+ name: 'hides the total when showTotal is false',
+ chartSettings: { pie: { showTotal: false } },
+ expectedShares: ['40% · 40', '30% · 30', '20% · 20', '10% · 10'],
+ showsTotal: false,
+ },
+ {
+ name: 'still shows the total when a stale pie sliceContent carries over',
+ chartSettings: { pie: { sliceContent: 'labels' as const } },
+ expectedShares: ['40% · 40', '30% · 30', '20% · 20', '10% · 10'],
+ showsTotal: true,
+ },
+ {
+ name: 'starts with its legend off when it has many parts',
+ chartSettings: {},
+ partCount: 25,
+ expectedShares: [],
+ showsTotal: true,
+ },
+ ])('$name', ({ chartSettings, partCount, expectedShares, showsTotal }) => {
+ const props = partCount ? withParts(partCount) : barProps(chartSettings, [40, 30, 20, 10])
+ const { container } = render(<SqlProportionBar {...props} />)
+
+ const legendRows = getHogChart(container).legendItems()
+ expect(legendRows.map((row) => row.secondaryLabel)).toEqual(expectedShares)
+ expect(screen.queryByText('100') !== null).toBe(showsTotal)
+ })
+
+ it("shows a part's share in its tooltip, even for a percent-formatted column", async () => {
+ const props = barProps({}, [0.2, 0.2])
+ props.yData[0].settings = { formatting: { style: 'percent' } }
+ const { container } = render(<SqlProportionBar {...props} />)
+ const chart = getHogChart(container)
+
+ const tooltip = await waitForHogChartTooltip(3000, () =>
+ fireEvent.mouseMove(chart.element, { clientX: mockRect.width / 4, clientY: mockRect.height / 2 })
+ )
+
+ expect(tooltip).toHaveTextContent('50%')
+ })
+})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.tsx
new file mode 100644
index 000000000000..5ba9e719c782
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlProportionBar.tsx
@@ -0,0 +1,58 @@
+import clsx from 'clsx'
+
+import { ProportionBar } from '@posthog/quill-charts'
+import type { ProportionBarConfig } from '@posthog/quill-charts'
+
+import { useChartConfig } from 'lib/charts/hooks'
+
+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
+
+import { SqlChartProps } from './SqlChart'
+import { useSqlPartOfWholeChart } from './useSqlPartOfWholeChart'
+
+const handleChartError = makeChartErrorHandler('sql-proportion-bar')
+
+export const SqlProportionBar = ({
+ xData,
+ yData,
+ chartSettings,
+ presetChartHeight,
+ className,
+}: SqlChartProps): JSX.Element => {
+ const { theme, series, legendConfig, total, showTotal, valueFormatter } = useSqlPartOfWholeChart(
+ { xData, yData, chartSettings },
+ true
+ )
+ const config: ProportionBarConfig = useChartConfig(() => ({ legend: legendConfig }), [legendConfig])
+
+ if (!series.length) {
+ return (
+ <div className={clsx(className, 'rounded bg-surface-primary flex flex-1 items-center justify-center p-6')}>
+ <span className="text-secondary text-sm">Proportion bars require at least one positive value.</span>
+ </div>
+ )
+ }
+
+ return (
+ <div
+ className={clsx(className, 'rounded bg-surface-primary flex flex-col flex-1 min-h-0 p-4 justify-center', {
+ 'h-[60vh]': presetChartHeight,
+ 'h-full': !presetChartHeight,
+ })}
+ >
+ <ProportionBar
+ series={series}
+ theme={theme}
+ config={config}
+ valueFormatter={valueFormatter}
+ dataAttr="sql-proportion-bar"
+ onError={handleChartError}
+ />
+ {showTotal && (
+ <div className="pt-4 text-center shrink-0">
+ <div className="text-5xl font-bold">{valueFormatter(total)}</div>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.test.ts
index edc42fa5adea..0cea72a6ec6c 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.test.ts
@@ -70,6 +70,30 @@ describe('sqlPieGraphAdapter', () => {
])
})
+ it('treats a non-finite value as zero instead of making the whole label non-finite', () => {
+ const yData: AxisSeries<number | null>[] = [
+ {
+ column: {
+ name: 'value',
+ type: {
+ name: 'INTEGER',
+ isNumerical: true,
+ },
+ label: 'value',
+ dataIndex: 1,
+ },
+ // 'alpha' sums 2 and Infinity; a non-finite value must not carry into the total.
+ data: [2, 3, Number.POSITIVE_INFINITY],
+ settings: {},
+ },
+ ]
+
+ expect(buildPieSlices(xData, yData)).toEqual([
+ { label: 'alpha', value: 2, color: getSeriesColor(0) },
+ { label: 'beta', value: 3, color: getSeriesColor(1) },
+ ])
+ })
+
it('aggregates breakdown series by series total', () => {
const yData: AxisBreakdownSeries<number | null>[] = [
{
@@ -92,6 +116,19 @@ describe('sqlPieGraphAdapter', () => {
])
})
+ it('does not let one NaN point drop a breakdown series that also has valid points', () => {
+ const yData: AxisBreakdownSeries<number | null>[] = [
+ {
+ name: 'first',
+ breakdownValue: 'first',
+ data: [1, NaN, 2],
+ settings: { display: { color: '#111111' } },
+ },
+ ]
+
+ expect(buildPieSlices(xData, yData)).toEqual([{ label: 'first', value: 3, color: '#111111' }])
+ })
+
it('falls back to one slice per y-series when there is no categorical x-axis', () => {
const noXAxis: AxisSeries<string> = {
column: {
@@ -150,11 +187,33 @@ describe('sqlPieGraphAdapter', () => {
{ label: 'beta', value: 3, color: '#222222' },
])
).toEqual([
- { key: 'alpha-0', label: 'alpha', color: '#111111', data: [7] },
- { key: 'beta-1', label: 'beta', color: '#222222', data: [3] },
+ { key: 'alpha', label: 'alpha', color: '#111111', data: [7] },
+ { key: 'beta', label: 'beta', color: '#222222', data: [3] },
])
})
+ it.each([
+ {
+ name: 'keys a part by its label, so a reorder keeps the key',
+ labels: ['beta', 'alpha'],
+ keys: ['beta', 'alpha'],
+ },
+ {
+ name: 'numbers a repeated label',
+ labels: ['alpha', 'alpha', 'beta'],
+ keys: ['alpha', 'alpha-2', 'beta'],
+ },
+ {
+ name: 'skips a numbered key that another label already takes',
+ labels: ['alpha', 'alpha', 'alpha-2'],
+ keys: ['alpha', 'alpha-3', 'alpha-2'],
+ },
+ ])('$name', ({ labels, keys }) => {
+ const slices = labels.map((label) => ({ label, value: 1, color: '#111111' }))
+
+ expect(buildPieSeries(slices).map((series) => series.key)).toEqual(keys)
+ })
+
it('returns an empty array when there are no slices', () => {
expect(buildPieSeries([])).toEqual([])
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.ts
index 053f0663a156..ca652be53ee5 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter.ts
@@ -1,9 +1,12 @@
import { type Series } from '@posthog/quill-charts'
import { getSeriesColor } from 'lib/colors'
+import { MAX_DEFAULT_PROPORTION_LEGEND_PARTS } from 'lib/constants'
+
+import { ChartSettings } from '~/queries/schema/schema-general'
import { AxisSeries, AxisSeriesSettings } from '../../dataVisualizationLogic'
-import { AxisBreakdownSeries } from '../seriesBreakdownLogic'
+import { AxisBreakdownSeries, BreakdownSeriesData } from '../seriesBreakdownLogic'
import { formatSqlSeriesValue } from './sqlLineGraphAdapter'
export interface PieSlice {
@@ -14,7 +17,7 @@ export interface PieSlice {
export type SqlPieYSeries = AxisSeries<number | null> | AxisBreakdownSeries<number | null>
-const isBreakdownSeries = (series: SqlPieYSeries): series is AxisBreakdownSeries<number | null> => {
+export const isBreakdownSeries = (series: SqlPieYSeries): series is AxisBreakdownSeries<number | null> => {
return !('column' in series)
}
@@ -26,8 +29,11 @@ const toSliceLabel = (value: unknown): string => {
return String(value)
}
+// One NaN or Infinity point would otherwise make the whole category's sum non-finite.
+const toFiniteValue = (value: number | null): number => (value !== null && Number.isFinite(value) ? value : 0)
+
const sumValues = (values: (number | null)[]): number => {
- return values.reduce<number>((sum, value) => sum + (value ?? 0), 0)
+ return values.reduce<number>((sum, value) => sum + toFiniteValue(value), 0)
}
const getSeriesLabel = (series: SqlPieYSeries, index: number): string => {
@@ -48,6 +54,12 @@ const seriesToSlices = (yData: SqlPieYSeries[]): PieSlice[] =>
}))
.filter((slice) => slice.value > 0)
+const hasLabelColumn = (xData: AxisSeries<string> | null): xData is AxisSeries<string> =>
+ !!xData && xData.column.name !== 'None'
+
+export const drawsOnePartPerSeries = (xData: AxisSeries<string> | null, yData: SqlPieYSeries[]): boolean =>
+ yData.length !== 1 || !hasLabelColumn(xData) || yData.some(isBreakdownSeries)
+
export const buildPieSlices = (
xData: AxisSeries<string> | null,
yData: AxisSeries<number | null>[] | AxisBreakdownSeries<number | null>[]
@@ -56,42 +68,77 @@ export const buildPieSlices = (
return []
}
- if (yData.some(isBreakdownSeries)) {
+ if (drawsOnePartPerSeries(xData, yData) || !xData) {
return seriesToSlices(yData)
}
- if (yData.length === 1 && xData && xData.column.name !== 'None') {
- const totalsByLabel = new Map<string, number>()
-
- xData.data.forEach((rawLabel, index) => {
- const label = toSliceLabel(rawLabel)
- const value = yData[0].data[index] ?? 0
- totalsByLabel.set(label, (totalsByLabel.get(label) ?? 0) + value)
- })
-
- return Array.from(totalsByLabel.entries())
- .map(([label, value], index) => ({
- label,
- value,
- color: getSeriesColor(index),
- }))
- .filter((slice) => slice.value > 0)
- }
-
- return seriesToSlices(yData)
+ const totalsByLabel = new Map<string, number>()
+ xData.data.forEach((rawLabel, index) => {
+ const label = toSliceLabel(rawLabel)
+ const value = toFiniteValue(yData[0].data[index])
+ totalsByLabel.set(label, (totalsByLabel.get(label) ?? 0) + value)
+ })
+
+ return Array.from(totalsByLabel.entries())
+ .map(([label, value], index) => ({
+ label,
+ value,
+ color: getSeriesColor(index),
+ }))
+ .filter((slice) => slice.value > 0)
}
/** One quill `Series` per slice, with the slice's resolved color pinned so per-breakdown
* `resultCustomizations` survive the move off chart.js. */
export const buildPieSeries = (slices: PieSlice[]): Series[] => {
- return slices.map((slice, index) => ({
- key: `${slice.label}-${index}`,
- label: slice.label,
- color: slice.color,
- data: [slice.value],
- }))
+ // Keyed by label, not position, so a part hidden in the legend stays hidden when the results reorder.
+ // A repeat skips a numbered key that another part has as its own label, so no two parts share a key.
+ const labels = new Set(slices.map((slice) => slice.label))
+ const usedKeys = new Set<string>()
+ const nextSuffix = new Map<string, number>()
+ return slices.map((slice) => {
+ let key = slice.label
+ let count = nextSuffix.get(slice.label) ?? 2
+ while (usedKeys.has(key) || (key !== slice.label && labels.has(key))) {
+ key = `${slice.label}-${count}`
+ count++
+ }
+ nextSuffix.set(slice.label, count)
+ usedKeys.add(key)
+ return {
+ key,
+ label: slice.label,
+ color: slice.color,
+ data: [slice.value],
+ }
+ })
}
+/** Pie charts can consume breakdown series totals directly, even when there isn't a matching
+ * breakdown x-axis to swap in like the line/bar path expects. */
+export const partOfWholeChartData = (
+ breakdown: BreakdownSeriesData<number | null>,
+ xData: AxisSeries<string> | null,
+ yData: AxisSeries<number | null>[]
+): { xData: AxisSeries<string> | null; yData: AxisSeries<number | null>[] | AxisBreakdownSeries<number | null>[] } => ({
+ xData: breakdown.xData.data.length ? breakdown.xData : xData,
+ yData: breakdown.seriesData.length ? breakdown.seriesData : yData,
+})
+
+export const showsLegendByDefault = (isProportionBar: boolean, partCount: number): boolean =>
+ isProportionBar && partCount <= MAX_DEFAULT_PROPORTION_LEGEND_PARTS
+
+/** The total is a sum-of-values readout, so it defaults on only when slices show values.
+ * `showPieTotal` is the legacy top-level toggle, honored for charts saved before `pie`. A proportion
+ * bar has no "show on slices" control, so a `sliceContent` left from a pie does not turn its total off. */
+export const showsPieTotal = (
+ chartSettings: Pick<ChartSettings, 'pie' | 'showPieTotal'>,
+ isProportionBar: boolean
+): boolean =>
+ chartSettings.pie?.showTotal ??
+ chartSettings.showPieTotal ??
+ (isProportionBar || (chartSettings.pie?.sliceContent ?? 'values') === 'values')
+
export const formatPieSliceCount = (
value: number,
total: number,
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlPartOfWholeChart.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlPartOfWholeChart.ts
new file mode 100644
index 000000000000..551acd180436
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlPartOfWholeChart.ts
@@ -0,0 +1,74 @@
+import { useCallback, useMemo, useState } from 'react'
+
+import type { ChartLegendConfig, ChartTheme, Series } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+import { useChartLegendSeriesMenu } from 'lib/components/ChartLegendSeriesMenu/useChartLegendSeriesMenu'
+
+import { ChartSettings } from '~/queries/schema/schema-general'
+
+import { AxisSeriesSettings } from '../../dataVisualizationLogic'
+import { SqlChartProps } from './SqlChart'
+import { formatSqlSeriesValue } from './sqlLineGraphAdapter'
+import { buildPieSeries, buildPieSlices, showsLegendByDefault, showsPieTotal } from './sqlPieGraphAdapter'
+
+export interface SqlPartOfWholeChart {
+ theme: ChartTheme
+ series: Series[]
+ legendConfig: ChartLegendConfig
+ total: number
+ showTotal: boolean
+ formattingSettings: AxisSeriesSettings | undefined
+ valueFormatter: (value: number) => string
+}
+
+/** The parts, legend, total and formatting a SQL pie, donut or proportion bar shares. */
+export function useSqlPartOfWholeChart(
+ { xData, yData, chartSettings }: Pick<SqlChartProps, 'xData' | 'yData'> & { chartSettings: ChartSettings },
+ isProportionBar: boolean
+): SqlPartOfWholeChart {
+ const theme = useChartTheme()
+ const series = useMemo(() => buildPieSeries(buildPieSlices(xData, yData)), [xData, yData])
+ const formattingSettings = yData[0]?.settings
+
+ // Toggled-off slices aren't persisted (SQL insights have nowhere to save them), but the legend
+ // is controlled anyway so the total and the tooltip shares track the slices actually drawn.
+ const [hiddenKeys, setHiddenKeys] = useState<string[]>([])
+ const showLegend = chartSettings.showLegend ?? showsLegendByDefault(isProportionBar, series.length)
+ const visibleHiddenKeySet = useMemo(() => new Set(showLegend ? hiddenKeys : []), [showLegend, hiddenKeys])
+ const total = useMemo(
+ () => series.reduce((sum, s) => (visibleHiddenKeySet.has(s.key) ? sum : sum + (s.data[0] ?? 0)), 0),
+ [series, visibleHiddenKeySet]
+ )
+
+ const valueFormatter = useCallback(
+ (value: number) => formatSqlSeriesValue(value, formattingSettings),
+ [formattingSettings]
+ )
+
+ const legendRenderItem = useChartLegendSeriesMenu({ surface: 'sql', seriesCount: series.length })
+
+ const legendConfig: ChartLegendConfig = useMemo(
+ () => ({
+ show: showLegend,
+ position: chartSettings.legendPosition ?? (isProportionBar ? 'bottom' : 'right'),
+ interactive: true,
+ hiddenKeys: showLegend ? hiddenKeys : [],
+ onToggleSeries: (key: string) =>
+ setHiddenKeys((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key])),
+ onSetHiddenSeries: setHiddenKeys,
+ renderItem: legendRenderItem,
+ }),
+ [showLegend, chartSettings.legendPosition, isProportionBar, hiddenKeys, legendRenderItem]
+ )
+
+ return {
+ theme,
+ series,
+ legendConfig,
+ total,
+ showTotal: showsPieTotal(chartSettings, isProportionBar),
+ formattingSettings,
+ valueFormatter,
+ }
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
index 19884c4e875e..ddef788e2ec4 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx
@@ -338,4 +338,44 @@ describe('DisplayTab', () => {
)
})
})
+
+ it.each([
+ [ChartDisplayType.ActionsPie, 'Show total below chart'],
+ [ChartDisplayType.ActionsDonut, 'Show total in center'],
+ [ChartDisplayType.ActionsProportionBar, 'Show total below chart'],
+ ])('honors the legacy top-level showPieTotal when pie.showTotal is unset (%s)', async (display, switchLabel) => {
+ initKeaTests()
+
+ const key = `display-tab-legacy-show-total-test-${display}`
+ const query: VisualizationNode = {
+ kind: NodeKind.DataVisualizationNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: 'select label, total from numbers(2)',
+ },
+ display,
+ chartSettings: { showPieTotal: false },
+ }
+
+ const props: DataVisualizationLogicProps = {
+ key,
+ query,
+ dataNodeCollectionId: key,
+ setQuery: jest.fn(),
+ }
+
+ dataVisualizationLogic(props).mount()
+ displayLogic({ key }).mount()
+
+ render(
+ <BindLogic logic={dataVisualizationLogic} props={props}>
+ <BindLogic logic={displayLogic} props={{ key }}>
+ <DisplayTab />
+ </BindLogic>
+ </BindLogic>
+ )
+
+ const toggle = (await screen.findByText(switchLabel)).closest('div')?.querySelector('[role="switch"]')
+ expect(toggle).toHaveAttribute('aria-checked', 'false')
+ })
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
index fb72be58251a..de20bd224e14 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
import { IconPlusSmall } from '@posthog/icons'
import {
@@ -21,13 +22,15 @@ import {
METRIC_SHOW_CHANGE_DEFAULT,
type MetricSummary,
} from 'lib/components/Metric/metricSummary'
-import { PIE_DISPLAY_TYPES } from 'lib/constants'
+import { PART_OF_WHOLE_DISPLAY_TYPES, PIE_DISPLAY_TYPES } from 'lib/constants'
import { ChartDisplayType } from '~/types'
import { dataVisualizationLogic } from '../dataVisualizationLogic'
import { displayLogic } from '../displayLogic'
+import { buildPieSlices, partOfWholeChartData, showsLegendByDefault, showsPieTotal } from './Charts/sqlPieGraphAdapter'
import { SQL_METRIC_SUMMARY_DEFAULT } from './Charts/useSqlMetricModel'
+import { seriesBreakdownLogic } from './seriesBreakdownLogic'
const PIE_SLICE_CONTENT_OPTIONS: { value: 'labels' | 'values' | 'none'; label: string }[] = [
{ value: 'labels', label: 'Labels' },
@@ -59,13 +62,24 @@ const LINE_STYLE_OPTIONS: { value: 'smooth' | 'linear'; label: string }[] = [
]
export const DisplayTab = (): JSX.Element => {
- const { effectiveVisualizationType, xData } = useValues(dataVisualizationLogic)
+ const { effectiveVisualizationType, xData, yData, dataVisualizationProps } = useValues(dataVisualizationLogic)
+ const { seriesBreakdownData } = useValues(seriesBreakdownLogic({ key: dataVisualizationProps.key }))
const { goalLines, chartSettings } = useValues(displayLogic)
const { addGoalLine, updateGoalLine, removeGoalLine, updateChartSettings } = useActions(displayLogic)
const isStackedBarChart = effectiveVisualizationType === ChartDisplayType.ActionsStackedBar
const isPieChart = PIE_DISPLAY_TYPES.includes(effectiveVisualizationType)
const isDonutChart = effectiveVisualizationType === ChartDisplayType.ActionsDonut
+ const isProportionBar = effectiveVisualizationType === ChartDisplayType.ActionsProportionBar
+ const isPartOfWholeChart = PART_OF_WHOLE_DISPLAY_TYPES.includes(effectiveVisualizationType)
+ const proportionBarPartCount = useMemo(() => {
+ if (!isProportionBar) {
+ return 0
+ }
+ const pieData = partOfWholeChartData(seriesBreakdownData, xData, yData)
+ return buildPieSlices(pieData.xData, pieData.yData).length
+ }, [isProportionBar, seriesBreakdownData, xData, yData])
+ const showLegend = chartSettings.showLegend ?? showsLegendByDefault(isProportionBar, proportionBarPartCount)
const isScatterPlot = effectiveVisualizationType === ChartDisplayType.ScatterPlot
const isBoxPlot = effectiveVisualizationType === ChartDisplayType.BoxPlot
const isMetric = effectiveVisualizationType === ChartDisplayType.Metric
@@ -246,7 +260,7 @@ export const DisplayTab = (): JSX.Element => {
<LemonSwitch
className="flex-1 w-full"
label="Show legend"
- checked={chartSettings.showLegend ?? false}
+ checked={showLegend}
onChange={(value) => {
updateChartSettings({ showLegend: value })
}}
@@ -255,12 +269,13 @@ export const DisplayTab = (): JSX.Element => {
<LemonLabel>Legend position</LemonLabel>
<LemonSelect
className="w-full"
- value={chartSettings.legendPosition ?? (isPieChart ? 'right' : 'top')}
+ value={
+ chartSettings.legendPosition ??
+ (isProportionBar ? 'bottom' : isPieChart ? 'right' : 'top')
+ }
options={LEGEND_POSITION_OPTIONS}
disabledReason={
- chartSettings.showLegend
- ? undefined
- : 'Turn the legend on to set its position'
+ showLegend ? undefined : 'Turn the legend on to set its position'
}
onChange={(value) => updateChartSettings({ legendPosition: value })}
fullWidth
@@ -287,39 +302,40 @@ export const DisplayTab = (): JSX.Element => {
}}
/>
)}
- {isPieChart ? (
+ {isPartOfWholeChart ? (
<>
- <div className="flex flex-col gap-1">
- <LemonLabel>Show on slices</LemonLabel>
- <LemonSegmentedButton
- className="w-full"
- value={chartSettings.pie?.sliceContent ?? 'values'}
- onChange={(value) =>
- updateChartSettings({ pie: { sliceContent: value } })
- }
- options={PIE_SLICE_CONTENT_OPTIONS}
- fullWidth
- />
- </div>
- <div className="flex flex-col gap-1">
- <LemonLabel>Show values as</LemonLabel>
- <LemonSegmentedButton
- className="w-full"
- value={chartSettings.pie?.valueDisplay ?? 'absolute'}
- onChange={(value) =>
- updateChartSettings({ pie: { valueDisplay: value } })
- }
- options={PIE_VALUE_DISPLAY_OPTIONS}
- fullWidth
- />
- </div>
+ {isPieChart && (
+ <>
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Show on slices</LemonLabel>
+ <LemonSegmentedButton
+ className="w-full"
+ value={chartSettings.pie?.sliceContent ?? 'values'}
+ onChange={(value) =>
+ updateChartSettings({ pie: { sliceContent: value } })
+ }
+ options={PIE_SLICE_CONTENT_OPTIONS}
+ fullWidth
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Show values as</LemonLabel>
+ <LemonSegmentedButton
+ className="w-full"
+ value={chartSettings.pie?.valueDisplay ?? 'absolute'}
+ onChange={(value) =>
+ updateChartSettings({ pie: { valueDisplay: value } })
+ }
+ options={PIE_VALUE_DISPLAY_OPTIONS}
+ fullWidth
+ />
+ </div>
+ </>
+ )}
<LemonSwitch
className="flex-1 w-full"
label={isDonutChart ? 'Show total in center' : 'Show total below chart'}
- checked={
- chartSettings.pie?.showTotal ??
- (chartSettings.pie?.sliceContent ?? 'values') === 'values'
- }
+ checked={showsPieTotal(chartSettings, isProportionBar)}
onChange={(value) => {
updateChartSettings({ pie: { showTotal: value } })
}}
@@ -473,7 +489,7 @@ export const DisplayTab = (): JSX.Element => {
),
}
: null,
- !isPieChart
+ !isPartOfWholeChart
? {
key: 'left-y-axis',
header: isHorizontalBarChart ? 'X-axis' : supportsRightYAxis ? 'Left Y-axis' : 'Y-axis',
@@ -481,7 +497,7 @@ export const DisplayTab = (): JSX.Element => {
content: renderYAxisSettings('leftYAxisSettings'),
}
: null,
- !isPieChart && supportsRightYAxis
+ !isPartOfWholeChart && supportsRightYAxis
? {
key: 'right-y-axis',
header: 'Right Y-axis',
@@ -506,7 +522,7 @@ export const DisplayTab = (): JSX.Element => {
),
}
: null,
- !isPieChart && !isSingleAxisChart
+ !isPartOfWholeChart && !isSingleAxisChart
? {
key: 'goals',
header: (
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.test.tsx
index dc1493ea768d..ab2a45819059 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.test.tsx
@@ -1,19 +1,152 @@
import '@testing-library/jest-dom'
-import { render, screen, waitFor } from '@testing-library/react'
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { BindLogic } from 'kea'
-import { VisualizationNode, NodeKind } from '~/queries/schema/schema-general'
+import { HogQLQueryResponse, VisualizationNode, NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { ChartDisplayType } from '~/types'
import { dataNodeLogic } from '../../DataNode/dataNodeLogic'
import { DataVisualizationLogicProps, dataVisualizationLogic } from '../dataVisualizationLogic'
-import { YSeriesDisplayTab, YSeriesFormattingTab } from './SeriesTab'
+import { SeriesTab, YSeriesDisplayTab, YSeriesFormattingTab } from './SeriesTab'
import { YSeriesLogicProps } from './ySeriesLogic'
+const renderPartOfWholeSeriesTab = (
+ display: ChartDisplayType,
+ xAxis: { column: string } | undefined,
+ valueColumns: string[],
+ seriesBreakdownColumn?: string,
+ rows: unknown[][] = [['Mon', 3, 5, 'US']]
+): ReturnType<typeof render> => {
+ initKeaTests()
+ const cachedResults: HogQLQueryResponse = {
+ results: rows,
+ columns: ['day', 'signups', 'logins', 'country'],
+ types: [
+ ['day', 'String'],
+ ['signups', 'Float64'],
+ ['logins', 'Float64'],
+ ['country', 'String'],
+ ],
+ }
+ const query: VisualizationNode = {
+ kind: NodeKind.DataVisualizationNode,
+ source: { kind: NodeKind.HogQLQuery, query: 'select day, signups, logins, country from daily' },
+ display,
+ chartSettings: { xAxis, yAxis: valueColumns.map((column) => ({ column })), seriesBreakdownColumn },
+ }
+ const props: DataVisualizationLogicProps = {
+ key: `series-tab-part-of-whole-${display}-${!!xAxis}-${valueColumns.length}-${seriesBreakdownColumn}-${rows.length}`,
+ query,
+ cachedResults,
+ dataNodeCollectionId: 'series-tab-part-of-whole',
+ setQuery: jest.fn(),
+ }
+ dataNodeLogic({
+ key: props.key,
+ query: query.source,
+ cachedResults,
+ dataNodeCollectionId: props.dataNodeCollectionId,
+ }).mount()
+ dataVisualizationLogic(props).mount()
+
+ return render(
+ <BindLogic logic={dataVisualizationLogic} props={props}>
+ <SeriesTab />
+ </BindLogic>
+ )
+}
+
describe('SeriesTab', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it.each([
+ {
+ name: 'lists every value column for a proportion bar with no label column',
+ display: ChartDisplayType.ActionsProportionBar,
+ xAxis: undefined,
+ valueColumns: ['signups', 'logins'],
+ listsEveryValueColumn: true,
+ labelDisabled: true,
+ },
+ {
+ name: 'lists every value column and disables the label when several value columns ignore it',
+ display: ChartDisplayType.ActionsProportionBar,
+ xAxis: { column: 'day' },
+ valueColumns: ['signups', 'logins'],
+ listsEveryValueColumn: true,
+ labelDisabled: true,
+ },
+ {
+ name: 'picks one value column for a proportion bar grouped by a label column',
+ display: ChartDisplayType.ActionsProportionBar,
+ xAxis: { column: 'day' },
+ valueColumns: ['signups'],
+ listsEveryValueColumn: false,
+ labelDisabled: false,
+ },
+ {
+ name: 'lists the breakdown parts and disables the label when a breakdown ignores it',
+ display: ChartDisplayType.ActionsProportionBar,
+ xAxis: { column: 'day' },
+ valueColumns: ['signups'],
+ seriesBreakdownColumn: 'country',
+ listsEveryValueColumn: true,
+ labelDisabled: true,
+ },
+ {
+ name: 'lists every value column for a pie with several value columns',
+ display: ChartDisplayType.ActionsPie,
+ xAxis: { column: 'day' },
+ valueColumns: ['signups', 'logins'],
+ listsEveryValueColumn: true,
+ labelDisabled: true,
+ },
+ {
+ name: 'picks one value column for a pie grouped by a label column',
+ display: ChartDisplayType.ActionsPie,
+ xAxis: { column: 'day' },
+ valueColumns: ['signups'],
+ listsEveryValueColumn: false,
+ labelDisabled: false,
+ },
+ ])('$name', ({ display, xAxis, valueColumns, seriesBreakdownColumn, listsEveryValueColumn, labelDisabled }) => {
+ const { container } = renderPartOfWholeSeriesTab(display, xAxis, valueColumns, seriesBreakdownColumn)
+
+ expect(screen.queryAllByText('Values').length > 0).toBe(listsEveryValueColumn)
+ expect(container.querySelector('[data-attr="part-of-whole-label-column"]')?.getAttribute('aria-disabled')).toBe(
+ String(labelDisabled)
+ )
+ expect(container.querySelector('[title="Delete series breakdown"]') !== null).toBe(!!seriesBreakdownColumn)
+ })
+
+ it('keeps a selected breakdown removable when the results have no rows', () => {
+ const { container } = renderPartOfWholeSeriesTab(
+ ChartDisplayType.ActionsProportionBar,
+ { column: 'day' },
+ ['signups'],
+ 'country',
+ []
+ )
+
+ expect(container.querySelector('[title="Delete series breakdown"]')).not.toBeNull()
+ })
+
+ it('lets each value column of a part-of-whole chart edit its label and color', async () => {
+ const { container } = renderPartOfWholeSeriesTab(ChartDisplayType.ActionsProportionBar, undefined, [
+ 'signups',
+ 'logins',
+ ])
+
+ await userEvent.click(container.querySelector<HTMLElement>('[data-attr="y-series-settings"]')!)
+
+ expect(await screen.findByText('Display')).toBeInTheDocument()
+ })
+
it('persists table column formatting changes immediately', async () => {
initKeaTests()
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsx b/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsx
index dd1f6f800c86..ef893ab00a13 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsx
@@ -19,7 +19,7 @@ import {
} from '@posthog/lemon-ui'
import { DataColorToken, getSeriesColor, getSeriesColorPalette } from 'lib/colors'
-import { PIE_DISPLAY_TYPES } from 'lib/constants'
+import { PART_OF_WHOLE_DISPLAY_TYPES } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { dataThemeLogic } from 'scenes/dataThemeLogic'
import { INSIGHT_UNIT_OPTIONS_SHORT } from 'scenes/insights/aggregationAxisFormat'
@@ -29,6 +29,7 @@ import { ChartDisplayType } from '~/types'
import { AxisSeries, Column, dataVisualizationLogic } from '../dataVisualizationLogic'
import { BoxPlotSeriesTab } from './BoxPlotSeriesTab'
+import { drawsOnePartPerSeries, isBreakdownSeries, partOfWholeChartData } from './Charts/sqlPieGraphAdapter'
import { HeatmapSeriesTab } from './Heatmap/HeatmapSeriesTab'
import { AxisBreakdownSeries, BREAKDOWN_LIMIT_LABEL, seriesBreakdownLogic } from './seriesBreakdownLogic'
import { getAvailableSeriesBreakdownColumns } from './seriesBreakdownUtils'
@@ -52,7 +53,7 @@ export const SeriesTab = (): JSX.Element => {
const { updateXSeries, addYSeries, updateSeriesIndex, deleteYSeries, setTransposeResults } =
useActions(dataVisualizationLogic)
const breakdownLogic = seriesBreakdownLogic({ key: dataVisualizationProps.key })
- const { selectedSeriesBreakdownColumn, showSeriesBreakdown } = useValues(breakdownLogic)
+ const { selectedSeriesBreakdownColumn, showSeriesBreakdown, seriesBreakdownData } = useValues(breakdownLogic)
const { addSeriesBreakdown } = useActions(breakdownLogic)
const isScatterPlot = effectiveVisualizationType === ChartDisplayType.ScatterPlot
@@ -119,7 +120,9 @@ export const SeriesTab = (): JSX.Element => {
// 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 (PIE_DISPLAY_TYPES.includes(effectiveVisualizationType)) {
+ if (PART_OF_WHOLE_DISPLAY_TYPES.includes(effectiveVisualizationType)) {
+ const parts = partOfWholeChartData(seriesBreakdownData, xData, yData)
+ const breakdownSplitsValue = parts.yData.some(isBreakdownSeries)
const valueColumn = selectedYAxis?.find((series) => series !== null)?.name ?? null
const valueOptions = numericalColumns.map(({ name, type }) => ({
value: name,
@@ -153,7 +156,16 @@ export const SeriesTab = (): JSX.Element => {
className="w-full"
value={xData !== null ? xData.column.name : 'None'}
options={options}
- disabledReason={responseLoading ? 'Query loading...' : undefined}
+ disabledReason={
+ responseLoading
+ ? 'Query loading...'
+ : yData.length > 1
+ ? 'A label splits one value column. Remove the other values to use it.'
+ : breakdownSplitsValue
+ ? 'The breakdown already splits the value. Remove the breakdown to use a label.'
+ : undefined
+ }
+ data-attr="part-of-whole-label-column"
onChange={(value) => {
const column = columns.find((n) => n.name === value)
if (column) {
@@ -162,19 +174,27 @@ export const SeriesTab = (): JSX.Element => {
}}
/>
- <LemonLabel className="mt-4 mb-1">Value</LemonLabel>
- <LemonSelect
- className="w-full"
- placeholder="Select a column"
- value={valueColumn}
- options={valueOptions}
- disabledReason={responseLoading ? 'Query loading...' : undefined}
- onChange={(value) => {
- if (value) {
- setValueColumn(value)
- }
- }}
- />
+ {selectedSeriesBreakdownColumn && <SeriesBreakdownSelector />}
+
+ {drawsOnePartPerSeries(parts.xData, parts.yData) ? (
+ <YSeriesList label="Values" addLabel="Add value" showAdd={!hideAddYSeries} />
+ ) : (
+ <>
+ <LemonLabel className="mt-4 mb-1">Value</LemonLabel>
+ <LemonSelect
+ className="w-full"
+ placeholder="Select a column"
+ value={valueColumn}
+ options={valueOptions}
+ disabledReason={responseLoading ? 'Query loading...' : undefined}
+ onChange={(value) => {
+ if (value) {
+ setValueColumn(value)
+ }
+ }}
+ />
+ </>
+ )}
</div>
)
}
@@ -207,11 +227,22 @@ export const SeriesTab = (): JSX.Element => {
)}
{showSeriesBreakdownSelector && <SeriesBreakdownSelector />}
- <LemonLabel className="mt-4 mb-1">Y-axis</LemonLabel>
+ <YSeriesList label="Y-axis" addLabel="Add Y-series" showAdd={!hideAddYSeries} />
+ </div>
+ )
+}
+
+function YSeriesList({ label, addLabel, showAdd }: { label: string; addLabel: string; showAdd: boolean }): JSX.Element {
+ const { yData } = useValues(dataVisualizationLogic)
+ const { addYSeries } = useActions(dataVisualizationLogic)
+
+ return (
+ <>
+ <LemonLabel className="mt-4 mb-1">{label}</LemonLabel>
{yData.map((series, index) => (
<YSeries series={series} index={index} key={`${series?.column.name}-${index}`} />
))}
- {!hideAddYSeries && (
+ {showAdd && (
<LemonButton
className="mt-1"
type="tertiary"
@@ -219,10 +250,10 @@ export const SeriesTab = (): JSX.Element => {
icon={<IconPlusSmall />}
fullWidth
>
- Add Y-series
+ {addLabel}
</LemonButton>
)}
- </div>
+ </>
)
}
@@ -284,14 +315,8 @@ const SeriesSelectLabel = ({
}
const YSeries = ({ series, index }: { series: AxisSeries<number | null>; index: number }): JSX.Element => {
- const {
- columns,
- numericalColumns,
- responseLoading,
- dataVisualizationProps,
- showTableSettings,
- effectiveVisualizationType,
- } = useValues(dataVisualizationLogic)
+ const { columns, numericalColumns, responseLoading, dataVisualizationProps, showTableSettings } =
+ useValues(dataVisualizationLogic)
const { updateSeriesIndex, deleteYSeries } = useActions(dataVisualizationLogic)
const { selectedSeriesBreakdownColumn } = useValues(seriesBreakdownLogic({ key: dataVisualizationProps.key }))
@@ -301,7 +326,6 @@ const YSeries = ({ series, index }: { series: AxisSeries<number | null>; index:
const { isSettingsOpen, canOpenSettings, activeSettingsTab } = useValues(seriesLogic)
const { setSettingsOpen, submitFormatting, submitDisplay, setSettingsTab } = useActions(seriesLogic)
- const isPieChart = PIE_DISPLAY_TYPES.includes(effectiveVisualizationType)
const seriesColor = series.settings?.display?.color ?? getSeriesColor(index)
const showSeriesColor = !showTableSettings && !selectedSeriesBreakdownColumn
@@ -336,19 +360,11 @@ const YSeries = ({ series, index }: { series: AxisSeries<number | null>; index:
),
}))
- const settingsTabs = isPieChart
- ? [
- {
- label: Y_SERIES_SETTINGS_TABS[YSeriesSettingsTab.Formatting].label,
- key: YSeriesSettingsTab.Formatting,
- content: <YSeriesFormattingTab ySeriesLogicProps={seriesLogicProps} />,
- },
- ]
- : Object.values(Y_SERIES_SETTINGS_TABS).map(({ label, Component }, index) => ({
- label: label,
- key: Object.keys(Y_SERIES_SETTINGS_TABS)[index],
- content: <Component ySeriesLogicProps={seriesLogicProps} />,
- }))
+ const settingsTabs = Object.values(Y_SERIES_SETTINGS_TABS).map(({ label, Component }, index) => ({
+ label: label,
+ key: Object.keys(Y_SERIES_SETTINGS_TABS)[index],
+ content: <Component ySeriesLogicProps={seriesLogicProps} />,
+ }))
return (
<div className="flex gap-1 mb-1">
@@ -387,6 +403,7 @@ const YSeries = ({ series, index }: { series: AxisSeries<number | null>; index:
key="seriesSettings"
icon={<IconGear />}
noPadding
+ data-attr="y-series-settings"
onClick={() => setSettingsOpen(true)}
disabledReason={!canOpenSettings && 'Select a column first'}
/>
@@ -504,7 +521,7 @@ export const YSeriesDisplayTab = ({ ySeriesLogicProps }: { ySeriesLogicProps: YS
const { selectedSeriesBreakdownColumn } = useValues(seriesBreakdownLogic({ key: dataVisualizationProps.key }))
const { updateSeriesIndex } = useActions(dataVisualizationLogic)
- const isPieChart = PIE_DISPLAY_TYPES.includes(effectiveVisualizationType)
+ const isPieChart = PART_OF_WHOLE_DISPLAY_TYPES.includes(effectiveVisualizationType)
const hideChartSpecificOptions =
isPieChart ||
effectiveVisualizationType === ChartDisplayType.ActionsBarValue ||
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
index 421467499ecb..90229b80dc51 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
@@ -4,11 +4,21 @@ import { IconGraph, IconLifecycle, IconPieChart, IconScatter, IconTrends } from
import { LemonSelect, LemonSelectOptions, LemonSelectProps } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
-import { Icon123, IconAreaChart, IconDonutChart, IconHeatmap, IconTableChart, IconTrendingUp } from 'lib/lemon-ui/icons'
+import {
+ Icon123,
+ IconAreaChart,
+ IconDonutChart,
+ IconHeatmap,
+ IconProportionBarChart,
+ IconTableChart,
+ IconTrendingUp,
+} from 'lib/lemon-ui/icons'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { ChartDisplayType } from '~/types'
+import { offersProportionBar } from 'products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions'
+
import { Column, dataVisualizationLogic } from '../dataVisualizationLogic'
const DISPLAY_TYPE_LABELS: Record<ChartDisplayType, string> = {
@@ -50,7 +60,8 @@ export function getTableDisplayOptions(
numericalColumns: Column[],
autoVisualizationType: ChartDisplayType,
disabledReasonFor?: (displayType: ChartDisplayType) => string | undefined,
- metricInsightEnabled = false
+ metricInsightEnabled = false,
+ proportionBarEnabled = false
): LemonSelectOptions<ChartDisplayType> {
const canDisplayContinuousChart = columns.length > 1 && numericalColumns.length > 0
const canDisplayScatterPlot = numericalColumns.length > 1
@@ -134,12 +145,26 @@ export function getTableDisplayOptions(
value: ChartDisplayType.ActionsPie,
icon: <IconPieChart />,
label: 'Pie chart',
+ disabledReason: !numericalColumns.length ? 'Requires at least one numeric column' : undefined,
},
{
value: ChartDisplayType.ActionsDonut,
icon: <IconDonutChart />,
label: 'Donut chart',
+ disabledReason: !numericalColumns.length ? 'Requires at least one numeric column' : undefined,
},
+ ...(proportionBarEnabled
+ ? [
+ {
+ value: ChartDisplayType.ActionsProportionBar,
+ icon: <IconProportionBarChart />,
+ label: 'Proportion bar',
+ disabledReason: !numericalColumns.length
+ ? 'Requires at least one numeric column'
+ : undefined,
+ },
+ ]
+ : []),
{
value: ChartDisplayType.ScatterPlot,
icon: <IconScatter />,
@@ -210,7 +235,8 @@ export const TableDisplay = ({
numericalColumns,
autoVisualizationType,
disabledReasonFor,
- !!featureFlags[FEATURE_FLAGS.METRIC_INSIGHT]
+ !!featureFlags[FEATURE_FLAGS.METRIC_INSIGHT],
+ offersProportionBar(!!featureFlags[FEATURE_FLAGS.PROPORTION_BAR_CHART], visualizationType)
)}
renderButtonContent={() => renderDisplayTypeLabel(visualizationType, autoVisualizationType)}
size="small"
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index d5fec248020d..31d403b26466 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -7,7 +7,7 @@ import { IconGear } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonDivider } from '@posthog/lemon-ui'
import { ExportButton } from 'lib/components/ExportButton/ExportButton'
-import { PIE_DISPLAY_TYPES } from 'lib/constants'
+import { PART_OF_WHOLE_DISPLAY_TYPES } from 'lib/constants'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { InsightErrorState, StatelessInsightLoadingState } from 'scenes/insights/EmptyStates'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
@@ -42,11 +42,12 @@ import { DateRange } from '../DataNode/DateRange'
import { ElapsedTime } from '../DataNode/ElapsedTime'
import { Reload } from '../DataNode/Reload'
import { QueryFeature } from '../DataTable/queryFeatures'
-import { PieChart } from './Components/Charts/PieChart'
+import { PartOfWholeChart } from './Components/Charts/PartOfWholeChart'
import { SqlBoxPlot } from './Components/Charts/SqlBoxPlot'
import { isSqlChartVisualizationType, SqlChart } from './Components/Charts/SqlChart'
import { getSeriesKey } from './Components/Charts/sqlLineGraphAdapter'
import { SqlMetricCard } from './Components/Charts/SqlMetricCard'
+import { partOfWholeChartData } from './Components/Charts/sqlPieGraphAdapter'
import { SqlScatterGraph } from './Components/Charts/SqlScatterGraph'
import { TwoDimensionalHeatmap } from './Components/Heatmap/TwoDimensionalHeatmap'
import { seriesBreakdownLogic } from './Components/seriesBreakdownLogic'
@@ -351,17 +352,14 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
/>
</BindLogic>
)
- } else if (PIE_DISPLAY_TYPES.includes(effectiveVisualizationType)) {
- const _xData = seriesBreakdownData.xData.data.length ? seriesBreakdownData.xData : xData
- // Pie charts can consume breakdown series totals directly, even when there isn't
- // a matching breakdown x-axis to swap in like the line/bar path expects.
- const _yData = seriesBreakdownData.seriesData.length ? seriesBreakdownData.seriesData : yData
+ } else if (PART_OF_WHOLE_DISPLAY_TYPES.includes(effectiveVisualizationType)) {
+ const pieData = partOfWholeChartData(seriesBreakdownData, xData, yData)
component = (
- <PieChart
+ <PartOfWholeChart
className="p-3"
- xData={_xData}
- yData={_yData}
+ xData={pieData.xData}
+ yData={pieData.yData}
visualizationType={effectiveVisualizationType}
chartSettings={chartSettings}
presetChartHeight={presetChartHeight}
diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts
index 774b4b487dda..fbb99182dc64 100644
--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts
@@ -553,6 +553,56 @@ describe('dataVisualizationLogic', () => {
})
})
+ it.each([ChartDisplayType.ActionsProportionBar, ChartDisplayType.ActionsPie])(
+ 'gives a numeric x-axis back to the values when %s draws one part per column',
+ async (displayType) => {
+ dataNodeLogic({ key: testKey, query: defaultQuery.source, dataNodeCollectionId }).actions.setResponse({
+ columns: ['signups', 'logins', 'purchases'],
+ types: [
+ ['signups', 'Int64'],
+ ['logins', 'Int64'],
+ ['purchases', 'Int64'],
+ ],
+ results: [[1, 2, 3]],
+ })
+ logic.actions.setVisualizationType(ChartDisplayType.ActionsLineGraph)
+ await expectLogic(logic).toMatchValues({ selectedXAxis: 'signups' })
+
+ logic.actions.setVisualizationType(displayType)
+
+ await expectLogic(logic).toMatchValues({
+ selectedXAxis: null,
+ selectedYAxis: [
+ expect.objectContaining({ name: 'signups' }),
+ expect.objectContaining({ name: 'logins' }),
+ expect.objectContaining({ name: 'purchases' }),
+ ],
+ })
+ }
+ )
+
+ it('keeps the x-axis a series breakdown needs when a part-of-whole chart is picked', async () => {
+ dataNodeLogic({ key: testKey, query: defaultQuery.source, dataNodeCollectionId }).actions.setResponse({
+ columns: ['week', 'signups', 'logins', 'country'],
+ types: [
+ ['week', 'Int64'],
+ ['signups', 'Int64'],
+ ['logins', 'Int64'],
+ ['country', 'String'],
+ ],
+ results: [[1, 2, 3, 'US']],
+ })
+ logic.actions.updateChartSettings({
+ xAxis: { column: 'week' },
+ yAxis: [{ column: 'signups' }, { column: 'logins' }],
+ seriesBreakdownColumn: 'country',
+ })
+
+ logic.actions.setVisualizationType(ChartDisplayType.ActionsProportionBar)
+
+ await expectLogic(logic).toMatchValues({ selectedXAxis: 'week' })
+ })
+
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'],
diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
index 92e15fb23668..ce3d85295738 100644
--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
@@ -18,7 +18,7 @@ import { subscriptions } from 'kea-subscriptions'
import mergeObject from 'lodash.merge'
import posthog from 'posthog-js'
-import { PIE_DISPLAY_TYPES } from 'lib/constants'
+import { PART_OF_WHOLE_DISPLAY_TYPES, PIE_DISPLAY_TYPES } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import type { execHog } from 'lib/hog'
import { RGBToHex, lightenDarkenColor } from 'lib/utils/colors'
@@ -567,6 +567,21 @@ export function applyVisualizationType(
yAxis = yAxis.slice(0, 1)
}
+ // With several values a part-of-whole chart draws one part per column and ignores the x-axis, so a
+ // numeric column a line or scatter chart moved onto the x-axis goes back to the values. A series
+ // breakdown still needs the x-axis, so it stays then.
+ const numericXAxisColumn = numericalColumns.find((column) => column.name === selectedXAxis)
+ if (
+ PART_OF_WHOLE_DISPLAY_TYPES.includes(visualizationType) &&
+ !chartSettings.seriesBreakdownColumn &&
+ yAxis.length > 1 &&
+ numericXAxisColumn &&
+ !yAxis.some((series) => series.column === numericXAxisColumn.name)
+ ) {
+ yAxis = [{ column: numericXAxisColumn.name, settings: DefaultAxisSettings() }, ...yAxis]
+ chartSettings.xAxis = undefined
+ }
+
if (
[ChartDisplayType.ActionsLineGraph, ChartDisplayType.ActionsAreaGraph].includes(visualizationType) &&
shouldUseFirstNumericColumnAsContinuousChartXAxis(columns, numericalColumns, selectedXAxis, selectedYAxis)
diff --git a/frontend/src/queries/nodes/DataVisualization/sqlVisualizationSupport.ts b/frontend/src/queries/nodes/DataVisualization/sqlVisualizationSupport.ts
index 5e7bc12072b3..48f5c87f1259 100644
--- a/frontend/src/queries/nodes/DataVisualization/sqlVisualizationSupport.ts
+++ b/frontend/src/queries/nodes/DataVisualization/sqlVisualizationSupport.ts
@@ -1,3 +1,5 @@
+import { PART_OF_WHOLE_DISPLAY_TYPES } from 'lib/constants'
+
import { ChartDisplayType } from '~/types'
import { Column, applyVisualizationType } from './dataVisualizationLogic'
@@ -50,7 +52,13 @@ export function sqlVisualizationDisabledReason(
const nextQuery = applyVisualizationType(query, displayType, columns, rowCount)
const hasYAxis = !!nextQuery.chartSettings?.yAxis?.length
- if (hasYAxis && (drawnAs === ChartDisplayType.Metric || nextQuery.chartSettings?.xAxis)) {
+ // A pie, donut or proportion bar draws one part per numeric column, so like `Metric` it needs no X-axis column.
+ if (
+ hasYAxis &&
+ (drawnAs === ChartDisplayType.Metric ||
+ PART_OF_WHOLE_DISPLAY_TYPES.includes(drawnAs) ||
+ nextQuery.chartSettings?.xAxis)
+ ) {
return undefined
}
diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
index 0dfd0223174a..5beb0e64fca9 100644
--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx
@@ -37,7 +37,7 @@ import { MCPUseCaseCard } from 'lib/components/MCPHint/MCPUseCaseCard'
import { Resizer } from 'lib/components/Resizer/Resizer'
import { type ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
import { TZLabel } from 'lib/components/TZLabel'
-import { PIE_DISPLAY_TYPES } from 'lib/constants'
+import { PART_OF_WHOLE_DISPLAY_TYPES } from 'lib/constants'
import { useCellCopyContextMenu } from 'lib/hooks/useCellCopyContextMenu'
import { IconTableChart } from 'lib/lemon-ui/icons'
import { Link } from 'lib/lemon-ui/Link'
@@ -56,10 +56,11 @@ import { ElapsedTime } from '~/queries/nodes/DataNode/ElapsedTime'
import { LoadPreviewText } from '~/queries/nodes/DataNode/LoadNext'
import { QueryExecutionDetails } from '~/queries/nodes/DataNode/QueryExecutionDetails'
import { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'
-import { PieChart } from '~/queries/nodes/DataVisualization/Components/Charts/PieChart'
+import { PartOfWholeChart } from '~/queries/nodes/DataVisualization/Components/Charts/PartOfWholeChart'
import { SqlBoxPlot } from '~/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot'
import { isSqlChartVisualizationType, SqlChart } from '~/queries/nodes/DataVisualization/Components/Charts/SqlChart'
import { SqlMetricCard } from '~/queries/nodes/DataVisualization/Components/Charts/SqlMetricCard'
+import { partOfWholeChartData } from '~/queries/nodes/DataVisualization/Components/Charts/sqlPieGraphAdapter'
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'
@@ -1085,15 +1086,14 @@ function InternalDataTableVisualization(
/>
</BindLogic>
)
- } else if (PIE_DISPLAY_TYPES.includes(effectiveVisualizationType)) {
- const _xData = seriesBreakdownData.xData.data.length ? seriesBreakdownData.xData : xData
- const _yData = seriesBreakdownData.seriesData.length ? seriesBreakdownData.seriesData : yData
+ } else if (PART_OF_WHOLE_DISPLAY_TYPES.includes(effectiveVisualizationType)) {
+ const pieData = partOfWholeChartData(seriesBreakdownData, xData, yData)
component = (
- <PieChart
+ <PartOfWholeChart
className="p-2"
- xData={_xData}
- yData={_yData}
+ xData={pieData.xData}
+ yData={pieData.yData}
visualizationType={effectiveVisualizationType}
chartSettings={chartSettings}
presetChartHeight={presetChartHeight}