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(hog-charts): add confidenceIntervals + movingAverage config to TimeSeriesLineChart (#57487)

Sam Penningtona9ebc1eb5954
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a2e95e58f419..c5e09fbff363 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -580,10 +580,18 @@ snapshots:
hash: v1.k794b7964.529535e435c93c8f004cdba8f2ba29681dd679eb9bfbaff745a5f00c3b424ffd.2Kq3-2B9F2VNlkrFY-dge3vntnfrudonJ-Lle1s8m5E
components-hogcharts-timeserieslinechart--basic--light:
hash: v1.k794b7964.3a097fd7390b5a54fcf6e20a1769cc9058b66f4d040ed58748d0d4dc55c8788b.zqLqP936uYDq025ot6wQL3TxRVnq4UzQAtiS92DFZp8
+ components-hogcharts-timeserieslinechart--confidence-intervals--dark:
+ hash: v1.k794b7964.604addbe746f827ade2350d9167a72d9a7fbedfd96bd621a7af7994cd489c4c8.M3UGtYXBVSJzocWg4vxO3GwAXWveRgWHTGCql8iWjec
+ components-hogcharts-timeserieslinechart--confidence-intervals--light:
+ hash: v1.k794b7964.748b89470fc51d7943898d2c1b472c4a7c707251324be0d22e8fd8555e457afb.syed-39Rp1r--wavVUlzOaZ08JQ8kE1KgP4OCKvSrDw
components-hogcharts-timeserieslinechart--date-axis--dark:
hash: v1.k794b7964.5805c3a1a9848b678164dcb7f71f6e6df63feb0528585a035d46ca9494080129.e7jpy3cDRnVfLZFjsQcScQdz8mwwULxW5TsnWUE_Rq4
components-hogcharts-timeserieslinechart--date-axis--light:
hash: v1.k794b7964.7a2951f2481faf207966615e374818fb43d30ae3f16aeb2af836bc6955d80d77.WNimlXEb2nRgkA5J86byjnuJ3WUmvR_vb9glEJzoQJw
+ components-hogcharts-timeserieslinechart--moving-average--dark:
+ hash: v1.k794b7964.276935f8bb553e4ab9fac3ace6eebb3d28dfdf96cffe2e034fedb97e74ce37d0.5SBoJ3War_QIpdVFWyeow-y8o4S-qReI1UdVs9HO6Ik
+ components-hogcharts-timeserieslinechart--moving-average--light:
+ hash: v1.k794b7964.326fb129af77ff50842a525cabd6dc99bdda0184f67de96e57ad1c9a13be4ab3.e5Hz2jQlR4ZqIhUHnbbeFlfLsHNkw7_7_1JJqj1v2N0
components-hogcharts-timeserieslinechart--y-axis-formats--dark:
hash: v1.k794b7964.ab5470e4567b923b3414ddc27d0e40872a481d973df9e12d1765fbedff32c20d.JdA-hTR2nKp921x6JROPc0p43nBvLgWiXzJQRPLviMQ
components-hogcharts-timeserieslinechart--y-axis-formats--light:
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
index 0b7a8483ebb3..4909a9904d83 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
@@ -2,6 +2,7 @@ import { Meta, StoryObj } from '@storybook/react'
import { DEFAULT_Y_AXIS_ID, TimeSeriesLineChart } from 'lib/hog-charts'
import type { AnomalyMarker, Series, TimeInterval, YAxisConfig } from 'lib/hog-charts'
+import { ciRanges } from 'lib/statistics'
import { Stage, useReactiveTheme } from '../../story-helpers'
@@ -188,6 +189,52 @@ export const Anomalies: Story = {
},
}
+const DERIVED_SERIES: Series[] = [
+ { key: 'visits', label: 'Visits', data: [20, 35, 28, 60, 45, 70, 52] },
+ { key: 'signups', label: 'Sign-ups', data: [4, 8, 6, 14, 11, 19, 13] },
+]
+const [DERIVED_CI_LOWER, DERIVED_CI_UPPER] = ciRanges(DERIVED_SERIES[0].data, 0.95)
+
+export const ConfidenceIntervals: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage>
+ <TimeSeriesLineChart
+ series={DERIVED_SERIES}
+ labels={DAYS}
+ theme={theme}
+ config={{
+ yAxis: { showGrid: true },
+ confidenceIntervals: [
+ { seriesKey: 'visits', lower: DERIVED_CI_LOWER, upper: DERIVED_CI_UPPER },
+ ],
+ }}
+ />
+ </Stage>
+ )
+ },
+}
+
+export const MovingAverage: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage>
+ <TimeSeriesLineChart
+ series={DERIVED_SERIES}
+ labels={DAYS}
+ theme={theme}
+ config={{
+ yAxis: { showGrid: true },
+ movingAverage: [{ seriesKey: 'visits', window: 3 }],
+ }}
+ />
+ </Stage>
+ )
+ },
+}
+
export const DateAxis: Story = {
render: () => {
const cells: { interval: TimeInterval; labels: string[]; series: Series[]; title: string }[] = [
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
index 7d4a155afb49..936bcd64b3e8 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
@@ -251,6 +251,19 @@ describe('TimeSeriesLineChart', () => {
})
})
+ describe('derived-series wiring', () => {
+ it.each([
+ ['confidenceIntervals', { confidenceIntervals: [{ seriesKey: 'a', lower: [0, 1, 2], upper: [2, 3, 4] }] }],
+ ['movingAverage', { movingAverage: [{ seriesKey: 'a', window: 2 }] }],
+ ])('plumbs config.%s through to the rendered series count', (_, derivedConfig) => {
+ const { chart } = renderHogChart(
+ <TimeSeriesLineChart series={SERIES} labels={LABELS} theme={THEME} config={derivedConfig} />
+ )
+ // SERIES has 1 entry; each derived block adds one more series.
+ expect(chart.seriesCount).toBe(2)
+ })
+ })
+
it('forwards children alongside built-in overlays', () => {
const { container } = renderHogChart(
<TimeSeriesLineChart series={SERIES} labels={LABELS} theme={THEME}>
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index 67fc0faa49dd..1297f07ed628 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -8,18 +8,23 @@ import { AnomalyPointsLayer, type AnomalyMarker } from './overlays/AnomalyPoints
import { buildGoalLineReferenceLines, type GoalLineConfig } from './utils/goal-lines'
import { applyInProgressToSeries, type InProgressConfig } from './utils/in-progress'
import { useXTickFormatter, useYTickFormatter, type XAxisConfig, type YAxisConfig } from './utils/use-axis-formatters'
+import { useDerivedSeries, type ConfidenceIntervalConfig, type MovingAverageConfig } from './utils/use-derived-series'
export interface ValueLabelsConfig {
seriesKeys?: string[]
formatter?: (value: number) => string
}
+export type { ConfidenceIntervalConfig, MovingAverageConfig }
+
export interface TimeSeriesLineChartConfig {
xAxis?: XAxisConfig
yAxis?: YAxisConfig
inProgress?: InProgressConfig
valueLabels?: boolean | ValueLabelsConfig
goalLines?: GoalLineConfig[]
+ confidenceIntervals?: ConfidenceIntervalConfig[]
+ movingAverage?: MovingAverageConfig[]
/** Anomaly markers rendered as filled circles on top of the chart. */
anomalies?: AnomalyMarker[]
}
@@ -57,7 +62,8 @@ export function TimeSeriesLineChart<Meta = unknown>({
className,
children,
}: TimeSeriesLineChartProps<Meta>): React.ReactElement {
- const { xAxis, yAxis, inProgress, valueLabels, goalLines, anomalies } = config ?? {}
+ const { xAxis, yAxis, inProgress, valueLabels, goalLines, confidenceIntervals, movingAverage, anomalies } =
+ config ?? {}
const xTickFormatter = useXTickFormatter(xAxis, labels)
const yTickFormatter = useYTickFormatter(yAxis)
@@ -65,13 +71,16 @@ export function TimeSeriesLineChart<Meta = unknown>({
const seriesWithInProgress = useMemo(
() => applyInProgressToSeries(series, inProgress),
+ // inProgress.fromIndex is the only field applyInProgressToSeries reads; depending
+ // on `inProgress` itself would invalidate on every inline-config render.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
[series, inProgress?.fromIndex]
)
// Stable primitive key so callers can pass `valueLabels: { seriesKeys: ['a'] }` inline
// without re-running the transform on every render.
const seriesKeysSignature = valueLabelsConfig?.seriesKeys?.join(' ')
- const transformedSeries = useMemo(() => {
+ const seriesAfterValueLabels = useMemo(() => {
const seriesKeys = valueLabelsConfig?.seriesKeys
if (!seriesKeys) {
return seriesWithInProgress
@@ -83,12 +92,14 @@ export function TimeSeriesLineChart<Meta = unknown>({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [seriesWithInProgress, seriesKeysSignature])
+ const finalSeries = useDerivedSeries(seriesAfterValueLabels, {
+ confidenceIntervals,
+ movingAverage,
+ })
+
const valueLabelFormatter = valueLabelsConfig ? (valueLabelsConfig.formatter ?? yTickFormatter) : undefined
- const referenceLines = useMemo(
- () => buildGoalLineReferenceLines(goalLines, transformedSeries),
- [goalLines, transformedSeries]
- )
+ const referenceLines = useMemo(() => buildGoalLineReferenceLines(goalLines, finalSeries), [goalLines, finalSeries])
const lineChartConfig: LineChartConfig = {
yScaleType: yAxis?.scale,
@@ -101,7 +112,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
return (
<LineChart
- series={transformedSeries}
+ series={finalSeries}
labels={labels}
config={lineChartConfig}
theme={theme}
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.test.ts b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.test.ts
new file mode 100644
index 000000000000..c5f56f7fef97
--- /dev/null
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.test.ts
@@ -0,0 +1,66 @@
+import type { Series } from '../../../core/types'
+import { buildConfidenceIntervalSeries, buildMovingAverageSeries } from './derived-series'
+
+const SOURCE: Series = {
+ key: 'visits',
+ label: 'Visits',
+ data: [10, 12, 14, 16, 18, 20, 22],
+ color: '#336699',
+ yAxisId: 'y1',
+ meta: { domain: 'visits' },
+}
+
+describe('buildConfidenceIntervalSeries', () => {
+ it('returns a fill-between series keyed off the source seriesKey', () => {
+ const ci = buildConfidenceIntervalSeries({
+ seriesKey: SOURCE.key,
+ label: SOURCE.label,
+ baseColor: SOURCE.color,
+ lower: [9, 11, 13, 15, 17, 19, 21],
+ upper: [11, 13, 15, 17, 19, 21, 23],
+ yAxisId: SOURCE.yAxisId,
+ meta: SOURCE.meta,
+ })
+ expect(ci.key).toBe('visits__ci')
+ expect(ci.label).toBe('Visits (CI)')
+ expect(ci.data).toEqual([11, 13, 15, 17, 19, 21, 23])
+ expect(ci.color).toBe('#336699')
+ expect(ci.yAxisId).toBe('y1')
+ expect(ci.meta).toEqual({ domain: 'visits' })
+ expect(ci.fill?.lowerData).toEqual([9, 11, 13, 15, 17, 19, 21])
+ expect(ci.fill?.opacity).toBeGreaterThan(0)
+ expect(ci.visibility?.fromTooltip).toBe(true)
+ expect(ci.visibility?.fromValueLabels).toBe(true)
+ })
+
+ it('forwards the excluded flag so an excluded source hides the band', () => {
+ const ci = buildConfidenceIntervalSeries({
+ seriesKey: 'a',
+ label: 'A',
+ lower: [0],
+ upper: [1],
+ excluded: true,
+ })
+ expect(ci.visibility?.excluded).toBe(true)
+ })
+})
+
+describe('buildMovingAverageSeries', () => {
+ it('computes via movingAverage and styles a dashed overlay', () => {
+ const ma = buildMovingAverageSeries({ sourceSeries: SOURCE, window: 3 })
+ expect(ma.key).toBe('visits-ma')
+ expect(ma.label).toBe('Visits (Moving avg)')
+ expect(ma.data).toHaveLength(SOURCE.data.length)
+ expect(ma.data[3]).toBeCloseTo((14 + 16 + 18) / 3, 5)
+ expect(ma.color).toBe(SOURCE.color)
+ expect(ma.yAxisId).toBe(SOURCE.yAxisId)
+ expect(ma.stroke?.pattern).not.toBeUndefined()
+ expect(ma.visibility?.fromStack).toBe(true)
+ expect(ma.visibility?.fromTooltip).toBe(true)
+ })
+
+ it('uses an explicit label when provided', () => {
+ const ma = buildMovingAverageSeries({ sourceSeries: SOURCE, window: 3, label: 'Smoothed' })
+ expect(ma.label).toBe('Smoothed')
+ })
+})
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.ts b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.ts
new file mode 100644
index 000000000000..6c04e3bf13bc
--- /dev/null
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series.ts
@@ -0,0 +1,52 @@
+import { movingAverage } from 'lib/statistics'
+
+import type { Series } from '../../../core/types'
+
+const CI_FILL_OPACITY = 0.2
+const MA_DASH_PATTERN = [10, 3]
+
+export interface BuildConfidenceIntervalSeriesInput<Meta = unknown> {
+ seriesKey: string
+ label: string
+ baseColor?: string
+ lower: number[]
+ upper: number[]
+ yAxisId?: string
+ meta?: Meta
+ excluded?: boolean
+}
+
+export function buildConfidenceIntervalSeries<Meta = unknown>(
+ input: BuildConfidenceIntervalSeriesInput<Meta>
+): Series<Meta> {
+ return {
+ key: `${input.seriesKey}__ci`,
+ label: `${input.label} (CI)`,
+ data: input.upper,
+ color: input.baseColor,
+ yAxisId: input.yAxisId,
+ meta: input.meta,
+ fill: { opacity: CI_FILL_OPACITY, lowerData: input.lower },
+ visibility: { excluded: input.excluded, fromTooltip: true, fromValueLabels: true },
+ }
+}
+
+export interface BuildMovingAverageSeriesInput<Meta = unknown> {
+ sourceSeries: Series<Meta>
+ window: number
+ label?: string
+}
+
+export function buildMovingAverageSeries<Meta = unknown>(input: BuildMovingAverageSeriesInput<Meta>): Series<Meta> {
+ const { sourceSeries, window: windowSize } = input
+ return {
+ key: `${sourceSeries.key}-ma`,
+ label: input.label ?? `${sourceSeries.label} (Moving avg)`,
+ data: movingAverage(sourceSeries.data, windowSize),
+ color: sourceSeries.color,
+ yAxisId: sourceSeries.yAxisId,
+ meta: sourceSeries.meta,
+ stroke: { pattern: MA_DASH_PATTERN },
+ visibility: { fromTooltip: true, fromStack: true },
+ }
+}
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.test.ts b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.test.ts
new file mode 100644
index 000000000000..47c7bcd28cfe
--- /dev/null
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.test.ts
@@ -0,0 +1,33 @@
+import { renderHook } from '@testing-library/react'
+
+import type { Series } from '../../../core/types'
+import { useDerivedSeries } from './use-derived-series'
+
+const SOURCE: Series[] = [
+ { key: 'a', label: 'A', data: [1, 2, 3, 4], color: '#112233' },
+ { key: 'b', label: 'B', data: [5, 6, 7, 8], color: '#445566' },
+]
+
+describe('useDerivedSeries', () => {
+ it('returns the source reference unchanged when no options are set', () => {
+ const { result } = renderHook(() => useDerivedSeries(SOURCE, {}))
+ expect(result.current).toBe(SOURCE)
+ })
+
+ it('orders derived series CI → main → MA', () => {
+ const { result } = renderHook(() =>
+ useDerivedSeries(SOURCE, {
+ confidenceIntervals: [{ seriesKey: 'a', lower: [0, 1, 2, 3], upper: [2, 3, 4, 5] }],
+ movingAverage: [{ seriesKey: 'a', window: 2 }],
+ })
+ )
+ expect(result.current.map((s) => s.key)).toEqual(['a__ci', 'a', 'b', 'a-ma'])
+ })
+
+ it('skips derived entries whose seriesKey does not exist in source', () => {
+ const { result } = renderHook(() =>
+ useDerivedSeries(SOURCE, { movingAverage: [{ seriesKey: 'missing', window: 2 }] })
+ )
+ expect(result.current.map((s) => s.key)).toEqual(['a', 'b'])
+ })
+})
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.ts b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.ts
new file mode 100644
index 000000000000..557caa1f6655
--- /dev/null
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/utils/use-derived-series.ts
@@ -0,0 +1,106 @@
+import { useMemo } from 'react'
+
+import type { Series } from '../../../core/types'
+import { buildConfidenceIntervalSeries, buildMovingAverageSeries } from './derived-series'
+
+export interface ConfidenceIntervalConfig {
+ seriesKey: string
+ lower: number[]
+ upper: number[]
+}
+
+export interface MovingAverageConfig {
+ seriesKey: string
+ window: number
+ label?: string
+}
+
+export interface DerivedSeriesOptions {
+ confidenceIntervals?: ConfidenceIntervalConfig[]
+ movingAverage?: MovingAverageConfig[]
+}
+
+/** Builds CI bands and moving averages from `source` and merges them with the source
+ * series in paint order: CI behind, then main, then MA on top (matches
+ * `LineChart.drawStatic` array iteration). 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 } = options
+ // Reduce each config to a primitive signature so callers passing inline configs
+ // (`config={{ movingAverage: [...] }}`) 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
+ // caller hands us stable references when the underlying numbers haven't changed.
+ const ciSignature = ciSig(confidenceIntervals)
+ const maSignature = maSig(movingAverage)
+ return useMemo(() => {
+ const hasDerived =
+ (confidenceIntervals && confidenceIntervals.length > 0) || (movingAverage && movingAverage.length > 0)
+ if (!hasDerived) {
+ return source
+ }
+
+ const sourceByKey = new Map(source.map((s) => [s.key, s]))
+
+ const ciSeries: Series<Meta>[] = []
+ for (const ci of confidenceIntervals ?? []) {
+ const found = sourceByKey.get(ci.seriesKey)
+ if (!found) {
+ continue
+ }
+ ciSeries.push(
+ buildConfidenceIntervalSeries<Meta>({
+ seriesKey: found.key,
+ label: found.label,
+ baseColor: found.color,
+ lower: ci.lower,
+ upper: ci.upper,
+ yAxisId: found.yAxisId,
+ meta: found.meta,
+ excluded: found.visibility?.excluded,
+ })
+ )
+ }
+
+ const maSeries: Series<Meta>[] = []
+ for (const ma of movingAverage ?? []) {
+ const found = sourceByKey.get(ma.seriesKey)
+ if (!found) {
+ continue
+ }
+ maSeries.push(buildMovingAverageSeries<Meta>({ sourceSeries: found, window: ma.window, label: ma.label }))
+ }
+
+ return [...ciSeries, ...source, ...maSeries]
+ // The signatures above stand in for the two 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])
+}
+
+function ciSig(ci: ConfidenceIntervalConfig[] | undefined): string {
+ if (!ci?.length) {
+ return ''
+ }
+ // Identity of CI inputs: which series, and the lower/upper array refs.
+ // We avoid serialising the data arrays — array reference equality is the
+ // caller's contract for "values haven't changed."
+ return ci.map((c) => `${c.seriesKey}|${refKey(c.lower)}|${refKey(c.upper)}`).join(';')
+}
+
+function maSig(ma: MovingAverageConfig[] | undefined): string {
+ if (!ma?.length) {
+ return ''
+ }
+ return ma.map((m) => `${m.seriesKey}|${m.window}|${m.label ?? ''}`).join(';')
+}
+
+const refIds = new WeakMap<object, number>()
+let nextRefId = 1
+function refKey(arr: number[]): number {
+ let id = refIds.get(arr)
+ if (id === undefined) {
+ id = nextRefId++
+ refIds.set(arr, id)
+ }
+ return id
+}
diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.ts
index 17ec4cda3c2d..fbb6f307693a 100644
--- a/frontend/src/lib/hog-charts/index.ts
+++ b/frontend/src/lib/hog-charts/index.ts
@@ -5,6 +5,8 @@ export { LineChart } from './charts/LineChart'
export type { LineChartProps } from './charts/LineChart'
export { TimeSeriesLineChart } from './charts/TimeSeriesLineChart/TimeSeriesLineChart'
export type {
+ ConfidenceIntervalConfig,
+ MovingAverageConfig,
TimeSeriesLineChartConfig,
TimeSeriesLineChartProps,
ValueLabelsConfig,
diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts b/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts
index e7739efb5c53..83d83594a3ef 100644
--- a/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts
+++ b/frontend/src/scenes/trends/viz/trends-line-chart/trendsChartTransforms.ts
@@ -1,6 +1,10 @@
import { DEFAULT_Y_AXIS_ID } from 'lib/hog-charts'
import type { LineChartConfig, Series } from 'lib/hog-charts'
-import { ciRanges, movingAverage, trendLine } from 'lib/statistics'
+import {
+ buildConfidenceIntervalSeries,
+ buildMovingAverageSeries,
+} from 'lib/hog-charts/charts/TimeSeriesLineChart/utils/derived-series'
+import { ciRanges, trendLine } from 'lib/statistics'
import { hexToRGBA } from 'lib/utils'
import { ChartDisplayType } from '~/types'
@@ -82,45 +86,44 @@ function buildDerivedTrendsSeries<R extends TrendsResultLike, M = unknown>(
opts: BuildTrendsSeriesOpts<R, M>
): Series<M>[] {
const { main, baseColor, dashedFromIndex, excluded } = built
+ const label = r.label ?? ''
const out: Series<M>[] = []
if (opts.showConfidenceIntervals) {
const ci = (opts.confidenceLevel ?? 95) / 100
const [lower, upper] = ciRanges(r.data, ci)
- out.push({
- key: `${r.id}__ci`,
- label: `${r.label ?? ''} (CI)`,
- data: upper,
- color: main.color,
- yAxisId: main.yAxisId,
- meta: main.meta,
- fill: { opacity: 0.2, lowerData: lower },
- visibility: { excluded, fromTooltip: true, fromValueLabels: true },
- })
+ out.push(
+ buildConfidenceIntervalSeries<M>({
+ seriesKey: main.key,
+ label,
+ baseColor: main.color,
+ lower,
+ upper,
+ yAxisId: main.yAxisId,
+ meta: main.meta,
+ excluded,
+ })
+ )
}
+ let maSeries: Series<M> | undefined
if (
opts.showMovingAverage &&
opts.movingAverageIntervals !== undefined &&
r.data.length >= opts.movingAverageIntervals
) {
- const maData = movingAverage(r.data, opts.movingAverageIntervals)
- out.push({
- key: `${r.id}-ma`,
- label: `${r.label ?? ''} (Moving avg)`,
- data: maData,
- color: main.color,
- yAxisId: main.yAxisId,
- meta: main.meta,
- stroke: { pattern: [10, 3] },
- visibility: { fromTooltip: true, fromStack: true },
+ maSeries = buildMovingAverageSeries<M>({
+ sourceSeries: main,
+ window: opts.movingAverageIntervals,
+ label: `${label} (Moving avg)`,
})
+ out.push(maSeries)
if (opts.showTrendLines && !excluded) {
out.push({
key: `${r.id}-ma__trendline`,
- label: `${r.label ?? ''} (Moving avg)`,
- data: trendLine(maData),
+ label: `${label} (Moving avg)`,
+ data: trendLine(maSeries.data),
color: hexToRGBA(baseColor, TRENDLINE_DIM_OPACITY),
yAxisId: main.yAxisId,
stroke: { pattern: [1, 3] },
@@ -136,7 +139,7 @@ function buildDerivedTrendsSeries<R extends TrendsResultLike, M = unknown>(
if (opts.showTrendLines && !excluded) {
out.push({
key: `${r.id}__trendline`,
- label: r.label ?? '',
+ label,
data: trendLine(r.data, dashedFromIndex),
color: hexToRGBA(baseColor, TRENDLINE_DIM_OPACITY),
yAxisId: main.yAxisId,