: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
fix(insights): prevent overlapping x-axis labels on horizontal bar charts (#62468)
Sam Penningtona7024f62834f
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsxindex 16b56c085b71..714d902b7826 100644--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.stories.tsx@@ -108,6 +108,32 @@ export const HorizontalAggregatedSingle: Story = {},}+// Exercises the horizontal value-tick de-overlap: wide thousands-separated labels (millions) in a+// compact panel, where consecutive ticks genuinely collide. The de-overlap pass hides the colliding+// ones so the axis reads cleanly instead of smearing into "0 500,0001,000,000…" — gridlines stay at+// every tick, labels only at the survivors. Remove the pass and the labels overlap again; the exact+// gap that decides which survive is pinned by AxisLabels.test.ts.+export const HorizontalWideValueLabels: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const config: BarChartConfig = {+ axisOrientation: 'horizontal',+ showGrid: true,+ yTickFormatter: (v) => v.toLocaleString('en-US'),+ bars: { cornerRadius: 4, fitToHeight: true },+ }+ const labels = ['/pricing', '/signup', '/product', '/docs', '/blog']+ const series: Series[] = [+ { key: 'views', label: 'Views', color: '', data: [2_300_000, 1_510_000, 940_000, 460_000, 180_000] },+ ]+ return (+ <Stage width={340} height={280}>+ <BarChart series={series} labels={labels} config={config} theme={theme} />+ </Stage>+ )+ },+}+export const SingleSeries: Story = {render: () => {const theme = useReactiveTheme()diff --git a/packages/quill/packages/charts/src/core/bar-scales.test.ts b/packages/quill/packages/charts/src/core/bar-scales.test.tsindex 1c2a696bf6e7..eff682d0fc97 100644--- a/packages/quill/packages/charts/src/core/bar-scales.test.ts+++ b/packages/quill/packages/charts/src/core/bar-scales.test.ts@@ -211,11 +211,36 @@ describe('hog-charts bar scales', () => {})})+ describe('createBarScales — fitToHeight value domain', () => {+ // minBandSize == plotHeight forces maxBands = 1, so only the leading row survives.+ const dropToFirst = {+ axisOrientation: 'horizontal' as const,+ fitToHeight: true,+ minBandSize: dimensions.plotHeight,+ }++ it('scales the value axis to only the rows fitToHeight keeps', () => {+ const series = [makeSeries({ key: 's1', data: [5, 10, 999] })]+ const { value } = createBarScales(series, ['a', 'b', 'c'], dimensions, dropToFirst)+ // 999 sits in a dropped row, so it must not stretch the domain past the kept value.+ expect(value.domain()[1]).toBeLessThan(999)+ })++ it('keeps a large value in the domain when its row survives', () => {+ const series = [makeSeries({ key: 's1', data: [999, 5, 10] })]+ const { value } = createBarScales(series, ['a', 'b', 'c'], dimensions, dropToFirst)+ expect(value.domain()[1]).toBeGreaterThanOrEqual(999)+ })++ it('leaves the domain spanning every row when no rows are dropped', () => {+ const series = [makeSeries({ key: 's1', data: [5, 10, 999] })]+ const { value } = createBarScales(series, ['a', 'b', 'c'], dimensions, { axisOrientation: 'horizontal' })+ expect(value.domain()[1]).toBeGreaterThanOrEqual(999)+ })+ })+describe('groupedBandSlot', () => {- const series = [- makeSeries({ key: 's1', data: [1, 2] }),- makeSeries({ key: 's2', data: [3, 4] }),- ]+ const series = [makeSeries({ key: 's1', data: [1, 2] }), makeSeries({ key: 's2', data: [3, 4] })]const grouped = createBarScales(series, ['a', 'b'], dimensions, { barLayout: 'grouped' })it("returns the series' band-axis slot within the band", () => {diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.tsindex 152dbfefe06a..718b3d7a1fa0 100644--- a/packages/quill/packages/charts/src/core/scales.ts+++ b/packages/quill/packages/charts/src/core/scales.ts@@ -457,9 +457,27 @@ export function createBarScales(? [dimensions.plotLeft, dimensions.plotLeft + dimensions.plotWidth]: [dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop]+ // When fitToHeight drops rows, the value axis must scale to only the rendered bars — a dropped+ // off-screen bar (e.g. a dominant "Other" bucket) would otherwise stretch the domain and crush+ // every visible bar. domainLabels is a leading slice, so the kept rows are each series's first+ // `keptCount` data points.+ const keptCount = domainLabels.length+ const restrictToKept = (s: Series): Series =>+ keptCount < labels.length ? { ...s, data: s.data.slice(0, keptCount) } : s+ const valueSeries = series.map(restrictToKept)+ const valueStackedSeries = stackedSeries?.map(restrictToKept)+return {band,- value: buildBarValueScale(series, valueRange, tickCount, barLayout, scaleType, stackedSeries, valueDomain),+ value: buildBarValueScale(+ valueSeries,+ valueRange,+ tickCount,+ barLayout,+ scaleType,+ valueStackedSeries,+ valueDomain+ ),group,}}diff --git a/packages/quill/packages/charts/src/overlays/AxisLabels.test.ts b/packages/quill/packages/charts/src/overlays/AxisLabels.test.tsindex c334525088d6..6d05219fdca6 100644--- a/packages/quill/packages/charts/src/overlays/AxisLabels.test.ts+++ b/packages/quill/packages/charts/src/overlays/AxisLabels.test.ts@@ -1,5 +1,5 @@import { measureLabelWidth } from '../utils/text-measure'-import { computeVisibleXLabels } from './AxisLabels'+import { computeVisibleValueTicks, computeVisibleXLabels } from './AxisLabels'describe('computeVisibleXLabels', () => {const longUrl = 'https://app.posthog.com/project/1/insights/abc123/edit?with=a&very=long&query=string'@@ -39,3 +39,57 @@ describe('computeVisibleXLabels', () => {expect(visible.map((v) => v.index)).toEqual([0])})})++describe('computeVisibleValueTicks', () => {+ const fmt = (v: number): string => v.toLocaleString('en-US')++ it('drops value ticks whose wide labels would overlap, always keeping the first', () => {+ // 10 ticks packed into ~120px (every ~13px) — far too tight for "450,000"-style labels.+ const ticks = Array.from({ length: 10 }, (_, i) => i * 50_000)+ const valueToCoord = (v: number): number => (v / 450_000) * 120++ const visible = computeVisibleValueTicks(ticks, valueToCoord, fmt)++ expect(visible.length).toBeLessThan(ticks.length)+ expect(visible[0].tick).toBe(0)+ // Survivors stay strictly left-to-right with no measured-label overlap.+ for (let i = 1; i < visible.length; i++) {+ const prevRight = visible[i - 1].x + measureLabelWidth(visible[i - 1].text) / 2+ const currLeft = visible[i].x - measureLabelWidth(visible[i].text) / 2+ expect(currLeft).toBeGreaterThanOrEqual(prevRight)+ }+ })++ it('keeps numeric ticks separated by a small but legible gap', () => {+ // Two wide labels whose boxes sit ~14px apart: comfortably readable, but under the 20px gap+ // the category-label path enforces — value ticks must not inherit that aggressive culling.+ const ticks = [100_000, 120_000]+ const [w0, w1] = ticks.map((t) => measureLabelWidth(fmt(t)))+ const x0 = w0 / 2 + 10+ const x1 = x0 + w0 / 2 + 14 + w1 / 2+ const valueToCoord = (v: number): number => (v === ticks[0] ? x0 : x1)++ const visible = computeVisibleValueTicks(ticks, valueToCoord, fmt)++ expect(visible.map((v) => v.tick)).toEqual(ticks)+ })++ it.each([+ {+ description: 'keeps every tick when they are spread far apart',+ ticks: [0, 100, 200],+ valueToCoord: (v: number): number => v * 10,+ expected: [0, 100, 200],+ },+ {+ description: 'skips ticks whose coordinate is not finite',+ ticks: [0, 50, 100],+ valueToCoord: (v: number): number => (v === 50 ? NaN : v * 10),+ expected: [0, 100],+ },+ ])('$description', ({ ticks, valueToCoord, expected }) => {+ const visible = computeVisibleValueTicks(ticks, valueToCoord, fmt)++ expect(visible.map((v) => v.tick)).toEqual(expected)+ })+})diff --git a/packages/quill/packages/charts/src/overlays/AxisLabels.tsx b/packages/quill/packages/charts/src/overlays/AxisLabels.tsxindex 4b6f535e29a2..37f6fd385719 100644--- a/packages/quill/packages/charts/src/overlays/AxisLabels.tsx+++ b/packages/quill/packages/charts/src/overlays/AxisLabels.tsx@@ -20,7 +20,11 @@ interface AxisLabelsProps {maxCategoryLabelWidth?: number}-const LABEL_PADDING = 20+// Minimum gap (px) required between adjacent kept labels. Category labels are often words and get+// generous breathing room; uniformly-spaced numeric value ticks read clearly much closer, so forcing+// the category gap on them culls ticks that have plenty of room.+const CATEGORY_LABEL_PADDING = 20+const VALUE_TICK_LABEL_PADDING = 8interface XLabelCandidate {index: number@@ -37,6 +41,35 @@ function truncateWithTitle(fullText: string, maxCategoryLabelWidth: number): { treturn { text, title: text === fullText ? undefined : fullText }}+/** Greedily keep entries left→right, dropping any whose centered label would collide with the+ * previously kept one (closer than `padding` px). Entries must be sorted by ascending `x`. */+function dropOverlappingLabels<T extends { text: string; x: number }>(candidates: T[], padding: number): T[] {+ if (candidates.length === 0) {+ return []+ }++ const ctx = getTextMeasureCtx()+ if (!ctx) {+ return candidates+ }+ ctx.font = AXIS_LABEL_FONT++ const visible: T[] = []+ let lastRightEdge = -Infinity++ for (const candidate of candidates) {+ const halfWidth = ctx.measureText(candidate.text).width / 2+ const leftEdge = candidate.x - halfWidth++ if (leftEdge >= lastRightEdge + padding) {+ visible.push(candidate)+ lastRightEdge = candidate.x + halfWidth+ }+ }++ return visible+}+export function computeVisibleXLabels(labels: string[],xScale: (label: string) => number | undefined,@@ -58,32 +91,35 @@ export function computeVisibleXLabels(candidates.push({ index: i, text, title, x })}- if (candidates.length === 0) {- return []- }-- const ctx = getTextMeasureCtx()- if (!ctx) {- return candidates- }- ctx.font = AXIS_LABEL_FONT-- const widths = candidates.map((c) => ctx.measureText(c.text).width)-- const visible: XLabelCandidate[] = []- let lastRightEdge = -Infinity+ return dropOverlappingLabels(candidates, CATEGORY_LABEL_PADDING)+}- for (let i = 0; i < candidates.length; i++) {- const halfWidth = widths[i] / 2- const leftEdge = candidates[i].x - halfWidth+interface ValueTickCandidate {+ tick: number+ text: string+ x: number+}- if (leftEdge >= lastRightEdge + LABEL_PADDING) {- visible.push(candidates[i])- lastRightEdge = candidates[i].x + halfWidth+/** Value-axis ticks for a horizontal bar chart map onto the x-axis, where wide numeric labels+ * (e.g. "450,000") collide far more readily than stacked y-axis labels do. Greedily drop the+ * ones that would overlap so the axis stays legible — the same pass `computeVisibleXLabels`+ * applies to a vertical chart's category axis. Ticks arrive value-sorted, so ascending value+ * maps to ascending x for an increasing value scale. */+export function computeVisibleValueTicks(+ ticks: number[],+ valueToCoord: (value: number) => number,+ formatter?: (value: number) => string+): ValueTickCandidate[] {+ const candidates: ValueTickCandidate[] = []+ for (const tick of ticks) {+ const x = valueToCoord(tick)+ if (!isFinite(x)) {+ continue}+ candidates.push({ tick, text: formatter ? formatter(tick) : String(tick), x })}- return visible+ return dropOverlappingLabels(candidates, VALUE_TICK_LABEL_PADDING)}const TICK_STYLE_BASE: React.CSSProperties = {@@ -204,6 +240,14 @@ export const AxisLabels = React.memo(function AxisLabels({[hideXAxis, labels, scales.x, xTickFormatter, orientation, maxCategoryLabelWidth])+ // Mirror the vertical branch's memoization so an unrelated prop change (e.g. axisColor)+ // doesn't re-run the per-tick `ctx.measureText` measurements in `dropOverlappingLabels`.+ const visibleValueTicks = useMemo(+ () =>+ hideXAxis || orientation !== 'horizontal' ? [] : computeVisibleValueTicks(yTicks, scales.y, yTickFormatter),+ [hideXAxis, orientation, yTicks, scales.y, yTickFormatter]+ )+const rightFormatter = yRightTickFormatter ?? yTickFormatterif (orientation === 'horizontal') {@@ -236,24 +280,16 @@ export const AxisLabels = React.memo(function AxisLabels({/>)})}- {!hideXAxis &&- yTicks.map((tick: number) => {- const x = scales.y(tick)- if (!isFinite(x)) {- return null- }- const label = yTickFormatter ? yTickFormatter(tick) : String(tick)- return (- <XTickLabel- key={`x-val-${tick}`}- x={x}- box={dimensions}- text={label}- color={axisColor}- dataAttr="hog-chart-axis-tick-x"- />- )- })}+ {visibleValueTicks.map(({ tick, text, x }) => (+ <XTickLabel+ key={`x-val-${tick}`}+ x={x}+ box={dimensions}+ text={text}+ color={axisColor}+ dataAttr="hog-chart-axis-tick-x"+ />+ ))}</>)}