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): render and style goal lines correctly in hog-charts (#61054)

Sam Pennington9a5d52627fe1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 166942f1c2e2..3c79467f9e06 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -505,7 +505,7 @@ snapshots:
components-hogcharts-barchart--with-bar-track--light:
hash: v1.k794b7964.38ac4a98dead12b49e1727bdd93240f6ea0066adff611a97c6c5e3e307fc8e62.Fg389h17t2lWX9lR9CffIAX1jEZRri29prNfW7egOCE
components-hogcharts-barchart--with-reference-line--dark:
- hash: v1.k794b7964.b0c3c06250da7f04cb51a3044d2f6f54c9d6508e7aed6473bfd3f86991c9c358.pJc_WoUpP1J_PwVo6h-h_cXVue1gUJnph4-m95Xsd0I
+ hash: v1.k794b7964.1f241d2818a3ac969e14d29dd555240c5fb732a4fb0871f4d55f2d6a6a1955ab.XpPYc4tDjAAsNMMtoNsCiwJkA_luAGbIdYSjniuzEkM
components-hogcharts-barchart--with-reference-line--light:
hash: v1.k794b7964.081e6b6e0d8258756a42817806f81c4c2c934e5086728e4e57731d618cb0f5bb.LLR8JlGiNzCaW5F55LVIYQ9V5biMi1zPB6HpZ_tpmMk
components-hogcharts-barchart--with-value-labels--dark:
@@ -565,9 +565,9 @@ snapshots:
components-hogcharts-legend--vertical--light:
hash: v1.k794b7964.613d93ab14bd635185a8f3f5eabfaa884a3a8f7b418cdbdec94478b2bc3da2d2.poxwlxr4MP5HbhAC8JKzXCBFxGSJwc8uUXs26xUUcHU
components-hogcharts-linechart--combined-overlays--dark:
- hash: v1.k794b7964.38753d5c6bab2f9d1be492d0e191aca21265953e220c0f37714913c89d7caf42.0wzgqeeUqe_bxIfIbS861HknzpuGVzxC664U1GTe9S8
+ hash: v1.k794b7964.85034054b82c3649e42b84507f89c82af7df4341f89438376650298c79c8c484.ggHaFhXUXXHe0MKHvW6MT4xkpDndBHdkkn3Uy20U33o
components-hogcharts-linechart--combined-overlays--light:
- hash: v1.k794b7964.e0f8427b5643650cef898f599325c76f180066243ced0dacfbb84c35bda4af72.jZ1cNH9TnZJ4cppF70W6GKrg6XSnDDcybE7-pGlQZLA
+ hash: v1.k794b7964.cf6c7c5dd1d82006ae2a61a85d1af550a61d67dc85983694666f7ae3489e44f5._2K1C-9C_CUAmaCrLAnq8ZKK_QUumt5EJvD6yK4_18w
components-hogcharts-linechart--dual-y-axis--dark:
hash: v1.k794b7964.3cefe10d6ff3149785df1215afa32f2967fcdc0563173576d822fb2f4084b285.hnLnBqiMMU41pY8MFOTLprY0onNZvjvZ_nWM_6SkTV0
components-hogcharts-linechart--dual-y-axis--light:
@@ -661,25 +661,25 @@ snapshots:
components-hogcharts-piechart--with-breakdown-labels--light:
hash: v1.k794b7964.811f8e01cbeeb97d8319a76668d33864b6be08a2b8f270e5980fe951fafbc1bb.UoRHUDWOOnMGSCQcBN8D5TwfE6LL3IG58n0wUC_WOwo
components-hogcharts-referenceline--fill-sides--dark:
- hash: v1.k794b7964.88be514f5436eb4c62b3db30e81e6d2f2c2b71cc6cf19bca459ed13dc901258a.mhwEtPTUGmbBcNrc9l0arcCL92Fzc-tT6uIfVDkGgpg
+ hash: v1.k794b7964.c6b9d78f0423edc9a0baccf3dd9e05139aecb9387e8e3e5c32bcaec28663f279.zDKfyNa2u4-LWW40uD0XPkXVGUCnAZkfvJZI2TS0adA
components-hogcharts-referenceline--fill-sides--light:
- hash: v1.k794b7964.b3617f2aab1780e365660016c85f0daae62ff5851bfccd95fb3bbeb1e06448b6.4oB3BXkj0sJOkSW3h2lDmFy5zESjdgw2oi3Y67Ve0lA
+ hash: v1.k794b7964.670eaf8cf4ceecad58d9847836dcb80d7ad5c78197cb3c554453b0517b7248f1.4IWpGOyWBBAKyp0d5DaPblW4H_2kEGsKNtK4pyG9VtA
components-hogcharts-referenceline--horizontal-goal--dark:
- hash: v1.k794b7964.7789a578910fe26eee2a7770aca42913dc2156d4aa9d34bdb5cb6dda010a9670.cznULrSwCYSK5SHqc2emeWuQDRodAQQl1hroQ1py0is
+ hash: v1.k794b7964.bd601ac8479ca60a3b1a5ddeca7415c9851940a088c2671df6e46afe4e5a5bf6.CzvyS5WWn5MmnUJByi9QpLWqgJQ5_TMY-SQt5PzFsBo
components-hogcharts-referenceline--horizontal-goal--light:
- hash: v1.k794b7964.8d1e3040a3a29b030dea574024e56f8da1dec929a365ecb18f6e509a393d1fb1.1WY_3XTNVp3TVTx-phbZq0v16fSzxXppPiy1b86lnvM
+ hash: v1.k794b7964.e754e0914599e53edaa70b29b850bc96a87789d053c053759bac338afb082da8.foHtu1d4fJvvLBKASef_twIXnVo_-Lz5gb9EUjkcIUk
components-hogcharts-referenceline--horizontal-variants--dark:
- hash: v1.k794b7964.a009ed64c01f2d4b3ecaefe13dc7df0de5a9a374e6b6bebb04a1614787985f2d.RlMiRInKSZuGSB-Txdl5qTEsZD7G_RdD1t-30Lofljg
+ hash: v1.k794b7964.322b8a5a6690ff06abcd9fb7bdc2cda6d17339ebf52ae983991feb35e205b281.w0WsvX_fxKNz69xL6b4dmXzHE1HizDtbQaUHivYmVIQ
components-hogcharts-referenceline--horizontal-variants--light:
- hash: v1.k794b7964.1ee7b0eb338bb930c2ae9467d9802e358f3664c6369f9c50e154759dd534a86c.ImOHfi0EunpIPJgtCE5zMPsZ7lGn14kZiYXPr69mB0Y
+ hash: v1.k794b7964.26a99a0a645f53188423b4f8baebc3fbc9859a0750c906dec8444224bf9659ba.ijrrhJAbnHW0d-1LrbE_V2LWPRH3joRZO3v6SCYk1UI
components-hogcharts-referenceline--label-start-vs-end--dark:
hash: v1.k794b7964.fabcef88294104f29274ec587131942c155bf5ad07f7ccc44d5be4e043644c7c.8DxGcCR5SDI7WRkye1lRYYdqnoJyvsx29MIacSUYuUA
components-hogcharts-referenceline--label-start-vs-end--light:
- hash: v1.k794b7964.90ff54e19bd1817ec0da4fdfea22c05b57e59d709ec1fc82fbedbb6dcb2880b2.RWS_aFWJpBqvcPhSYo6K8qCEiO9fS7TD6hkAOpgOr0I
+ hash: v1.k794b7964.01a5b66f446ee36aa45a34e9bcda11dc3a54b54f6f362516966893eedc2c3d28.-w1ofSvDPDJWRfZ61t22NmPqoUvryXhNB2M1ccWZkzk
components-hogcharts-referenceline--vertical-reference-lines--dark:
- hash: v1.k794b7964.bf6bedb1f09bacdd7008902e47f2118b353f59b59d2dfbf7abecb7ad8fa09bd1.-uNfx0wyQ72E6nc1PrqC8rHg8J7gY8-7i9nop7w4Y2M
+ hash: v1.k794b7964.0bbe67f3d4f76183952e66b1e693dfc4784ed0caf8649a8f57bb4a15cf5e80e6.RH3hRdwnNpHGXdce_YxCruBjdIsvuQKdX4GNH5gxckg
components-hogcharts-referenceline--vertical-reference-lines--light:
- hash: v1.k794b7964.fde30e22b2056f1e8e22850bb06c5220d2953cfc94fbfd66bfb7f7b8eeb7323f.mR0MdlvDVJmrXWFmM9o48B66Ikx9Qavg8VWdW4bYy6s
+ hash: v1.k794b7964.5dcb0a0659868117ed589cf16c5b9e5d5e09a43d6971dcc9d5b1ad5e890ab5c3.BxyNtR_8BsK51YOYJQ_K4M3iAGGQxztcJtNGS1JbS9Q
components-hogcharts-sparkline--custom-color--dark:
hash: v1.k794b7964.9a599ca7e855408c1bda17c3b9094b60c333249c9df7d14d0be865a4f9fb424d.EFS4alrXA5COnCpJYXUfVxFvJd4GWClskV2utoqKWtE
components-hogcharts-sparkline--custom-color--light:
@@ -717,9 +717,9 @@ snapshots:
components-hogcharts-timeseriesbarchart--percent--light:
hash: v1.k794b7964.97eeda327c290f6a218c0c5a612b6180cdcf59738c4fcc6a2dd60343050b216d.5KrJNULtEF9jDv7lrNBQDHGXvT8Ic60zJ4ASkoFn3_g
components-hogcharts-timeseriesbarchart--with-goal-line--dark:
- hash: v1.k794b7964.a8afb665d437ac38f634e5a06a5489c8391d46d16a1b352920a9b11459c395e5.AZQRLWxOoK_bteNjvt4Ptt0h5Cz83fFRq06n-r-JDmw
+ hash: v1.k794b7964.7f3d17f5524960cd19f8397e98141cc368169d1c8cb33b100c49e610492226ad.mXs86Sw8Ay8lDkSwWpehLEZH2_AGc0Z-oFggDLCz6FI
components-hogcharts-timeseriesbarchart--with-goal-line--light:
- hash: v1.k794b7964.ddfc22ac1f0f33c808eb42283eadc30095e24e90c09e68f45a330268e31613db.v_goCVyEY1X4rmmEbJ5tCKfs5bufHel67bL3vwabk-Y
+ hash: v1.k794b7964.f858d12e2596161320b92a2030844a8c37c759beaf09d9dda1df5f2f9a1f287d.qQlKj0EqAs77chw4L8OTfGoDOvrajs1a1IDG9LPcmJU
components-hogcharts-timeseriesbarchart--with-value-labels--dark:
hash: v1.k794b7964.1d0b0f2ecd15593f82e3d673117538810b965e02d7460d974efc339f961e1c21.OfNaizOyso4D6O4EQJHfGCHYWVzZI-0fv8ksX6UtgH0
components-hogcharts-timeseriesbarchart--with-value-labels--light:
diff --git a/frontend/src/lib/hog-charts/charts/LineChart/LineChart.tsx b/frontend/src/lib/hog-charts/charts/LineChart/LineChart.tsx
index 6d1145deba18..d57d978d1038 100644
--- a/frontend/src/lib/hog-charts/charts/LineChart/LineChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/LineChart/LineChart.tsx
@@ -68,7 +68,7 @@ function LineChartInner<Meta = unknown>({
dataAttr,
children,
}: LineChartProps<Meta>): React.ReactElement {
- const { yScaleType = 'linear', percentStackView = false, showGrid = false } = config ?? {}
+ const { yScaleType = 'linear', percentStackView = false, showGrid = false, valueDomain } = config ?? {}
const hasMultipleFilledSeries = useMemo(() => {
const filledSeries = series.filter((s) => s.fill && !s.fill.lowerData)
@@ -113,6 +113,7 @@ function LineChartInner<Meta = unknown>({
const d3Scales = createLineScales(seriesForScale, scaleLabels, dimensions, {
scaleType: yScaleType,
percentStack: percentStackView,
+ valueDomain,
})
const yTickCount = yTickCountForHeight(dimensions.plotHeight)
@@ -143,7 +144,7 @@ function LineChartInner<Meta = unknown>({
_private: lineChartPrivate,
}
},
- [yScaleType, percentStackView, stackedData]
+ [yScaleType, percentStackView, stackedData, valueDomain]
)
const drawStatic = useCallback(
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
index 359cc1f2d8a0..600c92207600 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
@@ -220,6 +220,18 @@ describe('TimeSeriesBarChart', () => {
expect(lines[0].orientation).toBe('horizontal')
expect(lines[0].label).toBe('Target')
})
+
+ it('extends the value axis so a goal line above the data still renders', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={[{ key: 'a', label: 'A', data: [10, 20, 30] }]}
+ labels={LABELS}
+ theme={THEME}
+ config={{ goalLines: [{ value: 1000, label: 'Target' }] }}
+ />
+ )
+ expect(chart.referenceLines()).toHaveLength(1)
+ })
})
describe('config.barLayout', () => {
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index aeb19677e3e4..6b6ab55240f3 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -10,7 +10,7 @@ import type {
} from '../../core/types'
import { ReferenceLines } from '../../overlays/ReferenceLine'
import { ValueLabels } from '../../overlays/ValueLabels'
-import { buildGoalLineReferenceLines, type GoalLineConfig } from '../../utils/goal-lines'
+import { buildGoalLineReferenceLines, goalLineValueDomain, type GoalLineConfig } from '../../utils/goal-lines'
import {
useXTickFormatter,
useYTickFormatter,
@@ -101,6 +101,11 @@ export function TimeSeriesBarChart<Meta = unknown>({
[referenceLines, axisOrientation]
)
+ // Extend the value axis to cover goal lines that sit above (or below) the data, so a goal
+ // line off the data's natural scale still renders inside the plot. Memoized so the `{ include }`
+ // object stays referentially stable and doesn't re-trigger scale recomputation each render.
+ const valueDomain = useMemo(() => goalLineValueDomain(referenceLines), [referenceLines])
+
const barChartConfig: BarChartConfig = {
yScaleType: yAxis?.scale,
xTickFormatter,
@@ -114,7 +119,11 @@ export function TimeSeriesBarChart<Meta = unknown>({
axisOrientation,
showCrosshair,
tooltip: tooltipConfig,
- bars: { cornerRadius: barCornerRadius, divergingStack },
+ bars: {
+ cornerRadius: barCornerRadius,
+ divergingStack,
+ valueDomain,
+ },
}
return (
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 b1fa6f5bc590..0d097609c05b 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
@@ -237,6 +237,18 @@ describe('TimeSeriesLineChart', () => {
expect(lines[0].orientation).toBe('horizontal')
expect(lines[0].label).toBe('Target')
})
+
+ it('extends the value axis so a goal line above the data still renders', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesLineChart
+ series={[{ key: 'a', label: 'A', data: [10, 20, 30] }]}
+ labels={LABELS}
+ theme={THEME}
+ config={{ goalLines: [{ value: 1000, label: 'Target' }] }}
+ />
+ )
+ expect(chart.referenceLines()).toHaveLength(1)
+ })
})
describe('derived-series wiring', () => {
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index ae7ca17f396c..76320ea9c869 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -10,7 +10,7 @@ import type {
} from '../../core/types'
import { ReferenceLines } from '../../overlays/ReferenceLine'
import { ValueLabels } from '../../overlays/ValueLabels'
-import { buildGoalLineReferenceLines, type GoalLineConfig } from '../../utils/goal-lines'
+import { buildGoalLineReferenceLines, goalLineValueDomain, type GoalLineConfig } from '../../utils/goal-lines'
import {
useXTickFormatter,
useYTickFormatter,
@@ -105,6 +105,11 @@ export function TimeSeriesLineChart<Meta = unknown>({
const referenceLines = useMemo(() => buildGoalLineReferenceLines(goalLines, finalSeries), [goalLines, finalSeries])
+ // Extend the value axis to cover goal lines that sit outside the data range, so a goal line
+ // off the data's natural scale still renders inside the plot. Memoized so the `{ include }`
+ // object stays referentially stable and doesn't re-trigger scale recomputation each render.
+ const valueDomain = useMemo(() => goalLineValueDomain(referenceLines), [referenceLines])
+
const lineChartConfig: LineChartConfig = {
yScaleType: yAxis?.scale,
xTickFormatter,
@@ -117,6 +122,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
percentStackView,
showCrosshair,
tooltip: tooltipConfig,
+ valueDomain,
}
return (
diff --git a/frontend/src/lib/hog-charts/core/bar-scales.test.ts b/frontend/src/lib/hog-charts/core/bar-scales.test.ts
index aebf22264386..ab08afcc0313 100644
--- a/frontend/src/lib/hog-charts/core/bar-scales.test.ts
+++ b/frontend/src/lib/hog-charts/core/bar-scales.test.ts
@@ -128,6 +128,70 @@ describe('hog-charts bar scales', () => {
})
})
+ describe('createBarScales — valueDomain { include } (goal lines)', () => {
+ it('extends the value domain upward to include a goal line above the data', () => {
+ const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]
+ const { value } = createBarScales(series, ['a', 'b', 'c'], dimensions, { valueDomain: { include: [100] } })
+ expect(value.domain()[1]).toBeGreaterThanOrEqual(100)
+ const yAtGoal = value(100)
+ expect(yAtGoal).toBeGreaterThanOrEqual(dimensions.plotTop - 1)
+ expect(yAtGoal).toBeLessThanOrEqual(dimensions.plotTop + dimensions.plotHeight + 1)
+ })
+
+ it('extends the value domain downward to include a negative goal line', () => {
+ const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]
+ const { value } = createBarScales(series, ['a', 'b', 'c'], dimensions, { valueDomain: { include: [-50] } })
+ expect(value.domain()[0]).toBeLessThanOrEqual(-50)
+ })
+
+ it('leaves the data-derived domain unchanged when the goal line is within range', () => {
+ const series = [makeSeries({ key: 's1', data: [0, 50, 100] })]
+ const withGoal = createBarScales(series, ['a', 'b', 'c'], dimensions, { valueDomain: { include: [50] } })
+ const withoutGoal = createBarScales(series, ['a', 'b', 'c'], dimensions)
+ expect(withGoal.value.domain()).toEqual(withoutGoal.value.domain())
+ })
+
+ it('extends the log-scale domain to include a goal line above the data', () => {
+ const series = [makeSeries({ key: 's1', data: [3, 50, 700] })]
+ const { value } = createBarScales(series, ['a', 'b', 'c'], dimensions, {
+ scaleType: 'log',
+ valueDomain: { include: [9000] },
+ })
+ expect(value.domain()[1]).toBeGreaterThanOrEqual(9000)
+ })
+
+ it('is ignored under percent layout (domain stays [0, 1])', () => {
+ const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]
+ const { value } = createBarScales(series, ['a', 'b', 'c'], dimensions, {
+ barLayout: 'percent',
+ valueDomain: { include: [500] },
+ })
+ expect(value.domain()[0]).toBeCloseTo(0)
+ expect(value.domain()[1]).toBeCloseTo(1)
+ })
+
+ it.each([[100], [0], [-5]])('stays well-formed and zero-anchored with no data and only goal %s', (goal) => {
+ const { value } = createBarScales([], ['a', 'b'], dimensions, { valueDomain: { include: [goal] } })
+ const [lo, hi] = value.domain()
+ expect(lo).toBeLessThan(hi)
+ // The bar value axis always keeps a zero baseline, so the domain spans across 0.
+ expect(lo).toBeLessThanOrEqual(0)
+ expect(hi).toBeGreaterThanOrEqual(0)
+ expect(isFinite(value(goal))).toBe(true)
+ })
+ })
+
+ describe('createBarScales — valueDomain [min, max] (fixed)', () => {
+ it.each([
+ ['pins the domain regardless of data and skips nice()', undefined, [0, 40] as [number, number]],
+ ['takes precedence over percent layout', 'percent' as const, [0, 200] as [number, number]],
+ ])('%s', (_name, barLayout, valueDomain) => {
+ const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]
+ const { value } = createBarScales(series, ['a', 'b', 'c'], dimensions, { barLayout, valueDomain })
+ expect(value.domain()).toEqual(valueDomain)
+ })
+ })
+
describe('createBarScales — log scale', () => {
it('snaps the domain to enclosing decade boundaries with positive data', () => {
const series = [makeSeries({ key: 's1', data: [3, 50, 700] })]
diff --git a/frontend/src/lib/hog-charts/core/scales.test.ts b/frontend/src/lib/hog-charts/core/scales.test.ts
index c6229a097a47..6c7344aed860 100644
--- a/frontend/src/lib/hog-charts/core/scales.test.ts
+++ b/frontend/src/lib/hog-charts/core/scales.test.ts
@@ -150,6 +150,74 @@ describe('hog-charts scales', () => {
})
})
+ describe('createYScale — valueDomain { include } (goal lines)', () => {
+ it('extends the domain upward to include a goal line above the data', () => {
+ const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]
+ const scale = createYScale(series, dimensions, { valueDomain: { include: [100] } })
+ expect(scale.domain()[1]).toBeGreaterThanOrEqual(100)
+ expect(scale.domain()[0]).toBe(0)
+ })
+
+ it('extends the domain downward to include a negative goal line on positive data', () => {
+ const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]
+ const scale = createYScale(series, dimensions, { valueDomain: { include: [-50] } })
+ expect(scale.domain()[0]).toBeLessThanOrEqual(-50)
+ })
+
+ it('still clips an overlay-driven negative baseline to 0 when include values are non-negative', () => {
+ const main = makeSeries({ key: 'main', data: [0, 5000, 14500] })
+ const trendline = makeSeries({ key: 'trend', data: [-1000, 7000, 10000], overlay: true })
+ const scale = createYScale([main, trendline], dimensions, { valueDomain: { include: [20000] } })
+ expect(scale.domain()[0]).toBe(0)
+ expect(scale.domain()[1]).toBeGreaterThanOrEqual(20000)
+ })
+
+ it('leaves the data-derived domain unchanged when the goal line is within range', () => {
+ const series = [makeSeries({ key: 's1', data: [0, 50, 100] })]
+ const withGoal = createYScale(series, dimensions, { valueDomain: { include: [50] } })
+ const withoutGoal = createYScale(series, dimensions)
+ expect(withGoal.domain()).toEqual(withoutGoal.domain())
+ })
+
+ it('extends the log-scale domain to include a goal line above the data', () => {
+ const series = [makeSeries({ key: 's1', data: [3, 50, 700] })]
+ const scale = createYScale(series, dimensions, { scaleType: 'log', valueDomain: { include: [9000] } })
+ expect(scale.domain()[1]).toBeGreaterThanOrEqual(9000)
+ })
+
+ it('is ignored under percent stack mode', () => {
+ const series = [makeSeries({ key: 's1', data: [50, 100] })]
+ const scale = createYScale(series, dimensions, { percentStack: true, valueDomain: { include: [500] } })
+ expect(scale.domain()[0]).toBe(0)
+ expect(scale.domain()[1]).toBeGreaterThanOrEqual(1)
+ expect(scale.domain()[1]).toBeLessThan(2)
+ })
+
+ it.each([
+ ['a positive goal anchors to zero', [100], 100],
+ ['a zero goal still yields a unit span', [0], 0],
+ ])('stays well-formed with no data and only %s', (_name, include, goal) => {
+ const scale = createYScale([], dimensions, { valueDomain: { include } })
+ const [lo, hi] = scale.domain()
+ expect(lo).toBeLessThan(hi)
+ expect(isFinite(scale(goal))).toBe(true)
+ })
+ })
+
+ describe('createYScale — valueDomain [min, max] (fixed)', () => {
+ it('pins the domain regardless of data and skips nice()', () => {
+ const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]
+ const scale = createYScale(series, dimensions, { valueDomain: [0, 40] })
+ expect(scale.domain()).toEqual([0, 40])
+ })
+
+ it('takes precedence over percent stack mode', () => {
+ const series = [makeSeries({ key: 's1', data: [10, 20, 30] })]
+ const scale = createYScale(series, dimensions, { percentStack: true, valueDomain: [0, 200] })
+ expect(scale.domain()).toEqual([0, 200])
+ })
+ })
+
describe('createYScale — log mode', () => {
it('returns a log scale', () => {
const series = [makeSeries({ key: 's1', data: [1, 10, 100] })]
@@ -290,6 +358,15 @@ describe('hog-charts scales', () => {
// nice() can extend the domain slightly but nowhere near 9999.
expect(leftMax).toBeLessThan(100)
})
+
+ it('extends only the primary axis for goal lines, leaving secondary axes untouched', () => {
+ const left = makeSeries({ key: 'left', data: [0, 10], yAxisId: DEFAULT_Y_AXIS_ID })
+ const right = makeSeries({ key: 'right', data: [0, 500], yAxisId: 'y1' })
+ const result = createScales([left, right], ['a', 'b'], dimensions, { valueDomain: { include: [1000] } })
+ expect(result.yAxes![DEFAULT_Y_AXIS_ID].scale.domain()[1]).toBeGreaterThanOrEqual(1000)
+ // The right axis is unaffected — nice() can nudge 500 up a little, but nowhere near 1000.
+ expect(result.yAxes!.y1.scale.domain()[1]).toBeLessThan(1000)
+ })
})
describe('computePercentStackData', () => {
diff --git a/frontend/src/lib/hog-charts/core/scales.ts b/frontend/src/lib/hog-charts/core/scales.ts
index 1e3fae4dea6c..84e246b56fb8 100644
--- a/frontend/src/lib/hog-charts/core/scales.ts
+++ b/frontend/src/lib/hog-charts/core/scales.ts
@@ -1,6 +1,6 @@
import * as d3 from 'd3'
-import type { ChartDimensions, ChartScales, ResolveValueFn, Series } from './types'
+import type { ChartDimensions, ChartScales, ResolveValueFn, Series, ValueDomain } from './types'
import { DEFAULT_Y_AXIS_ID } from './types'
/** Inner padding fraction applied to the band scale when `BarChartConfig.bars.bandPadding` is unset. */
@@ -60,6 +60,43 @@ export function seriesValueRange(series: Series[]): SeriesValueRange {
return { min, max, minPositive, count }
}
+/** Split a {@link ValueDomain} into its two mutually-exclusive modes — a fixed `[min, max]`
+ * or the set of values an auto-scaled domain must `include`. */
+function resolveValueDomain(valueDomain: ValueDomain | undefined): {
+ fixed?: readonly [number, number]
+ include?: readonly number[]
+} {
+ if (!valueDomain) {
+ return {}
+ }
+ if ('include' in valueDomain) {
+ return { include: valueDomain.include }
+ }
+ return { fixed: valueDomain }
+}
+
+/** Fold extra values (e.g. goal-line targets) into a range so the axis covers them even when
+ * they sit outside the data's natural extent. */
+export function extendValueRange(range: SeriesValueRange, values: readonly number[]): SeriesValueRange {
+ let { min, max, minPositive, count } = range
+ for (const v of values) {
+ if (v == null || !isFinite(v)) {
+ continue
+ }
+ count++
+ if (v < min) {
+ min = v
+ }
+ if (v > max) {
+ max = v
+ }
+ if (v > 0 && v < minPositive) {
+ minPositive = v
+ }
+ }
+ return { min, max, minPositive, count }
+}
+
/** Round `minPositive` down to the previous decade, `max` up to the next round multiple
* of its top decade (e.g. 740 → 800, 4200 → 5000). */
export function niceLogDomain(minPositive: number, max: number): [number, number] {
@@ -87,11 +124,21 @@ export function createYScale(
options: {
scaleType?: 'linear' | 'log'
percentStack?: boolean
+ /** Fixed `[min, max]` or `{ include }` extra values the domain must cover. */
+ valueDomain?: ValueDomain
} = {}
): d3.ScaleLinear<number, number> | d3.ScaleLogarithmic<number, number> {
- const { scaleType = 'linear', percentStack = false } = options
+ const { scaleType = 'linear', percentStack = false, valueDomain } = options
+ const { fixed, include } = resolveValueDomain(valueDomain)
const tickCount = yTickCountForHeight(dimensions.plotHeight)
+ if (fixed) {
+ return d3
+ .scaleLinear()
+ .domain([fixed[0], fixed[1]])
+ .range([dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop])
+ }
+
if (percentStack) {
return d3
.scaleLinear()
@@ -100,7 +147,8 @@ export function createYScale(
.range([dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop])
}
- const range = seriesValueRange(series)
+ const dataRange = seriesValueRange(series)
+ const range = include?.length ? extendValueRange(dataRange, include) : dataRange
if (range.count === 0) {
return d3
@@ -129,14 +177,24 @@ export function createYScale(
// Auxiliary overlays (trendline projections, moving averages) may dip below 0
// when the underlying data does not. They shouldn't drag the axis baseline below
// 0 — d3.nice() applied to a slightly-negative min produces a disproportionately
- // large negative tick (e.g. [-1, 14500] → [-2000, 16000]).
- const primaryRange = series.some((s) => s.overlay) ? seriesValueRange(series.filter((s) => !s.overlay)) : range
- if (primaryRange.count > 0 && primaryRange.min >= 0) {
+ // large negative tick (e.g. [-1, 14500] → [-2000, 16000]). A negative `include`
+ // value (a goal line below 0) is explicit, though, so it must not be clamped away.
+ const hasExplicitNegativeGoal = include?.some((v) => v != null && isFinite(v) && v < 0) ?? false
+ const primaryRange = series.some((s) => s.overlay) ? seriesValueRange(series.filter((s) => !s.overlay)) : dataRange
+ if (primaryRange.count > 0 && primaryRange.min >= 0 && !hasExplicitNegativeGoal) {
min = 0
} else if (max < 0) {
max = 0
}
+ // With no real data, `include` (goal) values are the only contributors, so the range can
+ // collapse to a single point (e.g. `[100, 100]`) — a degenerate domain that maps everything to
+ // NaN. Bracket zero, then guarantee a unit span, so the axis stays well-formed.
+ if (min === max) {
+ min = Math.min(0, min)
+ max = Math.max(0, max, min + 1)
+ }
+
return d3
.scaleLinear()
.domain([min, max])
@@ -151,6 +209,9 @@ export function createScales(
options: {
scaleType?: 'linear' | 'log'
percentStack?: boolean
+ /** Applied to the primary y-axis only — goal lines (`{ include }`) render against the
+ * primary axis, so secondary axes keep their own data-derived scale. */
+ valueDomain?: ValueDomain
} = {}
): ScaleSet {
const x = createXScale(labels, dimensions)
@@ -162,6 +223,7 @@ export function createScales(
const y = createYScale(series, dimensions, {
scaleType: options.scaleType,
percentStack: options.percentStack,
+ valueDomain: options.valueDomain,
})
return { x, y }
}
@@ -179,6 +241,7 @@ export function createScales(
const scale = createYScale(axisSeries, dimensions, {
scaleType: options.scaleType,
percentStack: options.percentStack,
+ valueDomain: axisIndex === 0 ? options.valueDomain : undefined,
})
yAxes[axisId] = { scale, position: axisIndex === 0 ? 'left' : 'right' }
})
@@ -324,8 +387,8 @@ export function createBarScales(
stackedSeries?: Series[]
/** Cap on the band-axis range in px — clusters bars at the start of the plot when set. */
maxBandRange?: number
- /** Fixed value-axis domain — bypasses data-derived range + `nice()`. */
- valueDomain?: [number, number]
+ /** Fixed `[min, max]` or `{ include }` extra values the value axis must cover. */
+ valueDomain?: ValueDomain
} = {}
): BarScaleSet {
const {
@@ -376,23 +439,30 @@ function buildBarValueScale(
barLayout: 'stacked' | 'grouped' | 'percent',
scaleType: 'linear' | 'log',
stackedSeries: Series[] | undefined,
- valueDomain: [number, number] | undefined
+ valueDomain: ValueDomain | undefined
): D3YScale {
- if (valueDomain) {
- return d3.scaleLinear().domain(valueDomain).range(valueRange)
+ const { fixed, include } = resolveValueDomain(valueDomain)
+ if (fixed) {
+ return d3.scaleLinear().domain([fixed[0], fixed[1]]).range(valueRange)
}
if (barLayout === 'percent') {
return d3.scaleLinear().domain([0, 1]).nice(tickCount).range(valueRange)
}
- const range = seriesValueRange(stackedSeries ?? series)
+ const range = include?.length
+ ? extendValueRange(seriesValueRange(stackedSeries ?? series), include)
+ : seriesValueRange(stackedSeries ?? series)
if (range.count === 0) {
return d3.scaleLinear().domain([0, 1]).range(valueRange)
}
const min = range.min > 0 ? 0 : range.min
- const max = range.max < 0 ? 0 : range.max
+ let max = range.max < 0 ? 0 : range.max
if (scaleType === 'log' && isFinite(range.minPositive)) {
return d3.scaleLog().domain(niceLogDomain(range.minPositive, max)).range(valueRange).clamp(true)
}
+ // Guard the degenerate single-point domain (e.g. empty data with a single goal value at 0).
+ if (min === max) {
+ max = min + 1
+ }
return d3.scaleLinear().domain([min, max]).nice(tickCount).range(valueRange)
}
diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.ts
index 0c6b9d0de0d8..1cba07af931a 100644
--- a/frontend/src/lib/hog-charts/core/types.ts
+++ b/frontend/src/lib/hog-charts/core/types.ts
@@ -206,6 +206,19 @@ export interface TooltipConfig {
placement?: 'follow-data' | 'top' | 'cursor'
}
+/** How the value axis domain is determined (y for vertical/line/area charts, x for horizontal
+ * bars). The two modes are mutually exclusive by construction — pick one. Omit the option
+ * entirely for the default: a data-derived range with `d3.nice()`. */
+export type ValueDomain =
+ /** Pin both ends — skips the data-derived range and `d3.nice()` so independent charts that
+ * share this domain stay visually comparable (e.g. funnel steps). Takes precedence over
+ * `barLayout: 'percent'` / `percentStackView`. */
+ | readonly [number, number]
+ /** Keep data-derived auto-scaling, but stretch the domain to always cover these values
+ * (e.g. goal-line targets that sit outside the data). Folded into the range before
+ * `d3.nice()`. */
+ | { include: readonly number[] }
+
/** Bar appearance + band-layout details. Grouped under {@link BarChartConfig.bars} to keep the
* config flat at the top level. `barLayout` stays top-level as the primary discriminator. */
export interface BarsConfig {
@@ -232,9 +245,8 @@ export interface BarsConfig {
* an unreadable strip, the chart expands its container height so each row has at least this
* much vertical space (label height + breathing room). Defaults to `24`. Pass `0` to opt out. */
minBandSize?: number
- /** Fix the value-axis domain (no data-derived range, no `d3.nice()`) so independent charts
- * sharing a logical scale stay comparable. Takes precedence over `barLayout: 'percent'`. */
- valueDomain?: [number, number]
+ /** Value-axis domain control — omit for data-derived auto-scaling. See {@link ValueDomain}. */
+ valueDomain?: ValueDomain
/** Stacked layouts only — round both *outer* ends of the whole stack so it reads as one pill,
* rather than only the topmost segment's cap. Implemented by clipping the bar layer to a
* rounded rect spanning each band's full extent and drawing the segments square, so the outer
@@ -253,6 +265,8 @@ export interface BarChartConfig extends ChartConfig {
export interface LineChartConfig extends ChartConfig {
percentStackView?: boolean
+ /** Value-axis domain control — omit for data-derived auto-scaling. See {@link ValueDomain}. */
+ valueDomain?: ValueDomain
}
/** Arguments passed to a chart type's canvas draw function. */
diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.ts
index 6e944b296aef..18848fb91b60 100644
--- a/frontend/src/lib/hog-charts/index.ts
+++ b/frontend/src/lib/hog-charts/index.ts
@@ -75,6 +75,7 @@ export type {
Series,
TooltipConfig,
TooltipContext,
+ ValueDomain,
YAxisScale,
} from './core/types'
export { DEFAULT_Y_AXIS_ID } from './core/types'
diff --git a/frontend/src/lib/hog-charts/overlays/ReferenceLine.test.tsx b/frontend/src/lib/hog-charts/overlays/ReferenceLine.test.tsx
index cf50f58c0d82..3e7aee65ef79 100644
--- a/frontend/src/lib/hog-charts/overlays/ReferenceLine.test.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ReferenceLine.test.tsx
@@ -80,6 +80,28 @@ describe('ReferenceLine', () => {
expect(label.style.left).toBe('')
})
+ it('centers the label on the line when there is room', () => {
+ const { getByText } = renderInChart(<ReferenceLine value={50} label="T" />)
+ const label = getByText('T') as HTMLDivElement
+ // y-scale(50) = 192, comfortably inside the plot, so the center sits on the line.
+ expect(label.style.top).toBe('192px')
+ expect(label.style.transform).toBe('translateY(-50%)')
+ })
+
+ it('clamps the label inside the plot when the line is at the top edge', () => {
+ const { getByText } = renderInChart(<ReferenceLine value={100} label="T" />)
+ const label = getByText('T') as HTMLDivElement
+ // y-scale(100) = 16 (plotTop); center clamped down to plotTop + LABEL_HEIGHT/2 = 26.
+ expect(label.style.top).toBe('26px')
+ })
+
+ it('clamps the label inside the plot when the line is at the bottom edge', () => {
+ const { getByText } = renderInChart(<ReferenceLine value={0} label="T" />)
+ const label = getByText('T') as HTMLDivElement
+ // y-scale(0) = 368 (plotBottom); center clamped up to plotBottom - LABEL_HEIGHT/2 = 358.
+ expect(label.style.top).toBe('358px')
+ })
+
it('renders a fill rect above the line when fillSide="above"', () => {
const { container } = renderInChart(<ReferenceLine value={50} fillSide="above" />)
const divs = container.querySelectorAll<HTMLDivElement>('div')
diff --git a/frontend/src/lib/hog-charts/overlays/ReferenceLine.tsx b/frontend/src/lib/hog-charts/overlays/ReferenceLine.tsx
index 38e7d51e758e..5d773623731f 100644
--- a/frontend/src/lib/hog-charts/overlays/ReferenceLine.tsx
+++ b/frontend/src/lib/hog-charts/overlays/ReferenceLine.tsx
@@ -59,8 +59,9 @@ const VARIANT_DEFAULTS: Record<ReferenceLineVariant, ResolvedStyle> = {
marker: { color: 'rgba(0, 0, 0, 0.5)', stroke: 'solid', width: 1 },
}
-/** Vertical distance from the line to the top edge of the text label. */
-const LABEL_OFFSET = 18
+/** Approximate rendered height of the label bubble — used only to keep it inside the plot near
+ * the top/bottom edges. Vertical centering itself is exact via a translateY(-50%) transform. */
+const LABEL_HEIGHT = 20
/** Padding between the label and the plot edge. */
const LABEL_PADDING = 4
@@ -155,12 +156,16 @@ function HorizontalReferenceLine({
borderTopStyle: resolved.stroke,
borderTopColor: resolved.color,
}
+ // Center the label bubble on the line (translateY(-50%) handles exact centering regardless of
+ // rendered height), but keep its center far enough from the plot edges that an extended-axis
+ // goal line sitting at the very top/bottom isn't clipped.
+ const labelCenterY = Math.max(plotTop + LABEL_HEIGHT / 2, Math.min(y, plotBottom - LABEL_HEIGHT / 2))
const labelStyle: React.CSSProperties = {
- top: y - LABEL_OFFSET,
+ top: labelCenterY,
+ transform: 'translateY(-50%)',
...(labelPosition === 'end'
? { right: containerWidth - plotRight + LABEL_PADDING }
: { left: plotLeft + LABEL_PADDING }),
- color: resolved.color,
}
let fillRect: React.CSSProperties | null = null
@@ -226,7 +231,6 @@ function VerticalStripe({
...(labelPosition === 'end'
? { bottom: containerHeight - plotBottom + LABEL_PADDING }
: { top: plotTop + LABEL_PADDING }),
- color: resolved.color,
}
let fillRect: React.CSSProperties | null = null
@@ -309,7 +313,7 @@ function ReferenceLineView({
{label && (
<div
data-attr="hog-chart-reference-line-label"
- className="absolute pointer-events-none whitespace-nowrap font-medium text-[11px]"
+ className="absolute pointer-events-none whitespace-nowrap font-medium text-[11px] rounded px-1 py-0.5 bg-[var(--tooltip-bg)] text-white"
style={labelStyle}
>
{label}
diff --git a/frontend/src/lib/hog-charts/utils/goal-lines.test.ts b/frontend/src/lib/hog-charts/utils/goal-lines.test.ts
index f12754ce278f..ca06cd2f0de7 100644
--- a/frontend/src/lib/hog-charts/utils/goal-lines.test.ts
+++ b/frontend/src/lib/hog-charts/utils/goal-lines.test.ts
@@ -43,7 +43,7 @@ describe('goal-lines', () => {
expect(buildGoalLineReferenceLines(input, series)).toEqual([])
})
- it('maps each goal to a horizontal "goal" ReferenceLine, defaulting label position to start', () => {
+ it('maps each goal to a horizontal "goal" ReferenceLine, defaulting label position to end', () => {
const result = buildGoalLineReferenceLines([{ label: 'Target', value: 50 }], series)
expect(result).toHaveLength(1)
expect(result[0]).toMatchObject({
@@ -51,14 +51,14 @@ describe('goal-lines', () => {
orientation: 'horizontal',
variant: 'goal',
label: 'Target',
- labelPosition: 'start',
+ labelPosition: 'end',
})
})
it.each([
['propagates color via style.color', { color: 'var(--danger)' }, { style: { color: 'var(--danger)' } }],
['omits label when displayLabel is false', { displayLabel: false }, { label: undefined }],
- ['respects explicit labelPosition', { labelPosition: 'end' as const }, { labelPosition: 'end' }],
+ ['respects explicit labelPosition', { labelPosition: 'start' as const }, { labelPosition: 'start' }],
] as const)('%s', (_, lineOverrides, expectedProps) => {
const lines: GoalLineConfig[] = [{ label: 'X', value: 50, ...lineOverrides }]
expect(buildGoalLineReferenceLines(lines, series)[0]).toMatchObject(expectedProps)
diff --git a/frontend/src/lib/hog-charts/utils/goal-lines.ts b/frontend/src/lib/hog-charts/utils/goal-lines.ts
index 1df8dfb0f117..da6852d5ab1f 100644
--- a/frontend/src/lib/hog-charts/utils/goal-lines.ts
+++ b/frontend/src/lib/hog-charts/utils/goal-lines.ts
@@ -1,4 +1,4 @@
-import type { Series } from '../core/types'
+import type { Series, ValueDomain } from '../core/types'
import type { ReferenceLineProps } from '../overlays/ReferenceLine'
export interface GoalLineConfig {
@@ -43,8 +43,16 @@ export function buildGoalLineReferenceLines(
value: line.value,
orientation: 'horizontal',
label: line.displayLabel === false ? undefined : line.label,
- labelPosition: line.labelPosition ?? 'start',
+ // Match the UI control and legacy chart.js, which both default an unset position to 'end'.
+ labelPosition: line.labelPosition ?? 'end',
variant: 'goal',
style: line.color ? { color: line.color } : undefined,
}))
}
+
+/** Numeric values of a set of reference lines as a {@link ValueDomain}, so the chart's value axis
+ * stretches to keep off-scale goal lines on-plot. Returns `undefined` when there's nothing to add. */
+export function goalLineValueDomain(referenceLines: readonly ReferenceLineProps[]): ValueDomain | undefined {
+ const values = referenceLines.map((line) => line.value).filter((v): v is number => typeof v === 'number')
+ return values.length > 0 ? { include: values } : undefined
+}
diff --git a/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.test.ts b/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.test.ts
index 16f60bfe18ee..7a7e93aff4af 100644
--- a/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.test.ts
+++ b/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.test.ts
@@ -56,7 +56,7 @@ describe('goalLinesAdapter', () => {
orientation: 'horizontal',
variant: 'goal',
label: 'Target',
- labelPosition: 'start',
+ labelPosition: 'end',
})
})
@@ -67,7 +67,7 @@ describe('goalLinesAdapter', () => {
{ style: { color: 'var(--danger)' } },
],
['omits label when displayLabel is false', { displayLabel: false }, { label: undefined }],
- ['respects explicit labelPosition', { position: 'end' }, { labelPosition: 'end' }],
+ ['respects explicit labelPosition', { position: 'start' }, { labelPosition: 'start' }],
] as const)('%s', (_, goalOverrides, expectedProps) => {
const goals: SchemaGoalLine[] = [{ label: 'X', value: 50, ...goalOverrides }]
expect(goalLinesToReferenceLines(goals, series)[0]).toMatchObject(expectedProps)
@@ -111,7 +111,7 @@ describe('goalLinesAdapter', () => {
orientation: 'horizontal',
variant: 'alert',
label: 'Upper',
- labelPosition: 'start',
+ labelPosition: 'end',
})
expect(result[1]).toMatchObject({ value: 10, variant: 'alert' })
})
diff --git a/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.ts b/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.ts
index 492a6aefb865..116be2e7529a 100644
--- a/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.ts
+++ b/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.ts
@@ -26,7 +26,7 @@ function schemaToReferenceLine(line: SchemaGoalLine, variant: 'goal' | 'alert'):
value: line.value,
orientation: 'horizontal',
label: line.displayLabel === false ? undefined : line.label,
- labelPosition: line.position ?? 'start',
+ labelPosition: line.position ?? 'end',
variant,
style: line.borderColor ? { color: line.borderColor } : undefined,
}