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.

fix(insights): stop value labels dropping every other bar (#71831)

Sam Pennington068f7151c58f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6e98151e4fe2..2f0ffd55ed8a 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -536,6 +536,14 @@ snapshots:
hash: v1.k794b7964.ced56b04fb5a6f225291cfda3afa86a761a918389cbef178ff90b0fdce9ff410.1jGojIWZ8Zyj8PgzJOSsBG2_WnQaWs1TVc_QNwTVto0
components-hogcharts-barchart--custom-corner-radius--light:
hash: v1.k794b7964.d71058b115ad9763f80cae0e37a22665ce5b43ce8eb41dfbfa36d29a39a732ef.LBEhfGB4c-JH2n66cXiCeb-Jp2V8RHA1TJIMTdxQk74
+ components-hogcharts-barchart--dense-value-labels--dark:
+ hash: v1.k794b7964.f92354f54351883a59d80cb36fca32450addab7bce2fdfdcf2cf38a4e377ad9c.BKDsHhwPgtkKGPcR5SslyBaGd98Az4vFzIz2FEgakgk
+ components-hogcharts-barchart--dense-value-labels--light:
+ hash: v1.k794b7964.8126bfd42da400480479a5e3fe2df6799d144a6337695e59dd6cf362e8c896ec.Yx3S2Q-eHLeJPkd7Vzy5FsDl01QPUXQGPo9jYqbMyhQ
+ components-hogcharts-barchart--dense-value-labels-horizontal--dark:
+ hash: v1.k794b7964.ad1ced5fce2869bf7dc2dfd5d1c5d3ec37983a6201581e2732d64dd75fc01ab1.BU04lvXzOfLumNNI74HiD8NlyWCxwSIByWeRzrlbpC8
+ components-hogcharts-barchart--dense-value-labels-horizontal--light:
+ hash: v1.k794b7964.68a10cc196a088ff3182ebbc1326b917135bacc6a67fd0b3fcd4d295aa309b47.IdSAgm5SF1AIF9NyJbEyR64UQSOalylEpb8yRQDBuMs
components-hogcharts-barchart--fill-styles--dark:
hash: v1.k794b7964.269efb068d5073b907257d8cfcb37a7298817cdd925fc06b84b7b07f44f6bd0d.0yN65vIaNXOiz3m5usBaG4sA-l-FZDu-WBjgu-XY32c
components-hogcharts-barchart--fill-styles--light:
@@ -2249,9 +2257,9 @@ snapshots:
errortracking-volumesparkline--events-before-data-range--light:
hash: v1.k794b7964.683c24f2509215d174cda4a69fd2aa0f021af91d45f7ccdab742f78755c2e4ca.l0oCDgytHq-3gkB5Nza3SN1Tpmvc_LP_dsSdGCfoXxo
exporter-funnels--funnel-time-to-convert-insight--dark:
- hash: v1.k794b7964.365d7b29002266dc1c11204aca4714a1a08300dee58eef15ac4de749a99392d7.9weg3vF6Fk5KTqAtP0qzIOK--LxJ3n-2xeb_0iyG6FY
+ hash: v1.k794b7964.df689a0663d5c8465aff7085aafd8a71ff018e3b311bb9cc625bfbdc82fbe411.D4ShgJ5fysJWLIdyxzR19hb47kaQEHUJbeDtTXHPcvw
exporter-funnels--funnel-time-to-convert-insight--light:
- hash: v1.k794b7964.3afb6d41a3280b0428be00c4214fa98f44d476520ecbb308ffe81725151c95b3.KnKxSK0rkVa-zpJ8AwBFZfM3iBEfrUIpnS7y-phoav4
+ hash: v1.k794b7964.f1729da9a6b27a50180136e94c602c3c63e004093653e7c602ae6609626e19a2.v-HhwgvZ4eFuV-PADE_y_cUFWzt2O2_k5rdjhOivZPU
exporter-funnels--funnel-top-to-bottom-insight--dark:
hash: v1.k794b7964.de29e0a4751c337b9e03170399ae123d95e414ee6603c95927ba75832595fc0d.Dm1yLDqoTUl0jdPmKIzu7LPNjt1x2-gxz4JhoXe88io
exporter-funnels--funnel-top-to-bottom-insight--light:
@@ -2669,9 +2677,9 @@ snapshots:
insights-funnelhistogramchart--compare--light:
hash: v1.k794b7964.1fd181656106762b9db977b1a320fa7ec297aa13b0371a324e6e89d7fa9196e8.rmu_N6Ha5kpbSNz4iEslqbI2bRz-4ZrSl2-Swe8lnM0
insights-funnelhistogramchart--default--dark:
- hash: v1.k794b7964.2b849c9f3233e3fc337e11e4e11e9ac3cab78c02e0842370e528763276ba480b.Oj6dYHu2VrG1z0eNUIDTwo5-vbnMIdKcLz2qDCTg3XM
+ hash: v1.k794b7964.dfc2902b5eb5a757b6e15807ae19ee2e671058bc6d2b7a221e134fdfb0a303c3.vgM9Vr2TXGuY1LO4PPhsAvbR1nUIXkU1VQ9sVP3AIT8
insights-funnelhistogramchart--default--light:
- hash: v1.k794b7964.64fdbe8bbdc82b28bd3b187a843701a065930c1161ca2b5f693e81c8d6b93524.xPto_as1je4El0RPf61rS3OTaGiuSrXibHz1ndQ4Ye8
+ hash: v1.k794b7964.5b53f541758cdf451877538cba5ce23ea9fd5558afc87394ad1e50cc7f03c7df.DQ8DygCVqKFwMaQFFjiDWRlaUljZBa3KkXEqH7h_RJY
insights-funnelhistogramchart--edit-scene--dark:
hash: v1.k794b7964.b9075685ee89f56c946929e3eb5b11c4962962b846a4118ef8a7f8f5ed4d1c9b.458m5ypwOq5xoj0M8CPHTr6cvw5IrHGW68jfgw7SQuk
insights-funnelhistogramchart--edit-scene--light:
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 66a60350eed2..869d126c3e75 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -76,7 +76,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- To tune the built-in tooltip **without writing a render prop**, put those same fields on `config.tooltip` (`{ enabled, pinnable, resolveClickToNearestSeries, placement, valueFormatter, labelFormatter, showTotal, totalLabel, totalFormatter, sortedByValue }`). When no `tooltip` render prop is supplied, the chart renders `DefaultTooltip` with them applied; a render prop, if given, owns content entirely and these are ignored. Prefer config for "format each row / add a total" cases (e.g. SQL insights pass per-column formatters this way) and reach for the render prop only for genuinely custom tooltip markup (e.g. adding a `footer` hint). `resolveClickToNearestSeries` (default false) changes what a click on a `pinnable` multi-series chart does: instead of always pinning first (letting the user then click a specific row), it resolves the series nearest the cursor and fires `onPointClick` for it directly — skip pinning only where a click's target series is visually unambiguous by position (e.g. funnel breakdown areas, one per breakdown value); leave it off where series overlap closely and a wrong guess is costly (e.g. trend lines).
- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).
- `TrendLineOverlay` renders linear/exponential regression lines as SVG polylines on vertical bar and combo charts. Use via `trendLines?: TrendLineConfig[]` in `TimeSeriesBarChartConfig` or `TimeSeriesComboChartConfig` — the chart computes the derived series via `buildTrendLineSeries` and passes them to the overlay as a child. Only works for `axisOrientation: 'vertical'`; returns null on horizontal charts. Legend-toggled-off series are filtered automatically.
-- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original. `context.bandValues` is the stack's values at this index and `context.previousBandValues` the same for the preceding index (empty at the first), so a formatter can compute a segment's share of the current or the previous band (e.g. period-over-period).
+- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original. `context.bandValues` is the stack's values at this index and `context.previousBandValues` the same for the preceding index (empty at the first), so a formatter can compute a segment's share of the current or the previous band (e.g. period-over-period). Collision avoidance is a single greedy pass over the full 2D label box (`minGap` on every side): a label is dropped only when it actually overlaps a higher-priority one, so on bar charts neighbours at different heights both keep their labels instead of the axis dropping every other bar. Ties resolve toward earlier series and left-to-right / top-to-bottom.
- Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `SlopeChart`) takes a `config.legend: ChartLegendConfig` (`{ show, position, align, gap, interactive, hiddenKeys, onToggleSeries, renderItem }`). With `show: true` the chart renders a built-in legend that, by default (`interactive`), is click-to-toggle: clicking a row hides that series (no draw, no scale contribution, no tooltip — the axes rescale into the freed space) while the row stays listed but dimmed so it can be restored. The chart owns the toggled-off state (uncontrolled); set `interactive: false` for a static legend, or pass `hiddenKeys` + `onToggleSeries` to control it yourself. Hidden by default. `config.legend.renderItem(defaultNode, item)` wraps each rendered row, so consumers can augment it (e.g. attach a right-click context menu) while keeping the default swatch/label/toggle rendering — return `defaultNode` to leave a row untouched. Toggling on time-series charts lists the user's series only (not derived trend lines / CI bands) — and hiding a series also hides everything derived from it (its CI band, moving average, and trend line), so no orphaned overlay floats over the gap.
- `Legend` (and `ChartLegend` for layout) is the lower-level presentational primitive: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. Use it directly when the built-in `config.legend` can't express what you need (custom item order/labels). `useChartLegend(series, theme, config, items?)` is the shared hook the charts use — returns `visibleSeries` (hidden applied as `visibility.excluded`) plus `legendProps` to spread onto `<ChartLegend>`; `applyHiddenSeries` is the underlying helper. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change). Long labels clip with an ellipsis only when they run out of the space actually available — there is no fixed max width. A vertical legend bounds each row to its column and truncates at the column edge; a horizontal legend caps each row at an equal share of the line floored at 180px (flexbox wraps before it shrinks, so without a cap one long label would take a whole line instead of clipping) — many series pack into tidy 180px columns while a few series with room to spare, or a lone series, show unclipped whenever they fit. The full text is always exposed via a native `title` tooltip on hover. The legend slot in `ChartLegendLayout` is bounded and scrolls (a top/bottom legend caps at ~40% of the chart height so the plot keeps the majority; a left/right legend stretches to full chart height and caps at 45% width but never more than 240px), so a many-series legend scrolls instead of squeezing or stretching the chart. A left/right legend uses `align-self: stretch` (resolves against the container's used height, so it works even when no ancestor sets an explicit `height`). The top/bottom `max-height: 40%` cap is a percentage, so it only resolves when the chart container has an **explicit** `height` — a flex-derived used size (e.g. `flex: 1` with only `min-height`/`max-height`) does **not** count and the cap silently no-ops; pin a real `height` on the container.
- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order) and formats values with `valueFormatter` so they match the on-chart labels' units; pass your own `tooltip` to override. (`DefaultTooltip` itself takes an optional `valueFormatter` for the same reason — without it values fall back to `toLocaleString`.) Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx
index 40aa12a4d7b0..781a42b57801 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx
@@ -216,6 +216,57 @@ export const WithValueLabels: Story = {
},
}
+export const DenseValueLabels: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ // Many bars with widely varying heights. Labels sit at each bar's tip, so neighbours
+ // rarely share a height — collision avoidance should keep every label that actually fits
+ // rather than dropping every other bar.
+ const labels = Array.from({ length: 20 }, (_, i) => `D${i + 1}`)
+ const series: Series[] = [
+ {
+ key: 'events',
+ label: 'Events',
+ color: '',
+ data: [128, 24, 205, 61, 172, 39, 240, 88, 15, 199, 54, 143, 27, 218, 76, 165, 33, 187, 96, 231],
+ },
+ ]
+ const config: BarChartConfig = { showGrid: true }
+ return (
+ <Stage width={900} height={320}>
+ <BarChart series={series} labels={labels} config={config} theme={theme}>
+ <ValueLabels />
+ </BarChart>
+ </Stage>
+ )
+ },
+}
+
+export const DenseValueLabelsHorizontal: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ // Same stress test on a horizontal bar chart — labels track each bar's length, so the
+ // 2D collision check keeps labels whose bars differ enough in value.
+ const labels = Array.from({ length: 16 }, (_, i) => `Row ${i + 1}`)
+ const series: Series[] = [
+ {
+ key: 'events',
+ label: 'Events',
+ color: '',
+ data: [128, 24, 205, 61, 172, 39, 240, 88, 15, 199, 54, 143, 27, 218, 76, 165],
+ },
+ ]
+ const config: BarChartConfig = { axisOrientation: 'horizontal', showGrid: true }
+ return (
+ <Stage width={520} height={480}>
+ <BarChart series={series} labels={labels} config={config} theme={theme}>
+ <ValueLabels />
+ </BarChart>
+ </Stage>
+ )
+ },
+}
+
export const WithReferenceLine: Story = {
render: () => {
const theme = useReactiveTheme()
diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
index 9c90907fe710..54223c16d847 100644
--- a/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.test.tsx
@@ -186,7 +186,8 @@ describe('ValueLabels', () => {
{ key: 'b', label: 'B', color: '#445566', data: [20] },
]
const ctx = makeContext(series, { labels: ['Mon'] })
- // Collision avoidance is per-series so both labels should render.
+ // Same x but different values put the two labels at different value-axis coords, so their
+ // boxes don't overlap and both render.
const { container } = renderInChart(ctx, <ValueLabels />)
const divs = labelDivs(container)
expect(divs).toHaveLength(2)
@@ -276,8 +277,45 @@ describe('ValueLabels', () => {
expect(divs[0].style.transform).toBe(expectedTransform)
})
- it('horizontal: drops vertically overlapping labels via per-series collision avoidance', () => {
- const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [40, 60] }]
+ it('vertical: keeps neighbours that overlap along x but are separated along the value axis', () => {
+ // Two adjacent bars whose labels overlap horizontally (x=100 and x=108, boxes ~24px wide)
+ // but sit far apart vertically because the bars have very different heights (90 vs 10).
+ // A categorical-axis-only pass would drop the second; the 2D check keeps both.
+ const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [90, 10] }]
+ const xByLabel: Record<string, number> = { A: 100, B: 108 }
+ const ctx = makeContext(series, {
+ labels: ['A', 'B'],
+ scales: { x: (label: string) => xByLabel[label], y: yScale, yTicks: () => [0, 50, 100] },
+ })
+ expect(labelDivs(renderInChart(ctx, <ValueLabels />).container)).toHaveLength(2)
+ })
+
+ it('vertical: drops neighbours that overlap along both axes', () => {
+ // Same near-x overlap as above, but equal heights so the boxes also overlap vertically.
+ const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [50, 50] }]
+ const xByLabel: Record<string, number> = { A: 100, B: 108 }
+ const ctx = makeContext(series, {
+ labels: ['A', 'B'],
+ scales: { x: (label: string) => xByLabel[label], y: yScale, yTicks: () => [0, 50, 100] },
+ })
+ expect(labelDivs(renderInChart(ctx, <ValueLabels />).container)).toHaveLength(1)
+ })
+
+ it('horizontal: keeps neighbours on the same row that are separated along the value axis', () => {
+ // Both labels share the categorical row (y=200) but their bars have very different values
+ // (10 vs 90), so the boxes sit far apart along the x (value) axis and never touch.
+ const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [10, 90] }]
+ const ctx = makeContext(series, {
+ axisOrientation: 'horizontal',
+ labels: ['A', 'B'],
+ scales: { x: () => 200, y: yScale, yTicks: () => [0, 50, 100] },
+ })
+ expect(labelDivs(renderInChart(ctx, <ValueLabels />).container)).toHaveLength(2)
+ })
+
+ it('horizontal: drops neighbours that overlap along both axes', () => {
+ // Same row (y=200) and equal values, so the boxes overlap on the value axis too.
+ const series: ResolvedSeries[] = [{ key: 's', label: 'S', color: '#f00', data: [50, 50] }]
const ctx = makeContext(series, {
axisOrientation: 'horizontal',
labels: ['A', 'B'],
diff --git a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx b/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
index 8c9c822c22a2..86f0e09c4091 100644
--- a/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
+++ b/packages/quill/packages/charts/src/overlays/ValueLabels.tsx
@@ -356,48 +356,28 @@ function flipClippedCandidates(
return candidates
}
+// Greedy overlap removal over every candidate at once, keyed on the full 2D label box. Value
+// labels sit at their bar/point tip, so two neighbours can share a categorical position yet sit
+// far apart along the value axis (bars of different heights) — the boxes never touch. Testing
+// only the categorical axis would drop the second of every such pair (the "skips every other bar
+// even when there's room" case); the 2D `rectsOverlap` test keeps whatever genuinely fits, so a
+// label is skipped only when it would actually collide. Candidates are ordered by series, then
+// along the categorical axis, so ties resolve toward earlier series and a stable
+// left-to-right / top-to-bottom keep set.
function applyCollisionAvoidance(candidates: Candidate[], minGap: number, isHorizontal: boolean): Candidate[] {
if (candidates.length === 0) {
return candidates
}
- const bySeries: Map<number, Candidate[]> = new Map()
- for (const c of candidates) {
- const bucket = bySeries.get(c.seriesIndex)
- if (bucket) {
- bucket.push(c)
- } else {
- bySeries.set(c.seriesIndex, [c])
+ const ordered = [...candidates].sort((a, b) => {
+ if (a.seriesIndex !== b.seriesIndex) {
+ return a.seriesIndex - b.seriesIndex
}
- }
-
- const afterPrimary: Candidate[] = []
- for (const group of bySeries.values()) {
- if (isHorizontal) {
- group.sort((a, b) => a.y - b.y)
- const halfH = LABEL_HEIGHT / 2
- let lastBottom = -Infinity
- for (const c of group) {
- if (c.y - halfH >= lastBottom + minGap) {
- afterPrimary.push(c)
- lastBottom = c.y + halfH
- }
- }
- } else {
- group.sort((a, b) => a.x - b.x)
- let lastRight = -Infinity
- for (const c of group) {
- const halfW = c.width / 2
- if (c.x - halfW >= lastRight + minGap) {
- afterPrimary.push(c)
- lastRight = c.x + halfW
- }
- }
- }
- }
+ return isHorizontal ? a.y - b.y : a.x - b.x
+ })
const visible: Candidate[] = []
const placedRects: Rect[] = []
- for (const c of afterPrimary) {
+ for (const c of ordered) {
const rect = labelRect(c, isHorizontal)
if (!placedRects.some((p) => rectsOverlap(rect, p, minGap))) {
visible.push(c)