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(quill-charts): add a time x scale to time series line charts (#127292)

Sam Pennington53398490246f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 3c5768f971b5..f58720b189d6 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1564,6 +1564,10 @@ snapshots:
hash: v1.k794b7964.8b96c539f190a68acd91a3f45b064fb35c287eb42c026c252d54dc7518be21e4.Ma8lGNVFpVb_79Fs5pUDBJQWJb4HSlfOKnoNFPbEFXo
components-hogcharts-timeserieslinechart--start-at-zero--light:
hash: v1.k794b7964.c8d69212e98a1690b10aa0452f9addf1afbaa2c5d8430f29928905874542cbcf.2bGtOgJFy_0JdlDEo5wQj6jVRwzQDbPP-hRp5bR7vro
+ components-hogcharts-timeserieslinechart--time-scale--dark:
+ hash: v1.k794b7964.00797dd065019207fce650c0094f08a735062e4cb3c8693b3d479f0f8d69617f.9cQxUXU3P6ThTL4tnvjBp8ccQj16c3M3hhBORK0FlEo
+ components-hogcharts-timeserieslinechart--time-scale--light:
+ hash: v1.k794b7964.555c5ae439c1546c05f25839b6e7d19e5eca1a4e31a6ee2aaaee375ead906ee9.8Efnz1p05sBd3J7iRi-GQ1erSEq86cJJCpyHjIm0-sc
components-hogcharts-timeserieslinechart--trend-lines--dark:
hash: v1.k794b7964.4d5a8d344fd57bb3d23edccf5bbcd73a293820083e5ed9f2c25f5bc439dba3ed.am33OiZY-lTm4WRE_NQKTyorQpZqkkA-f_sX1Hx46hA
components-hogcharts-timeserieslinechart--trend-lines--light:
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
index 788da1e2e8b0..4a6404adbbe6 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
@@ -22,7 +22,7 @@ import {
PERCENTAGE_SERIES,
SERIES,
} from '../time-series-fixtures'
-import { TimeSeriesLineChart } from './TimeSeriesLineChart'
+import { TimeSeriesLineChart, type TimeSeriesLineChartConfig } from './TimeSeriesLineChart'
const meta: Meta = {
title: 'Components/HogCharts/TimeSeriesLineChart',
@@ -377,3 +377,48 @@ export const DateAxis: Story = {
)
},
}
+
+const SPARSE_HOURS = [0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 20]
+const SPARSE_LABELS = SPARSE_HOURS.map((h) => `2026-03-01T${String(h).padStart(2, '0')}:00:00Z`)
+const SPARSE_SERIES: Series[] = [
+ {
+ key: 'rps',
+ label: 'Requests',
+ data: SPARSE_HOURS.map((h) => 200 + 60 * Math.sin(h / 3)),
+ fill: { opacity: 0.2 },
+ },
+]
+const WHOLE_DAY = [Date.parse('2026-03-01T00:00:00Z'), Date.parse('2026-03-02T00:00:00Z')] as const
+
+export const TimeScale: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const cells: { title: string; config: TimeSeriesLineChartConfig }[] = [
+ { title: 'index (default)', config: {} },
+ { title: "xScale: 'time'", config: { xScale: 'time' } },
+ { title: "xScale: 'time', xDomain: whole day", config: { xScale: 'time', xDomain: WHOLE_DAY } },
+ ]
+ return (
+ // eslint-disable-next-line react/forbid-dom-props
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, auto)', gap: 24 }}>
+ {cells.map(({ title, config }) => (
+ <div key={title}>
+ <div>{title}</div>
+ <Stage width={360} height={200}>
+ <TimeSeriesLineChart
+ series={SPARSE_SERIES}
+ labels={SPARSE_LABELS}
+ theme={theme}
+ config={{
+ xAxis: { timezone: 'UTC', interval: 'hour' },
+ yAxis: { showGrid: true },
+ ...config,
+ }}
+ />
+ </Stage>
+ </div>
+ ))}
+ </div>
+ )
+ },
+}
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
index db03fb6023da..a30918819f53 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
@@ -53,6 +53,39 @@ describe('TimeSeriesLineChart', () => {
expect(bottomMargin).toBe(76)
})
+ describe('config.xScale', () => {
+ const TIME_LABELS = ['2026-03-01T00:00:00Z', '2026-03-01T01:00:00Z', '2026-03-01T04:00:00Z']
+
+ it.each([
+ ['spaces points evenly by default', {}, [0, 0.5, 1]],
+ ["places points by time with xScale: 'time'", { xScale: 'time' as const }, [0, 0.25, 1]],
+ [
+ 'spans xDomain and drops points outside it',
+ {
+ xScale: 'time' as const,
+ xDomain: [Date.parse('2026-03-01T01:00:00Z'), Date.parse('2026-03-01T03:00:00Z')] as const,
+ },
+ [null, 0, null],
+ ],
+ ])('%s', (_, config, expectedFractions) => {
+ let fractions: (number | null)[] = []
+ function Measure(): null {
+ const { scales, dimensions } = useChartLayout()
+ fractions = TIME_LABELS.map((label) => {
+ const x = scales.x(label)
+ return x == null ? null : (x - dimensions.plotLeft) / dimensions.plotWidth
+ })
+ return null
+ }
+ renderChart(
+ <TimeSeriesLineChart series={SERIES} labels={TIME_LABELS} theme={THEME} config={config}>
+ <Measure />
+ </TimeSeriesLineChart>
+ )
+ expect(fractions).toEqual(expectedFractions)
+ })
+ })
+
describe('config.xAxis', () => {
it('hides x-axis ticks when xAxis.hide is true', () => {
const { chart } = renderChart(
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index eca0e2401bb1..e13fe0f4c437 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -24,6 +24,7 @@ import {
type MovingAverageConfig,
type TrendLineConfig,
} from '../utils/use-derived-series'
+import { useTimeScale } from '../utils/use-time-scale'
import { useGoalLines, useTimeSeries, useValueBounds } from '../utils/use-time-series'
import type { ValueLabelsConfig } from '../utils/use-value-labels'
@@ -59,6 +60,11 @@ export interface TimeSeriesLineChartConfig {
showTickMarks?: boolean
/** Line interpolation: `linear` (default) or `monotone` (smooth curve through every point). */
curve?: 'linear' | 'monotone'
+ /** `time` places each point at its time, so uneven spacing and gaps in time show. Labels must
+ * be ascending. Moving averages still use sample order. Defaults to `index`. */
+ xScale?: 'index' | 'time'
+ /** With `xScale: 'time'`, the axis span as `[from, to]` epoch ms. Defaults to the label range. */
+ xDomain?: readonly [number, number]
/** Tooltip behaviour and built-in content options. A `tooltip` render prop replaces the content. */
tooltip?: TooltipConfig
/** Built-in legend with click-to-toggle series visibility. Hidden by default. */
@@ -117,9 +123,12 @@ export function TimeSeriesLineChart<Meta = unknown>({
showAxisLines,
showTickMarks,
curve,
+ xScale,
+ xDomain,
tooltip: tooltipConfig,
legend,
} = config ?? {}
+ const timeScale = useTimeScale(xScale === 'time', labels, xAxis?.timezone ?? 'UTC', xDomain)
const {
xTickFormatter,
yTickFormatter,
@@ -132,11 +141,13 @@ export function TimeSeriesLineChart<Meta = unknown>({
} = useTimeSeries(series, labels, theme, { xAxis, yAxis, valueLabels, legend })
const timeSeriesTooltipConfig = useTimeSeriesTooltipConfig(tooltipConfig, xAxis, labels)
+ const timeXs = useMemo(() => (timeScale ? labels.map(timeScale.parse) : undefined), [timeScale, labels])
const finalSeries = useDerivedSeries(chartSeries, {
confidenceIntervals,
movingAverage,
trendLines,
comparisonOf,
+ xs: timeXs,
})
// Goal lines scale against the drawn (post-derived) series, unlike bar/combo.
@@ -167,6 +178,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
showAxisLines,
showTickMarks,
curve,
+ timeScale,
percentStackView,
showCrosshair,
tooltip: timeSeriesTooltipConfig,
diff --git a/packages/quill/packages/charts/src/charts/utils/derived-series.test.ts b/packages/quill/packages/charts/src/charts/utils/derived-series.test.ts
index b2f2fa62b648..1339a6403c04 100644
--- a/packages/quill/packages/charts/src/charts/utils/derived-series.test.ts
+++ b/packages/quill/packages/charts/src/charts/utils/derived-series.test.ts
@@ -80,13 +80,29 @@ describe('buildTrendLineSeries', () => {
expect(tl.overlay).toBe(true)
})
+ const EPOCH_XS = [0, 1000, 4000].map((ms) => Date.parse('2026-03-01T00:00:00Z') + ms)
it.each([
- ['linear', [10, 12, 14, 16, 18, 20, 22], 'linear', undefined, 10, 22],
- ['exponential, all positive (y=2^x)', [1, 2, 4, 8, 16, 32, 64], 'exponential', undefined, 1, 64],
- ['exponential, non-positive falls back to linear y=x-1', [-1, 0, 1, 2], 'exponential', undefined, -1, 2],
- ['exponential, zero in tail with fitUpTo skipping it', [1, 2, 4, 8, 0], 'exponential', 4, 1, 16],
- ] as const)('fits %s', (_label, data, kind, fitUpTo, expectedFirst, expectedLast) => {
- const tl = buildTrendLineSeries({ sourceSeries: { ...SOURCE, data: [...data] }, kind, fitUpTo })
+ ['linear', [10, 12, 14, 16, 18, 20, 22], 'linear', undefined, undefined, 10, 22],
+ ['exponential, all positive (y=2^x)', [1, 2, 4, 8, 16, 32, 64], 'exponential', undefined, undefined, 1, 64],
+ [
+ 'exponential, non-positive falls back to linear y=x-1',
+ [-1, 0, 1, 2],
+ 'exponential',
+ undefined,
+ undefined,
+ -1,
+ 2,
+ ],
+ ['exponential, zero in tail with fitUpTo skipping it', [1, 2, 4, 8, 0], 'exponential', 4, undefined, 1, 16],
+ ['linear at epoch times', [0, 1, 4], 'linear', undefined, EPOCH_XS, 0, 4],
+ ['exponential at epoch times', [1, 2, 16], 'exponential', undefined, EPOCH_XS, 1, 16],
+ ] as const)('fits %s', (_label, data, kind, fitUpTo, xs, expectedFirst, expectedLast) => {
+ const tl = buildTrendLineSeries({
+ sourceSeries: { ...SOURCE, data: [...data] },
+ kind,
+ fitUpTo,
+ xs: xs ? [...xs] : undefined,
+ })
expect(tl.data).toHaveLength(data.length)
expect(tl.data.every(Number.isFinite)).toBe(true)
expect(tl.data[0]).toBeCloseTo(expectedFirst, 2)
diff --git a/packages/quill/packages/charts/src/charts/utils/derived-series.ts b/packages/quill/packages/charts/src/charts/utils/derived-series.ts
index 5b028709730a..a342763f4544 100644
--- a/packages/quill/packages/charts/src/charts/utils/derived-series.ts
+++ b/packages/quill/packages/charts/src/charts/utils/derived-series.ts
@@ -69,6 +69,8 @@ export interface BuildTrendLineSeriesInput<Meta = unknown> {
* trend is extrapolated across the full data range. Useful for excluding an
* in-progress tail so the partial bucket doesn't drag the slope. */
fitUpTo?: number
+ /** Each value's x position, such as its time. Defaults to the index. */
+ xs?: number[]
excluded?: boolean
}
@@ -79,8 +81,13 @@ export interface BuildTrendLineSeriesInput<Meta = unknown> {
* `applyComparisonDimming`). */
export function buildTrendLineSeries<Meta = unknown>(input: BuildTrendLineSeriesInput<Meta>): Series<Meta> {
const { sourceSeries, kind, fitUpTo } = input
+ // Epoch milliseconds are too large for the regression and cancel to NaN, so fit relative to the first x.
+ const origin = input.xs?.find((x) => isFinite(x)) ?? 0
+ const xs = input.xs?.map((x) => x - origin)
const data =
- kind === 'exponential' ? exponentialTrend(sourceSeries.data, fitUpTo) : trendLine(sourceSeries.data, fitUpTo)
+ kind === 'exponential'
+ ? exponentialTrend(sourceSeries.data, fitUpTo, xs)
+ : trendLine(sourceSeries.data, fitUpTo, xs)
const baseColor = sourceSeries.color
return {
key: `${sourceSeries.key}__trendline`,
@@ -95,10 +102,11 @@ export function buildTrendLineSeries<Meta = unknown>(input: BuildTrendLineSeries
}
}
-function exponentialTrend(values: number[], fitUpTo?: number): number[] {
+function exponentialTrend(values: number[], fitUpTo?: number, xs?: number[]): number[] {
const n = values.length
+ const xAt = (i: number): number => xs?.[i] ?? i
if (n < 2) {
- return trendLine(values, fitUpTo)
+ return trendLine(values, fitUpTo, xs)
}
const fitEnd = fitUpTo != null ? Math.max(2, Math.min(fitUpTo, n)) : n
// Single pass: build the log-space coords and bail on the first non-positive value.
@@ -108,10 +116,10 @@ function exponentialTrend(values: number[], fitUpTo?: number): number[] {
for (let x = 0; x < fitEnd; x++) {
const y = values[x]
if (y <= 0) {
- return trendLine(values, fitUpTo)
+ return trendLine(values, fitUpTo, xs)
}
- coords.push([x, Math.log(y)])
+ coords.push([xAt(x), Math.log(y)])
}
const { m, b } = linearRegression(coords)
- return values.map((_, x) => Math.exp(m * x + b))
+ return values.map((_, i) => Math.exp(m * xAt(i) + b))
}
diff --git a/packages/quill/packages/charts/src/charts/utils/use-derived-series.ts b/packages/quill/packages/charts/src/charts/utils/use-derived-series.ts
index 5d1fbe46f0da..e79cb0469533 100644
--- a/packages/quill/packages/charts/src/charts/utils/use-derived-series.ts
+++ b/packages/quill/packages/charts/src/charts/utils/use-derived-series.ts
@@ -33,6 +33,8 @@ export interface DerivedSeriesOptions {
/** Map of comparison series key → its primary series key. Comparison series render
* at reduced opacity so they read as subordinate to their primary. */
comparisonOf?: Record<string, string>
+ /** Each data index's x position for trend lines, such as its time. Defaults to the index. */
+ xs?: number[]
}
/** Builds CI bands, moving averages, and trend lines from `source` and merges them
@@ -41,7 +43,7 @@ export interface DerivedSeriesOptions {
* dimming runs as a final pass. Returns the original `source` reference when no
* derived-series options are set. */
export function useDerivedSeries<Meta>(source: Series<Meta>[], options: DerivedSeriesOptions): Series<Meta>[] {
- const { confidenceIntervals, movingAverage, trendLines, comparisonOf } = options
+ const { confidenceIntervals, movingAverage, trendLines, comparisonOf, xs } = options
// Reduce each config to a primitive signature so callers passing inline configs
// (`config={{ trendLines: [...] }}`) don't reallocate the dep refs on every render
// and miss the cache. CI's lower/upper data arrays aren't included — we assume the
@@ -120,6 +122,7 @@ export function useDerivedSeries<Meta>(source: Series<Meta>[], options: DerivedS
kind: tl.kind,
label: tl.label,
fitUpTo: tl.fitUpTo,
+ xs,
excluded: found.visibility?.excluded,
})
)
@@ -129,7 +132,7 @@ export function useDerivedSeries<Meta>(source: Series<Meta>[], options: DerivedS
// The signatures above stand in for the four reference-typed config inputs; the
// raw refs are intentionally absent so inline-config callers don't bust the cache.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [source, ciSignature, maSignature, tlSignature, cmpSignature])
+ }, [source, ciSignature, maSignature, tlSignature, cmpSignature, xs])
}
/** Trend-line series for charts that render trends as an SVG overlay ({@link TrendLineOverlay})
diff --git a/packages/quill/packages/charts/src/charts/utils/use-time-scale.ts b/packages/quill/packages/charts/src/charts/utils/use-time-scale.ts
new file mode 100644
index 000000000000..3692d70ee03f
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/utils/use-time-scale.ts
@@ -0,0 +1,36 @@
+import { useMemo } from 'react'
+
+import type { TimeScale } from '../../core/types'
+import { parseDateInTimezone } from '../../utils/dayjs'
+
+export function useTimeScale(
+ enabled: boolean,
+ labels: string[],
+ timezone: string,
+ xDomain: readonly [number, number] | undefined
+): TimeScale | undefined {
+ const [domainFrom, domainTo] = xDomain ?? []
+ return useMemo(() => {
+ if (!enabled) {
+ return undefined
+ }
+ // The shared parse cache clears past 5,000 labels, so a long series would re-parse on every draw.
+ const epochs = new Map(labels.map((label) => [label, parseDateInTimezone(label, timezone).valueOf()]))
+ const parse = (label: string): number => epochs.get(label) ?? parseDateInTimezone(label, timezone).valueOf()
+ const domain: [number, number] =
+ domainFrom != null && domainTo != null ? [domainFrom, domainTo] : timeExtent(epochs.values())
+ return { parse, domain }
+ }, [enabled, labels, timezone, domainFrom, domainTo])
+}
+
+function timeExtent(times: Iterable<number>): [number, number] {
+ let from = Infinity
+ let to = -Infinity
+ for (const t of times) {
+ if (isFinite(t)) {
+ from = Math.min(from, t)
+ to = Math.max(to, t)
+ }
+ }
+ return from <= to ? [from, to] : [NaN, NaN]
+}
diff --git a/packages/quill/packages/charts/src/docs/axes.md b/packages/quill/packages/charts/src/docs/axes.md
index 3b8538ced5ae..06137c736ef9 100644
--- a/packages/quill/packages/charts/src/docs/axes.md
+++ b/packages/quill/packages/charts/src/docs/axes.md
@@ -29,6 +29,7 @@ Theme-side restyle knobs, all optional: `theme.axisLineColor` strokes the baseli
- Labels must be unique. The x-scale keys positions off the strings, so a duplicate collapses onto the first occurrence and draws the series backwards. On time-series charts pass ISO date strings, never formatted display labels that repeat across years. Set `xAxis.timezone` to format ticks and tooltip headers. The library infers the interval from `allDays` or chart labels; set `interval` only to override it. `tickFormatter` overrides automatic formatting.
- `xAxis.tickLabelRotation` (`-45` tilts left) fixes the rotation, clamped to `-90..90`. Omit it to keep horizontal labels and the collision behavior.
- `maxCategoryLabelWidth` truncates category labels with an ellipsis and reveals the full value on hover. It also clamps the axis margin, so a long label cannot push the plot off screen. On horizontal charts the cap grows to 30% of the chart width when that is wider, so a wider chart shows more of each label. `MAX_CATEGORY_LABEL_WIDTH` is the exported default.
+- `TimeSeriesLineChart` `xScale: 'time'` places each point at its time, so a stretch with no samples keeps its width. Labels parse in `xAxis.timezone` and must be ascending. `xDomain: [from, to]` in epoch ms spans the axis past the data. Ticks stay on the data labels.
- `LineChart` `timeScale: { parse, domain }` places each label at its time instead of evenly by index. `parse` returns epoch milliseconds, and labels outside `domain` are not drawn. Memoize the object.
## Y-axis format
diff --git a/packages/quill/packages/charts/src/utils/statistics.test.ts b/packages/quill/packages/charts/src/utils/statistics.test.ts
index c0be5ab02cd6..02c8ecb9901c 100644
--- a/packages/quill/packages/charts/src/utils/statistics.test.ts
+++ b/packages/quill/packages/charts/src/utils/statistics.test.ts
@@ -43,6 +43,10 @@ describe('trendLine', () => {
}
})
+ it('fits against x positions when given', () => {
+ expect(trendLine([0, 1, 4], undefined, [0, 1, 4])).toEqual([0, 1, 4])
+ })
+
it('fits over finite points only, ignoring gaps (NaN)', () => {
// The fit should follow y = x from the finite points; the gap must not poison it.
const result = trendLine([0, 1, NaN, 3, 4])
diff --git a/packages/quill/packages/charts/src/utils/statistics.ts b/packages/quill/packages/charts/src/utils/statistics.ts
index 7b2e41c71fbe..4527f5f8eb48 100644
--- a/packages/quill/packages/charts/src/utils/statistics.ts
+++ b/packages/quill/packages/charts/src/utils/statistics.ts
@@ -25,19 +25,21 @@ export function ciRanges(values: number[], ci: number = 0.95): [number[], number
return [lower, upper]
}
-export function trendLine(values: number[], fitUpTo?: number): number[] {
+/** `xs` gives each value's x position, such as its time. Defaults to the index. */
+export function trendLine(values: number[], fitUpTo?: number, xs?: number[]): number[] {
const n = values.length
const fitEnd = fitUpTo != null ? Math.max(2, Math.min(fitUpTo, n)) : n
+ const xAt = (i: number): number => xs?.[i] ?? i
// Fit only over finite points so a single gap doesn't poison the regression.
const coordinates: [number, number][] = values
.slice(0, fitEnd)
- .map((y, x): [number, number] => [x, y])
- .filter(([, y]) => isFinite(y))
+ .map((y, i): [number, number] => [xAt(i), y])
+ .filter(([x, y]) => isFinite(x) && isFinite(y))
if (coordinates.length < 2) {
return values.slice()
}
const { m, b } = linearRegression(coordinates)
- return values.map((_, x) => m * x + b)
+ return values.map((_, i) => m * xAt(i) + b)
}
export function movingAverage(values: number[], intervals: number = 7): number[] {