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): scale axis decimals to small values (#73871)

Sam Pennington2d4a51ab671a
diff --git a/frontend/src/lib/utils/numbers.ts b/frontend/src/lib/utils/numbers.ts
index f4d5afccce13..0f15dbefb00a 100644
--- a/frontend/src/lib/utils/numbers.ts
+++ b/frontend/src/lib/utils/numbers.ts
@@ -65,6 +65,20 @@ export function formatPercentageDiff(current: number, previous: number): string
return diff >= 0 ? `(+${(diff * 100).toFixed(1)}%)` : `(-${(-diff * 100).toFixed(1)}%)`
}
+const MAX_SIGNIFICANT_DECIMAL_PLACES = 10
+
+/** Fraction digits needed to keep two significant digits — `minimum` for anything at or above 0.1,
+ * one more for every extra leading zero below that, capped so float residue doesn't render as a wall
+ * of digits. A flat two decimals renders a series of small values as a run of identical "0.01" / "0"
+ * labels. `minimum` is nullable because callers pass the schema's nullable config field through. */
+export function significantDecimalPlaces(value: number, minimum?: number | null): number {
+ const floor = validateFractionDigits(minimum ?? DEFAULT_DECIMAL_PLACES, DEFAULT_DECIMAL_PLACES)
+ if (!isFinite(value) || value === 0) {
+ return floor
+ }
+ return Math.min(Math.max(floor, 1 - Math.floor(Math.log10(Math.abs(value)))), MAX_SIGNIFICANT_DECIMAL_PLACES)
+}
+
/** Format number with comma as the thousands separator. */
export function humanFriendlyNumber(
d: number,
diff --git a/frontend/src/scenes/insights/aggregationAxisFormat.ts b/frontend/src/scenes/insights/aggregationAxisFormat.ts
index bf76ac4afbf3..7bea773d1354 100644
--- a/frontend/src/scenes/insights/aggregationAxisFormat.ts
+++ b/frontend/src/scenes/insights/aggregationAxisFormat.ts
@@ -3,7 +3,13 @@ import posthog from 'posthog-js'
import { LemonSelectOptionLeaf } from 'lib/lemon-ui/LemonSelect'
import { formatCurrency } from 'lib/utils/currency'
import { humanFriendlyDuration } from 'lib/utils/durations'
-import { compactNumber, humanFriendlyCurrency, humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+import {
+ compactNumber,
+ humanFriendlyCurrency,
+ humanFriendlyNumber,
+ percentage,
+ significantDecimalPlaces,
+} from 'lib/utils/numbers'
import { CurrencyCode, TrendsFilter } from '~/queries/schema/schema-general'
import { ChartDisplayType, TrendsFilterType } from '~/types'
@@ -84,7 +90,11 @@ export const formatAggregationAxisValue = (
const aggregationAxisPostfix =
(trendsFilter as TrendsFilter)?.aggregationAxisPostfix ??
(trendsFilter as Partial<TrendsFilterType>)?.aggregation_axis_postfix
- let formattedValue = humanFriendlyNumber(value, maxDecimalPlaces, minDecimalPlaces)
+ let formattedValue = humanFriendlyNumber(
+ value,
+ maxDecimalPlaces ?? significantDecimalPlaces(value, minDecimalPlaces),
+ minDecimalPlaces
+ )
if (aggregationAxisFormat) {
switch (aggregationAxisFormat) {
case 'duration':
@@ -97,10 +107,16 @@ export const formatAggregationAxisValue = (
formattedValue = formatNanoseconds(value)
break
case 'percentage':
- formattedValue = percentage(value / 100, maxDecimalPlaces)
+ formattedValue = percentage(
+ value / 100,
+ maxDecimalPlaces ?? significantDecimalPlaces(value, minDecimalPlaces)
+ )
break
case 'percentage_scaled':
- formattedValue = percentage(value, maxDecimalPlaces)
+ formattedValue = percentage(
+ value,
+ maxDecimalPlaces ?? significantDecimalPlaces(value * 100, minDecimalPlaces)
+ )
break
case 'currency':
// In the rare case where we get an error because we have an invalid currency code
diff --git a/frontend/src/scenes/insights/aggregationAxisFormats.test.ts b/frontend/src/scenes/insights/aggregationAxisFormats.test.ts
index 66881aa68903..b64ed0e84c07 100644
--- a/frontend/src/scenes/insights/aggregationAxisFormats.test.ts
+++ b/frontend/src/scenes/insights/aggregationAxisFormats.test.ts
@@ -84,6 +84,12 @@ describe('formatAggregationAxisValue', () => {
{ candidate: 0.8709423, filters: { decimalPlaces: 3 }, expected: '0.871' },
{ candidate: 0.8709423, filters: { decimal_places: 9 }, expected: '0.8709423' },
{ candidate: 0.8709423, filters: { decimal_places: -1 }, expected: '0.87' }, // Fall back to default for unsupported values
+ { candidate: 0.012, filters: {}, expected: '0.012' },
+ { candidate: 0.002, filters: {}, expected: '0.002' },
+ { candidate: 0.00012345, filters: {}, expected: '0.00012' },
+ { candidate: 0.012, filters: { decimal_places: 2 }, expected: '0.01' },
+ { candidate: 0.005, filters: { aggregation_axis_format: 'percentage' }, expected: '0.005%' },
+ { candidate: 0.0123456, filters: { aggregation_axis_format: 'percentage_scaled' }, expected: '1.23%' },
]
formatTestcases.forEach((testcase) => {
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 0ac6ffa1f1ca..5ec79f8e8f71 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -85,7 +85,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`; `sparklineDashedFromIndex` dashes the sparkline from that index onward (e.g. an in-progress trailing period). `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point). `changeTooltip` shows a styled hover tooltip (floating-ui, using the host's tooltip surface tokens with chart-surface fallbacks) on the change pill (e.g. to spell out what the resting comparison is).
- The composable form of `MetricCard` lives one layer up as `Metric` in `@posthog/quill-components` (it needs `Card`/`Badge` from primitives, which charts can't depend on). It's built on `Sparkline` plus the headless metric helpers this package exports — `resolveDelta` / `computeFallbackChangePercent` (delta math), `useAnimatedNumber` (count-up headline), `useHoverIntent` (hover dwell) — and the `MetricChange` / `ResolvedDelta` types. Reach for `Metric` when you need a custom layout; use the monolithic `MetricCard` here for the default self-contained tile.
- `TimeSeriesComboChart` wraps `ComboChart` the way `TimeSeriesLineChart`/`TimeSeriesBarChart` wrap their base charts: `config.xAxis`/`config.yAxis` (date tick formatter, y-format, scale, grid), `config.goalLines` (off-scale targets stretch the value axis via `ComboChart`'s `valueDomain`), `config.legend` (click-to-toggle), and `config.valueLabels`. Per-series `type` (`'bar' | 'line' | 'area'`) drives rendering; `barLayout` (`'stacked' | 'grouped' | 'percent'`), `divergingStack` (stacked only — negative bar values stack below the zero baseline instead of being clamped to 0, same semantics as `BarsConfig.divergingStack`), and right-axis series (`yAxisId: 'right'`) carry over from `ComboChart`. `ComboChart` itself now also honors `valueDomain` (primary axis only) and `showAxisLines`.
-- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration_ms | duration_ns`, plus `prefix`/`suffix`.
+- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration_ms | duration_ns`, plus `prefix`/`suffix`. Numeric and percentage ticks default to two decimals but gain a decimal per leading zero below 0.1, so a small-valued axis (say latency in seconds over 0–0.012) doesn't render every tick as `0.01`; `decimalPlaces` pins the precision instead.
- y-axis baseline: defaults to clamping a non-negative axis down to 0 (matching the classic insight axis). To float the axis to its data range instead — zooming in on the variation — set `yAxis.startAtZero: false` on `TimeSeriesLineChart`, or `config.floatBaseline: true` on the lower-level `LineChart`. Ignored on a log scale (no zero baseline) and applied to the primary axis only. Bar charts always draw from a zero baseline, so the flag is a no-op there.
- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. Duration formatters accept seconds (`duration`), milliseconds (`duration_ms`), or nanoseconds (`duration_ns`). `hide` and `startAtZero` are honored per entry (bar-series axes keep their zero baseline). A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. More than two axes work too (trends `showMultipleYAxes`): they stack outward per side and alternate sides. Each entry's `label` renders that axis's title at its own gutter — every axis is titled the same way (a single-object `yAxis`/scalar `yAxisLabel` is just the one left axis), driven by the shared `computeYAxisGutters` layout that `AxisLabels` (ticks) and `AxisTitles` (titles) both read so the two can't drift. `TimeSeriesBarChart`/`TimeSeriesComboChart` take the same `yAxis` array; a sole axis pinned `right` renders on the right on every chart type.
- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/`BarChart`/`TimeSeriesBarChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. Despite the name it is label-generic — it resolves the drag against label positions, so it works the same on categorical labels (weekdays, duration buckets) as on dates. A drag whose edges both snap to the same label (common on sparse charts, e.g. a 3-bar monthly chart) selects that single bucket, provided the drag spans enough horizontal distance to read as intentional. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis (`axisOrientation: 'horizontal'` bars, where the core disables the gesture).
diff --git a/packages/quill/packages/charts/src/core/scales.test.ts b/packages/quill/packages/charts/src/core/scales.test.ts
index 537cdecc69c8..973724bcc479 100644
--- a/packages/quill/packages/charts/src/core/scales.test.ts
+++ b/packages/quill/packages/charts/src/core/scales.test.ts
@@ -689,6 +689,17 @@ describe('hog-charts scales', () => {
expect(autoFormatYTick(value, domainMax)).toBe(expected)
})
+ it.each([
+ { domainMax: 0.012, value: 0.012, expected: '0.012' },
+ { domainMax: 0.012, value: 0.002, expected: '0.002' },
+ { domainMax: 0.0005, value: 0.0001, expected: '0.0001' },
+ ])(
+ 'scales precision to the domain so small ticks stay distinct: $value over 0–$domainMax → $expected',
+ ({ domainMax, value, expected }) => {
+ expect(autoFormatYTick(value, domainMax)).toBe(expected)
+ }
+ )
+
it('formats zero correctly when domainMax is large', () => {
expect(autoFormatYTick(0, 100)).toBe('0')
})
diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.ts
index 07f9aa36a5c0..587101e88020 100644
--- a/packages/quill/packages/charts/src/core/scales.ts
+++ b/packages/quill/packages/charts/src/core/scales.ts
@@ -10,6 +10,7 @@ import {
} from 'd3-scale'
import { stack as stackGen, stackOffsetDiverging, stackOffsetExpand, stackOffsetNone } from 'd3-shape'
+import { significantDecimalPlaces } from '../utils/format'
import type { BandSlot, ChartDimensions, ResolveValueFn, Series, ValueDomain, YAxisScale } from './types'
import { DEFAULT_Y_AXIS_ID } from './types'
@@ -728,7 +729,12 @@ function padValueRange(
export function autoFormatYTick(value: number, domainMax: number): string {
if (domainMax < 2) {
- return value.toFixed(2)
+ // Two decimals only resolve a domain down to ~0.1; below that every tick rounds to the same
+ // label, so scale the precision to the domain instead.
+ return value.toLocaleString('en-US', {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: significantDecimalPlaces(domainMax),
+ })
}
if (domainMax < 5) {
return value.toFixed(1)
diff --git a/packages/quill/packages/charts/src/utils/format.ts b/packages/quill/packages/charts/src/utils/format.ts
index 9527f15b3603..88f5710c5ec5 100644
--- a/packages/quill/packages/charts/src/utils/format.ts
+++ b/packages/quill/packages/charts/src/utils/format.ts
@@ -17,6 +17,21 @@ function validateFractionDigits(maximumFractionDigits: number, fallback: number)
return maximumFractionDigits
}
+const MAX_SIGNIFICANT_DECIMAL_PLACES = 10
+
+/** Fraction digits needed to keep two significant digits — `minimum` for anything at or above 0.1,
+ * one more for every extra leading zero below that, capped so float residue doesn't render as a wall
+ * of digits. A flat two decimals collapses a small-valued axis into repeated labels: ticks over
+ * 0–0.012 all round to "0.01" or "0". `minimum` is nullable because adapters pass a nullable config
+ * field through. */
+export function significantDecimalPlaces(value: number, minimum?: number | null): number {
+ const floor = validateFractionDigits(minimum ?? DEFAULT_DECIMAL_PLACES, DEFAULT_DECIMAL_PLACES)
+ if (!isFinite(value) || value === 0) {
+ return floor
+ }
+ return Math.min(Math.max(floor, 1 - Math.floor(Math.log10(Math.abs(value)))), MAX_SIGNIFICANT_DECIMAL_PLACES)
+}
+
export function humanFriendlyNumber(
d: number,
maximumFractionDigits: number = DEFAULT_DECIMAL_PLACES,
diff --git a/packages/quill/packages/charts/src/utils/y-formatters.test.ts b/packages/quill/packages/charts/src/utils/y-formatters.test.ts
index 8c171d04ab13..1ffaeb30781d 100644
--- a/packages/quill/packages/charts/src/utils/y-formatters.test.ts
+++ b/packages/quill/packages/charts/src/utils/y-formatters.test.ts
@@ -1,4 +1,4 @@
-import { buildYTickFormatter } from './y-formatters'
+import { buildYTickFormatter, type YAxisFormat } from './y-formatters'
const NBSP = ' '
@@ -36,5 +36,27 @@ describe('buildYTickFormatter', () => {
it('respects decimalPlaces for numeric format', () => {
const fmt = buildYTickFormatter({ format: 'numeric', decimalPlaces: 2 })
expect(fmt(1.2345)).toBe('1.23')
+ expect(fmt(0.012)).toBe('0.01')
+ })
+
+ const smallTickCases: { format: YAxisFormat; ticks: number[]; expected: string[] }[] = [
+ {
+ format: 'numeric',
+ ticks: [0, -0.002, 0.002, 0.008, 0.01, 0.012],
+ expected: ['0', '-0.002', '0.002', '0.008', '0.01', '0.012'],
+ },
+ { format: 'percentage', ticks: [0.005, 0.01], expected: ['0.005%', '0.01%'] },
+ { format: 'percentage_scaled', ticks: [0.00005, 0.0001], expected: ['0.005%', '0.01%'] },
+ ]
+
+ it.each(smallTickCases)('keeps small $format ticks distinct', ({ format, ticks, expected }) => {
+ const fmt = buildYTickFormatter({ format })
+ expect(ticks.map((tick) => fmt(tick))).toEqual(expected)
+ })
+
+ // Adapters pass a nullable config field straight through, and null coerces to 0 in `Math.max`
+ it('floors precision at two decimals when minDecimalPlaces is null', () => {
+ const fmt = buildYTickFormatter({ format: 'numeric', minDecimalPlaces: null as unknown as number })
+ expect(fmt(1.2345)).toBe('1.23')
})
})
diff --git a/packages/quill/packages/charts/src/utils/y-formatters.ts b/packages/quill/packages/charts/src/utils/y-formatters.ts
index 5cf93b9a2131..093f906e834c 100644
--- a/packages/quill/packages/charts/src/utils/y-formatters.ts
+++ b/packages/quill/packages/charts/src/utils/y-formatters.ts
@@ -5,6 +5,7 @@ import {
humanFriendlyDuration,
humanFriendlyNumber,
percentage,
+ significantDecimalPlaces,
} from './format'
export type YAxisFormat =
@@ -45,7 +46,11 @@ function formatNanoseconds(value: number): string {
export function buildYTickFormatter(config: YFormatterConfig): (value: number) => string {
const { format, prefix, suffix, decimalPlaces, minDecimalPlaces, currency } = config
return (value: number): string => {
- let formatted = humanFriendlyNumber(value, decimalPlaces, minDecimalPlaces)
+ let formatted = humanFriendlyNumber(
+ value,
+ decimalPlaces ?? significantDecimalPlaces(value, minDecimalPlaces),
+ minDecimalPlaces
+ )
switch (format) {
case 'duration':
formatted = humanFriendlyDuration(value)
@@ -57,10 +62,10 @@ export function buildYTickFormatter(config: YFormatterConfig): (value: number) =
formatted = formatNanoseconds(value)
break
case 'percentage':
- formatted = percentage(value / 100, decimalPlaces)
+ formatted = percentage(value / 100, decimalPlaces ?? significantDecimalPlaces(value, minDecimalPlaces))
break
case 'percentage_scaled':
- formatted = percentage(value, decimalPlaces)
+ formatted = percentage(value, decimalPlaces ?? significantDecimalPlaces(value * 100, minDecimalPlaces))
break
case 'currency':
try {