:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(insights): render aggregated bar breakdowns as one per-bar-colored series (#61277)
Sam Pennington1f76c3170874
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsxindex 7005ed8a47a8..100e3be878af 100644--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx@@ -16,6 +16,7 @@ import {} from '../../core/canvas-renderer'import { Chart } from '../../core/Chart'import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'+import { barColorAt } from '../../core/color-utils'import { DEFAULT_MARGINS, X_AXIS_TITLE_MARGIN } from '../../core/hooks/useChartMargins'import { useLatest } from '../../core/hooks/useLatest'import {@@ -557,8 +558,8 @@ function BarChartInner<Meta = unknown>({}for (const { series: s, bar, isTrackHighlight } of items) {if (isTrackHighlight) {- const parsed = d3.color(s.color)- // Always translucent — `s.color` direct would paint an opaque full-height+ const parsed = d3.color(barColorAt(s, bar.dataIndex))+ // Always translucent — the bar color direct would paint an opaque full-height// block if d3 can't parse the color.let trackColor: stringif (parsed) {@@ -574,7 +575,8 @@ function BarChartInner<Meta = unknown>({highlightRadius)} else {- const highlightColor = d3.color(s.color)?.darker(0.6).toString() ?? s.color+ const barColor = barColorAt(s, bar.dataIndex)+ const highlightColor = d3.color(barColor)?.darker(0.6).toString() ?? barColordrawBarHighlight(ctx, bar, highlightColor, highlightRadius)}}diff --git a/frontend/src/lib/hog-charts/core/bar-canvas-renderer.test.ts b/frontend/src/lib/hog-charts/core/bar-canvas-renderer.test.tsindex 740cfaae2017..8425995b944a 100644--- a/frontend/src/lib/hog-charts/core/bar-canvas-renderer.test.ts+++ b/frontend/src/lib/hog-charts/core/bar-canvas-renderer.test.ts@@ -142,6 +142,35 @@ describe('hog-charts canvas-renderer (bars)', () => {expect(ctx.fillStyle).toBe('#abcdef')})+ it('uses per-bar colors from bars[i].color, falling back to series.color where absent', () => {+ const ctx = mockCanvasContext()+ const drawCtx = makeDrawContext(ctx, ['a', 'b', 'c'])+ const series = makeSeries({+ key: 's',+ data: [1, 2, 3],+ color: '#000000',+ bars: [{ color: '#ff0000' }, {}, { color: '#0000ff' }],+ })+ const seen: (string | CanvasPattern)[] = []+ const original = Object.getOwnPropertyDescriptor(ctx, 'fillStyle')+ Object.defineProperty(ctx, 'fillStyle', {+ set(v: string | CanvasPattern) {+ seen.push(v)+ },+ configurable: true,+ })+ try {+ drawBars(drawCtx, series, [+ bar({ x: 0, dataIndex: 0 }),+ bar({ x: 60, dataIndex: 1 }),+ bar({ dataIndex: 2 }),+ ])+ } finally {+ Object.defineProperty(ctx, 'fillStyle', original!)+ }+ expect(seen).toEqual(['#ff0000', '#000000', '#0000ff'])+ })+it('fills all bars when partial fromIndex is set (some hatched, some solid)', () => {// The hatch pattern cache is module-level keyed by color; we verify the bar count// rather than whether createPattern was invoked, since prior tests may have warmed the cache.diff --git a/frontend/src/lib/hog-charts/core/canvas-renderer.ts b/frontend/src/lib/hog-charts/core/canvas-renderer.tsindex 1bfd74196f15..2dc60f82f85e 100644--- a/frontend/src/lib/hog-charts/core/canvas-renderer.ts+++ b/frontend/src/lib/hog-charts/core/canvas-renderer.ts@@ -1,5 +1,6 @@import * as d3 from 'd3'+import { barColorAt } from './color-utils'import { yTickCountForHeight } from './scales'import type { ChartDimensions, ChartDrawArgs, DrawHoverResult, ResolvedSeries } from './types'@@ -510,7 +511,7 @@ export function drawBars(const useHatch =hatch !== null &&((dashedFrom !== null && bar.dataIndex >= dashedFrom) || (dashedTo !== null && bar.dataIndex <= dashedTo))- ctx.fillStyle = useHatch ? hatch : series.color+ ctx.fillStyle = useHatch ? hatch : barColorAt(series, bar.dataIndex)ctx.beginPath()traceRoundedBarPath(ctx, bar.x, bar.y, bar.width, bar.height, cornerRadius, bar.corners)ctx.fill()diff --git a/frontend/src/lib/hog-charts/core/color-utils.ts b/frontend/src/lib/hog-charts/core/color-utils.tsindex 37496df597bc..9d23cffb025e 100644--- a/frontend/src/lib/hog-charts/core/color-utils.ts+++ b/frontend/src/lib/hog-charts/core/color-utils.ts@@ -1,7 +1,18 @@import * as d3 from 'd3'+import type { ResolvedSeries, Series } from './types'+/** Translucent variant of a series colour (any CSS color form d3 can parse — hex 3/6 digit,* rgb/rgba, named, HSL). Falls back to the raw string when `d3.color` returns `null`. */export function dimColor(color: string, alpha: number): string {return d3.color(color)?.copy({ opacity: alpha }).toString() ?? color}++/** Fill color for the bar at `index`: the per-bar override (`bars[index].color`) when set, else the+ * series color. The one resolver every bar color-read site (fill, hover highlight, tooltip swatch,+ * value labels) should use, so a per-bar series can't accidentally render bars in the series color. */+export function barColorAt(series: ResolvedSeries, index: number): string+export function barColorAt(series: Pick<Series, 'color' | 'bars'>, index: number): string | undefined+export function barColorAt(series: Pick<Series, 'color' | 'bars'>, index: number): string | undefined {+ return series.bars?.[index]?.color ?? series.color+}diff --git a/frontend/src/lib/hog-charts/core/interaction.ts b/frontend/src/lib/hog-charts/core/interaction.tsindex d1aaebc5acb6..aed6fa5aa5d4 100644--- a/frontend/src/lib/hog-charts/core/interaction.ts+++ b/frontend/src/lib/hog-charts/core/interaction.ts@@ -1,5 +1,6 @@import { bisector } from 'd3'+import { barColorAt } from './color-utils'import type {ChartDimensions,PointClickData,@@ -98,7 +99,11 @@ export function buildTooltipContext<Meta = unknown>(// `resolveValue` is the value shown to the user (the segment); `resolvePositionValue`// is where to anchor (the stacked top). They diverge only for stacked charts.if (s.visibility?.tooltip !== false) {- seriesData.push({ series: s, value: resolveValue(s, dataIndex), color: s.color })+ // A per-bar series carries each bar's identity in `bars[i]` — surface it so the tooltip+ // reads the right color/meta/label rather than the shared series-level ones.+ const bar = s.bars?.[dataIndex]+ const entrySeries = bar ? { ...s, meta: bar.meta ?? s.meta, label: bar.label ?? s.label } : s+ seriesData.push({ series: entrySeries, value: resolveValue(s, dataIndex), color: barColorAt(s, dataIndex) })}const seriesValueScale = yAxes?.[s.yAxisId ?? DEFAULT_Y_AXIS_ID]?.scale ?? yScaleconst px = seriesValueScale(resolvePositionValue(s, dataIndex))diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.tsindex d6b3c548ca66..546e5c69661d 100644--- a/frontend/src/lib/hog-charts/core/types.ts+++ b/frontend/src/lib/hog-charts/core/types.ts@@ -29,6 +29,11 @@ export interface Series<Meta = unknown> {/** CSS color string (hex, rgb, var(--…), etc.) for the line and associated fill/points.* When omitted (or empty), the chart picks a color from `theme.colors` by series index. */color?: string+ /** Bar charts only: per-bar overrides of the series-level `color`/`label`/`meta`, indexed by+ * data index. Lets one series draw bars with distinct identity (e.g. an aggregated breakdown,+ * one bar per breakdown value) instead of paying the O(n²) cost of one series per bar. Read by+ * bar fill, hover highlight, and the tooltip; not by track decorations (`drawBarTracks`). */+ bars?: { color?: string; label?: string; meta?: Meta }[]/** Which y-axis this series is scaled against. Defaults to {@link DEFAULT_Y_AXIS_ID}. */yAxisId?: string/** Arbitrary consumer data attached to this series. Flows through to TooltipContextdiff --git a/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx b/frontend/src/lib/hog-charts/overlays/ValueLabels.tsxindex 833408a0a60a..378693e6be26 100644--- a/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx+++ b/frontend/src/lib/hog-charts/overlays/ValueLabels.tsx@@ -1,6 +1,7 @@import React, { useMemo } from 'react'import { useChartHover, useChartLayout } from '../core/chart-context'+import { barColorAt } from '../core/color-utils'import { resolveYScaleForSeries } from '../core/scales'import type { ChartDimensions, ChartScales, ResolvedSeries, ResolveValueFn } from '../core/types'import { getTextMeasureCtx } from '../utils/text-measure'@@ -128,7 +129,6 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2}const topSeries = visible[visible.length - 1]const yScale = resolveYScaleForSeries(scales, topSeries)- const topColor = topSeries.colorfor (let dIdx = 0; dIdx < labels.length; dIdx++) {const total = bandTotal(visible, dIdx)@@ -147,7 +147,7 @@ function buildStackTotal(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2`${STACK_TOTAL_KEY}-${dIdx}`,-1,dIdx,- topColor,+ barColorAt(topSeries, dIdx),valueFormatter(total, -1, dIdx),categoricalCoord,valueCoord,@@ -216,7 +216,7 @@ function buildPerSegment(args: BuildCandidatesArgs, ctx: CanvasRenderingContext2`${s.key}-${dIdx}`,sIdx,dIdx,- s.color,+ barColorAt(s, dIdx),valueFormatter(displayValue, sIdx, dIdx),categoricalCoord,valueCoord,diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsxindex af0fb901f9e9..0ba509fabec7 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx@@ -252,7 +252,7 @@ describe('TrendsBarChart (ActionsBarValue)', () => {).toContain('rotate(-90')})- it('emits one series per breakdown so each bar gets its own color', async () => {+ it('emits one series with a colored bar per breakdown value', async () => {renderInsight({query: aggregatedBar({series: [@@ -270,17 +270,39 @@ describe('TrendsBarChart (ActionsBarValue)', () => {featureFlags: HOG_CHARTS_FLAG,})- // Five hedgehog breakdowns → five sparse-stacked series sharing five bands.+ // Five hedgehog breakdowns → one series carrying five per-bar colors across five bands.+ await screen.findByRole('img', { name: /chart with 1 data series/i }, { timeout: 5000 })await waitFor(() => {- expect(- screen.getByRole('img', {- name: /chart with 5 data series/i,- })- ).toBeInTheDocument()+ expect(getHogChart().yTicks()).toHaveLength(5)+ },+ { timeout: 5000 }+ )+ })++ it('colors each value-label pill by its own bar, not the first bar', async () => {+ // Regression: the single collapsed series carries per-bar colors, so value labels must+ // resolve `bars[dataIndex].color` — not the series-level color (which is just bars[0].color).+ renderInsight({+ query: aggregatedBar({+ series: [{ kind: NodeKind.EventsNode, event: 'Napped', name: 'Napped' }],+ breakdownFilter: { breakdown: 'hedgehog', breakdown_type: 'event' },+ trendsFilter: { display: ChartDisplayType.ActionsBarValue, showValuesOnSeries: true },+ }),+ featureFlags: HOG_CHARTS_FLAG,+ })+ await screen.findByRole('img', { name: /chart with 1 data series/i }, { timeout: 5000 })++ await waitFor(+ () => {+ expect(getHogChart().valueLabels().length).toBeGreaterThan(1)},{ timeout: 5000 })+ const pillColors = getHogChart()+ .valueLabels()+ .map((l) => l.color)+ expect(new Set(pillColors).size).toBeGreaterThan(1)})it('labels each aggregated breakdown bar by its breakdown value, one band per value by default', async () => {@@ -291,7 +313,7 @@ describe('TrendsBarChart (ActionsBarValue)', () => {}),featureFlags: HOG_CHARTS_FLAG,})- await screen.findByRole('img', { name: /chart with 5 data series/i }, { timeout: 5000 })+ await screen.findByRole('img', { name: /chart with 1 data series/i }, { timeout: 5000 })await waitFor(() => {@@ -403,7 +425,7 @@ describe('TrendsBarChart (ActionsBarValue)', () => {}),featureFlags: HOG_CHARTS_FLAG,})- await screen.findByRole('img', { name: /chart with 5 data series/i }, { timeout: 5000 })+ await screen.findByRole('img', { name: /chart with 1 data series/i }, { timeout: 5000 })// Spike has aggregated_value 11 — largest, so it's the topmost row in DESC layout.const canvas = screen.getByRole('img', { name: /chart with/i })diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.tsindex 50c58e838ea0..381821cf9444 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts@@ -140,20 +140,19 @@ describe('buildTrendsBarAggregatedSeries', () => {expect(displayLabels).toEqual(['Chrome'])})- it('places each aggregated_value at the index matching its own band — zero everywhere else', () => {+ it('collapses to a single series whose data holds each band value in order', () => {const results = [mkResult({ id: 'a', label: 'A', aggregated_value: 10 }),mkResult({ id: 'b', label: 'B', aggregated_value: 20 }),mkResult({ id: 'c', label: 'C', aggregated_value: 30 }),]const { series } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED })- expect(series[0].data).toEqual([10, 0, 0])- expect(series[1].data).toEqual([0, 20, 0])- expect(series[2].data).toEqual([0, 0, 30])+ expect(series).toHaveLength(1)+ expect(series[0].data).toEqual([10, 20, 30])})it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, undefined])(- 'replaces non-finite aggregated_value (%p) with 0 at the result index',+ 'replaces non-finite aggregated_value (%p) with 0',(badValue) => {const { series } = buildTrendsBarAggregatedSeries([mkResult({ aggregated_value: badValue })], {getColor: () => RED,@@ -162,11 +161,45 @@ describe('buildTrendsBarAggregatedSeries', () => {})- it('passes per-result colors through from getColor', () => {+ it('exposes per-result colors and labels as per-bar entries on the single series', () => {const colors = ['#aaa', '#bbb', '#ccc']- const results = colors.map((_, i) => mkResult({ id: `r${i}` }))+ const results = colors.map((_, i) => mkResult({ id: `r${i}`, label: `L${i}` }))const { series } = buildTrendsBarAggregatedSeries(results, { getColor: (_r, i) => colors[i] })- expect(series.map((s) => s.color)).toEqual(colors)+ expect(series).toHaveLength(1)+ expect(series[0].bars?.map((b) => b.color)).toEqual(colors)+ expect(series[0].bars?.map((b) => b.label)).toEqual(['L0', 'L1', 'L2'])+ // Series-level color falls back to the first bar so a tooltip/legend has something sane.+ expect(series[0].color).toBe(colors[0])+ })++ it('dims the previous-compare bar color, matching the time-series builder', () => {+ const results = [+ mkResult({ id: 'a', label: 'A', compare_label: 'current' }),+ mkResult({ id: 'b', label: 'B', compare_label: 'previous' }),+ ]+ const { series } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED })+ expect(series[0].bars?.map((b) => b.color)).toEqual([RED, hexToRGBA(RED, 0.5)])+ })++ it('builds per-bar meta by index when buildMeta is provided', () => {+ const results = [mkResult({ id: 'a' }), mkResult({ id: 'b' })]+ const { series } = buildTrendsBarAggregatedSeries<TrendsBarResultLike, { idx: number }>(results, {+ getColor: () => RED,+ buildMeta: (_r, i) => ({ idx: i }),+ })+ expect(series[0].bars?.map((b) => b.meta)).toEqual([{ idx: 0 }, { idx: 1 }])+ })++ it('keeps the sparse multi-series stack when stackBreakdowns is set', () => {+ const results = [+ mkResult({ id: 'a', label: 'F', order: 0, breakdown_value: 'Chrome', aggregated_value: 10 }),+ mkResult({ id: 'b', label: 'F', order: 0, breakdown_value: 'Safari', aggregated_value: 20 }),+ ]+ const { series } = buildTrendsBarAggregatedSeries(results, { getColor: () => RED, stackBreakdowns: true })+ // Stacked breakdowns share a band and genuinely stack, so they stay as one series per row.+ expect(series).toHaveLength(2)+ expect(series[0].data).toEqual([10, 0])+ expect(series[1].data).toEqual([0, 20])})it.each([@@ -207,9 +240,8 @@ describe('buildTrendsBarAggregatedSeries', () => {getHidden: (_r, i) => i === 1,})expect(displayLabels).toEqual(['A', 'C'])- expect(series).toHaveLength(2)- expect(series[0].data).toEqual([1, 0])- expect(series[1].data).toEqual([0, 3])+ expect(series).toHaveLength(1)+ expect(series[0].data).toEqual([1, 3])})})diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.tsindex e78d28632774..94ce97748582 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts@@ -39,14 +39,24 @@ export interface BuildTrendsBarAggregatedSeriesOpts<getDisplayLabel?: (r: R, index: number) => string}+/** Result color with the compare-previous dimming applied — shared by the per-series (time-series)+ * and per-bar (aggregated) builders so both render identical colors. */+function resolveBarColor<R extends TrendsBarResultLike, M = unknown>(+ r: R,+ index: number,+ opts: BuildTrendsBarSeriesOpts<R, M>+): string {+ const baseColor = opts.getColor(r, index)+ return r.compare_label === 'previous' ? hexToRGBA(baseColor, COMPARE_PREVIOUS_DIM_OPACITY) : baseColor+}+function buildMainTrendsBarSeries<R extends TrendsBarResultLike, M = unknown>(r: R,index: number,opts: BuildTrendsBarSeriesOpts<R, M>,data: number[]): Series<M> {- const baseColor = opts.getColor(r, index)- const color = r.compare_label === 'previous' ? hexToRGBA(baseColor, COMPARE_PREVIOUS_DIM_OPACITY) : baseColor+ const color = resolveBarColor(r, index, opts)const excluded = opts.getHidden ? opts.getHidden(r, index) : falseconst meta = opts.buildMeta ? opts.buildMeta(r, index) : undefinedreturn {@@ -109,9 +119,6 @@ export function buildTrendsBarTimeSeriesConfig(opts: BuildTrendsBarTimeSeriesCon/** Separator between the series id and compare label in synthetic stacked-mode band keys. */const BAND_KEY_SEP = '\u001f'-// Sparse-stacked: hog-charts BarChart allows one color per series, so we emit N series with-// data=0 except at their own band — d3.stack reduces this to one visible segment per band.-// Trade-off: only the last series gets rounded-corner caps.export function buildTrendsBarAggregatedSeries<R extends TrendsBarResultLike, M = unknown>(results: R[],opts: BuildTrendsBarAggregatedSeriesOpts<R, M>@@ -123,18 +130,31 @@ export function buildTrendsBarAggregatedSeries<R extends TrendsBarResultLike, Mconst base = opts.getDisplayLabel ? opts.getDisplayLabel(r, i) : (r.label ?? '')return r.compare_label ? `${base} - ${r.compare_label}` : base})- // Band key strategy:- // - separate (default): unique per result, so every breakdown value gets its own band.- // - stacked: one band per series/formula (keyed by order + compare_label) so a series'- // breakdown values collapse onto one band and stack into a single bar.- const labels = visible.map((r, i) => {- if (!opts.stackBreakdowns) {- return String(i)- }+ const n = visible.length++ if (!opts.stackBreakdowns) {+ const bars = visible.map((r, i) => ({+ color: resolveBarColor(r, i, opts),+ label: r.label ?? '',+ meta: opts.buildMeta ? opts.buildMeta(r, i) : undefined,+ }))+ const series: Series<M>[] = [+ {+ key: 'aggregated',+ label: '',+ data: visible.map((r) => (Number.isFinite(r.aggregated_value) ? r.aggregated_value! : 0)),+ color: bars[0]?.color,+ bars,+ },+ ]+ return { series, labels: visible.map((_, i) => String(i)), displayLabels }+ }++ // Stacked breakdowns share a band and genuinely stack, so they stay as N sparse series.+ const labels = visible.map((r) => {const seriesId = r.action?.order ?? r.order ?? 0return `${seriesId}${BAND_KEY_SEP}${r.compare_label ?? ''}`})- const n = visible.lengthconst series = visible.map((r, index) => {const data = new Array<number>(n).fill(0)const value = r.aggregated_value ?? 0