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 custom axis labels (#59488)

willwearing69e4e6bfd29d
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
index cfaef78c7683..baaf4a7576b5 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.test.tsx
@@ -153,6 +153,23 @@ describe('BarChart', () => {
expect(chart.xTicks()).toEqual(['tick-0', 'tick-1', 'tick-2'])
})
+ it('renders custom axis titles in horizontal orientation', () => {
+ const { chart } = renderHogChart(
+ <BarChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{
+ axisOrientation: 'horizontal',
+ xAxisLabel: 'Total events',
+ yAxisLabel: 'Series',
+ }}
+ />
+ )
+ expect(chart.xAxisLabel()).toBe('Total events')
+ expect(chart.yAxisLabel()).toBe('Series')
+ })
+
it('renders without crashing in yScaleType log with positive data', () => {
const series: Series[] = [{ key: 'a', label: 'A', data: [1, 10, 100] }]
const { chart } = renderHogChart(
diff --git a/frontend/src/lib/hog-charts/charts/LineChart.test.tsx b/frontend/src/lib/hog-charts/charts/LineChart.test.tsx
index f3cee5d95ff1..e33ecc1e4e79 100644
--- a/frontend/src/lib/hog-charts/charts/LineChart.test.tsx
+++ b/frontend/src/lib/hog-charts/charts/LineChart.test.tsx
@@ -99,6 +99,79 @@ describe('LineChart', () => {
expect(chart.xTicks()).toEqual(['tick-0', 'tick-1', 'tick-2'])
})
+ it('renders custom axis titles', () => {
+ const { chart } = renderHogChart(
+ <LineChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ xAxisLabel: 'Signup date', yAxisLabel: 'Unique users' }}
+ />
+ )
+ expect(chart.xAxisLabel()).toBe('Signup date')
+ expect(chart.yAxisLabel()).toBe('Unique users')
+ })
+
+ it('includes custom axis titles in the canvas accessible label', () => {
+ const { getByRole } = renderHogChart(
+ <LineChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ xAxisLabel: 'Signup date', yAxisLabel: 'Unique users' }}
+ />
+ )
+ expect(getByRole('img').getAttribute('aria-label')).toBe(
+ 'Chart with 2 data series. X-axis: Signup date. Y-axis: Unique users'
+ )
+ })
+
+ it('ignores whitespace-only axis titles', () => {
+ const { chart, getByRole } = renderHogChart(
+ <LineChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ xAxisLabel: ' ', yAxisLabel: ' ' }}
+ />
+ )
+
+ expect(chart.xAxisLabel()).toBeNull()
+ expect(chart.yAxisLabel()).toBeNull()
+ expect(getByRole('img').getAttribute('aria-label')).toBe('Chart with 2 data series')
+ })
+
+ it('truncates long axis titles without losing the full label metadata', () => {
+ const xAxisLabel = 'Signup date for a very long customer lifecycle analysis '.repeat(30).trim()
+ const yAxisLabel = 'Unique users with a very long aggregation description '.repeat(30).trim()
+ const { chart } = renderHogChart(
+ <LineChart series={SERIES} labels={LABELS} theme={THEME} config={{ xAxisLabel, yAxisLabel }} />
+ )
+
+ const xTitle = chart.xAxisLabelElement()
+ const yTitle = chart.yAxisLabelElement()
+ expect(xTitle?.textContent).toMatch(/\u2026$/)
+ expect(yTitle?.textContent).toMatch(/\u2026$/)
+ expect(xTitle?.textContent).not.toBe(xAxisLabel)
+ expect(yTitle?.textContent).not.toBe(yAxisLabel)
+ expect(xTitle?.getAttribute('data-full-label')).toBe(xAxisLabel)
+ expect(yTitle?.getAttribute('data-full-label')).toBe(yAxisLabel)
+ expect(yTitle?.getAttribute('transform')).toContain('rotate(-90')
+ })
+
+ it('hides an axis title when that axis is hidden', () => {
+ const { chart } = renderHogChart(
+ <LineChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ xAxisLabel: 'Signup date', yAxisLabel: 'Unique users', hideXAxis: true }}
+ />
+ )
+ expect(chart.xAxisLabel()).toBeNull()
+ expect(chart.yAxisLabel()).toBe('Unique users')
+ })
+
it('renders a right axis when a series sets yAxisId: right', () => {
const series: Series[] = [
{ key: 'a', label: 'A', data: [10, 20, 30] },
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index 67c6d9596cef..4f9552391e7d 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -107,6 +107,8 @@ export function TimeSeriesBarChart<Meta = unknown>({
yTickFormatter,
hideXAxis: xAxis?.hide,
hideYAxis: yAxis?.hide,
+ xAxisLabel: xAxis?.label,
+ yAxisLabel: yAxis?.label,
showGrid: yAxis?.showGrid,
barLayout,
barCornerRadius,
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index f5c52e0be8a1..56a64505c2b6 100644
--- a/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -111,6 +111,8 @@ export function TimeSeriesLineChart<Meta = unknown>({
yTickFormatter,
hideXAxis: xAxis?.hide,
hideYAxis: yAxis?.hide,
+ xAxisLabel: xAxis?.label,
+ yAxisLabel: yAxis?.label,
showGrid: yAxis?.showGrid,
percentStackView,
showCrosshair,
diff --git a/frontend/src/lib/hog-charts/core/Chart.tsx b/frontend/src/lib/hog-charts/core/Chart.tsx
index 30941a4e622f..fffb9f57b063 100644
--- a/frontend/src/lib/hog-charts/core/Chart.tsx
+++ b/frontend/src/lib/hog-charts/core/Chart.tsx
@@ -1,8 +1,10 @@
import React, { useCallback, useMemo } from 'react'
import { AxisLabels } from '../overlays/AxisLabels'
+import { AxisTitles } from '../overlays/AxisTitles'
import { DefaultTooltip } from '../overlays/DefaultTooltip'
import { Tooltip } from '../overlays/Tooltip'
+import { normalizeAxisLabel } from '../utils/axis-labels'
import { composeDrawHoverWithCrosshair } from './canvas-renderer'
import { ChartHoverContext, ChartLayoutContext } from './chart-context'
import type { ChartHoverContextValue, ChartLayoutContextValue } from './chart-context'
@@ -52,6 +54,7 @@ const OVERLAY_CANVAS_STYLE: React.CSSProperties = {
left: 0,
pointerEvents: 'none',
}
+const DEFAULT_AXIS_COLOR = 'rgba(0, 0, 0, 0.5)'
function OverlayLayer({ children }: { children: React.ReactNode }): React.ReactElement {
return <div style={OVERLAY_STYLE}>{children}</div>
@@ -112,6 +115,8 @@ export function Chart<Meta = unknown>({
yTickFormatter,
hideXAxis = false,
hideYAxis = false,
+ xAxisLabel,
+ yAxisLabel,
tooltip: tooltipConfig,
showCrosshair = false,
axisOrientation = 'vertical',
@@ -129,6 +134,8 @@ export function Chart<Meta = unknown>({
labels,
hideXAxis,
hideYAxis,
+ xAxisLabel,
+ yAxisLabel,
xTickFormatter,
yTickFormatter,
axisOrientation,
@@ -201,8 +208,17 @@ export function Chart<Meta = unknown>({
const ariaLabel = useMemo(() => {
const visible = coloredSeries.reduce((n, s) => n + (s.visibility?.excluded ? 0 : 1), 0)
- return `Chart with ${visible} data series`
- }, [coloredSeries])
+ const parts = [`Chart with ${visible} data series`]
+ const cleanXAxisLabel = normalizeAxisLabel(xAxisLabel)
+ const cleanYAxisLabel = normalizeAxisLabel(yAxisLabel)
+ if (!hideXAxis && cleanXAxisLabel) {
+ parts.push(`X-axis: ${cleanXAxisLabel}`)
+ }
+ if (!hideYAxis && cleanYAxisLabel) {
+ parts.push(`Y-axis: ${cleanYAxisLabel}`)
+ }
+ return parts.join('. ')
+ }, [coloredSeries, hideXAxis, hideYAxis, xAxisLabel, yAxisLabel])
const canvasBounds = useCallback(
(): DOMRect | null => canvasRef.current?.getBoundingClientRect() ?? null,
@@ -217,6 +233,7 @@ export function Chart<Meta = unknown>({
() => ({ orientation: axisOrientation, xTickFormatter, isPercent }),
[axisOrientation, xTickFormatter, isPercent]
)
+ const axisColor = theme.axisColor ?? DEFAULT_AXIS_COLOR
const layoutValue = useMemo<ChartLayoutContextValue | null>(() => {
if (!scales || !dimensions) {
@@ -259,10 +276,17 @@ export function Chart<Meta = unknown>({
yRightTickFormatter={resolvedYRightFormatter}
hideXAxis={hideXAxis}
hideYAxis={hideYAxis}
- axisColor={theme.axisColor}
+ axisColor={axisColor}
orientation={axisOrientation}
labelToCoord={labelToCoord}
/>
+ <AxisTitles
+ xAxisLabel={xAxisLabel}
+ yAxisLabel={yAxisLabel}
+ hideXAxis={hideXAxis}
+ hideYAxis={hideYAxis}
+ axisColor={axisColor}
+ />
{children}
diff --git a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.test.ts b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.test.ts
index 03961dec2978..7166b3612704 100644
--- a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.test.ts
+++ b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.test.ts
@@ -30,6 +30,14 @@ describe('useChartMargins', () => {
expect(render().bottom).toBe(DEFAULT_MARGINS.bottom)
})
+ it('adds bottom space for an x-axis title', () => {
+ expect(render({ xAxisLabel: 'Signup date' }).bottom).toBeGreaterThan(DEFAULT_MARGINS.bottom)
+ })
+
+ it('does not add bottom space for a whitespace-only x-axis title', () => {
+ expect(render({ xAxisLabel: ' ' }).bottom).toBe(DEFAULT_MARGINS.bottom)
+ })
+
it('collapses left margin when hideYAxis is true', () => {
expect(render({ hideYAxis: true }).left).toBe(8)
})
@@ -38,6 +46,16 @@ describe('useChartMargins', () => {
expect(render({ series: [], labels: [] }).left).toBeGreaterThanOrEqual(20)
})
+ it('adds left space for a y-axis title', () => {
+ const withoutTitle = render()
+ const withTitle = render({ yAxisLabel: 'Unique users' })
+ expect(withTitle.left).toBeGreaterThan(withoutTitle.left)
+ })
+
+ it('does not add left space for a whitespace-only y-axis title', () => {
+ expect(render({ yAxisLabel: ' ' }).left).toBe(render().left)
+ })
+
it('grows the right margin to at least 48 when multiple y-axes are present', () => {
const dual: Series[] = [
{ key: 'a', label: 'A', data: [1, 2, 3] },
diff --git a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
index 13d421877c47..f38567081f3d 100644
--- a/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
+++ b/frontend/src/lib/hog-charts/core/hooks/useChartMargins.ts
@@ -1,6 +1,7 @@
import * as d3 from 'd3'
import { useMemo } from 'react'
+import { normalizeAxisLabel } from '../../utils/axis-labels'
import { measureLabelWidth } from '../../utils/text-measure'
import { autoFormatterFor, seriesValueRange } from '../scales'
import { DEFAULT_Y_AXIS_ID } from '../types'
@@ -13,12 +14,16 @@ const MIN_LEFT_MARGIN = 20
const MIN_RIGHT_MARGIN_DUAL_AXIS = 48
const Y_LABEL_RIGHT_PADDING = 12
const X_LABEL_EDGE_PADDING = 4
+const X_AXIS_TITLE_MARGIN = 22
+const Y_AXIS_TITLE_MARGIN = 24
interface UseChartMarginsOptions {
series: Series[]
labels: string[]
hideXAxis: boolean
hideYAxis: boolean
+ xAxisLabel?: string
+ yAxisLabel?: string
xTickFormatter?: (value: string, index: number) => string | null
yTickFormatter?: (value: number) => string
axisOrientation?: 'vertical' | 'horizontal'
@@ -63,11 +68,15 @@ export function useChartMargins({
labels,
hideXAxis,
hideYAxis,
+ xAxisLabel,
+ yAxisLabel,
xTickFormatter,
yTickFormatter,
axisOrientation = 'vertical',
}: UseChartMarginsOptions): ChartMargins {
const isHorizontal = axisOrientation === 'horizontal'
+ const normalizedXAxisLabel = normalizeAxisLabel(xAxisLabel)
+ const normalizedYAxisLabel = normalizeAxisLabel(yAxisLabel)
const hasMultipleAxes = useMemo(() => {
const axisIds = new Set(
@@ -101,16 +110,26 @@ export function useChartMargins({
}, [labels, xTickFormatter, hideXAxis, isHorizontal, series, yTickFormatter])
return useMemo<ChartMargins>(() => {
- const bottom = hideXAxis ? COLLAPSED_AXIS_MARGIN : DEFAULT_MARGINS.bottom
+ const bottom = hideXAxis
+ ? COLLAPSED_AXIS_MARGIN
+ : DEFAULT_MARGINS.bottom + (normalizedXAxisLabel ? X_AXIS_TITLE_MARGIN : 0)
const left = hideYAxis
? COLLAPSED_AXIS_MARGIN
: Math.max(
MIN_LEFT_MARGIN,
Math.ceil(yLabelWidth) + Y_LABEL_RIGHT_PADDING,
xLabelHalfWidth + X_LABEL_EDGE_PADDING
- )
+ ) + (normalizedYAxisLabel ? Y_AXIS_TITLE_MARGIN : 0)
const rightFloor = hasMultipleAxes && !hideYAxis ? MIN_RIGHT_MARGIN_DUAL_AXIS : DEFAULT_MARGINS.right
const right = Math.max(rightFloor, xLabelHalfWidth + X_LABEL_EDGE_PADDING)
return { top: DEFAULT_MARGINS.top, right, bottom, left }
- }, [hideXAxis, hideYAxis, hasMultipleAxes, yLabelWidth, xLabelHalfWidth])
+ }, [
+ hideXAxis,
+ hideYAxis,
+ hasMultipleAxes,
+ yLabelWidth,
+ xLabelHalfWidth,
+ normalizedXAxisLabel,
+ normalizedYAxisLabel,
+ ])
}
diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.ts
index 1ab6dde7a09b..70cb33e7327c 100644
--- a/frontend/src/lib/hog-charts/core/types.ts
+++ b/frontend/src/lib/hog-charts/core/types.ts
@@ -160,6 +160,8 @@ export interface ChartConfig {
hideXAxis?: boolean
/** Hide the y-axis labels and reduce left margin. */
hideYAxis?: boolean
+ xAxisLabel?: string
+ yAxisLabel?: string
// — Overlays —
diff --git a/frontend/src/lib/hog-charts/docs/TESTING.md b/frontend/src/lib/hog-charts/docs/TESTING.md
index 98b14727daaf..1205905377ff 100644
--- a/frontend/src/lib/hog-charts/docs/TESTING.md
+++ b/frontend/src/lib/hog-charts/docs/TESTING.md
@@ -50,6 +50,10 @@ chart.seriesCount // visible series count, from the canvas's aria-label
chart.yTicks() // ['0', '20', '40', …]
chart.yRightTicks() // right-axis ticks (multi-axis charts)
chart.xTicks() // post-collision-avoidance x ticks
+chart.xAxisLabel() // optional x-axis label
+chart.yAxisLabel() // optional y-axis label
+chart.xAxisLabelElement() // optional x-axis label SVG element
+chart.yAxisLabelElement() // optional y-axis label SVG element
chart.hasRightAxis // boolean
chart.referenceLines() // [{ label, position, color, orientation }, …]
chart.valueLabels() // [{ text, color }, …]
diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.ts
index 232975ce98cf..10b769865145 100644
--- a/frontend/src/lib/hog-charts/index.ts
+++ b/frontend/src/lib/hog-charts/index.ts
@@ -76,6 +76,8 @@ export type {
} from './overlays/ReferenceLine'
export { ValueLabels } from './overlays/ValueLabels'
export type { ValueLabelsProps } from './overlays/ValueLabels'
+export { AxisTitles } from './overlays/AxisTitles'
+export type { AxisTitlesProps } from './overlays/AxisTitles'
// Helper for adapters that need to align with the same x-axis tick selection the chart draws.
export { computeVisibleXLabels } from './overlays/AxisLabels'
diff --git a/frontend/src/lib/hog-charts/overlays/AxisTitles.tsx b/frontend/src/lib/hog-charts/overlays/AxisTitles.tsx
new file mode 100644
index 000000000000..083104b2c6a8
--- /dev/null
+++ b/frontend/src/lib/hog-charts/overlays/AxisTitles.tsx
@@ -0,0 +1,127 @@
+import React from 'react'
+
+import { useChartLayout } from '../core/chart-context'
+import { normalizeAxisLabel } from '../utils/axis-labels'
+import { AXIS_LABEL_FONT, measureLabelWidth } from '../utils/text-measure'
+
+export interface AxisTitlesProps {
+ xAxisLabel?: string
+ yAxisLabel?: string
+ hideXAxis?: boolean
+ hideYAxis?: boolean
+ axisColor: string
+}
+
+const AXIS_TITLE_STYLE: React.CSSProperties = {
+ fontSize: 12,
+ fontWeight: 500,
+ pointerEvents: 'none',
+}
+const AXIS_TITLE_FONT = `500 ${AXIS_LABEL_FONT}`
+
+const SVG_STYLE: React.CSSProperties = {
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: '100%',
+ height: '100%',
+ pointerEvents: 'none',
+ overflow: 'visible',
+}
+
+const X_AXIS_TITLE_BASELINE_OFFSET = 6
+const Y_AXIS_TITLE_X = 12
+const TITLE_EDGE_PADDING = 8
+const ELLIPSIS = '\u2026'
+
+function measureAxisTitleWidth(label: string): number {
+ const measured = measureLabelWidth(label, AXIS_TITLE_FONT)
+ const fallback = label.length * 7
+ return measured > 0 ? measured : fallback
+}
+
+function truncateAxisTitle(label: string, maxWidth: number): string {
+ if (maxWidth <= 0 || measureAxisTitleWidth(label) <= maxWidth) {
+ return label
+ }
+
+ const ellipsisWidth = measureAxisTitleWidth(ELLIPSIS)
+ if (ellipsisWidth >= maxWidth) {
+ return ELLIPSIS
+ }
+
+ let low = 0
+ let high = label.length
+ while (low < high) {
+ const mid = Math.ceil((low + high) / 2)
+ const candidate = `${label.slice(0, mid).trimEnd()}${ELLIPSIS}`
+ if (measureAxisTitleWidth(candidate) <= maxWidth) {
+ low = mid
+ } else {
+ high = mid - 1
+ }
+ }
+
+ return `${label.slice(0, low).trimEnd()}${ELLIPSIS}`
+}
+
+export function AxisTitles({
+ xAxisLabel,
+ yAxisLabel,
+ hideXAxis,
+ hideYAxis,
+ axisColor,
+}: AxisTitlesProps): React.ReactElement | null {
+ const { dimensions } = useChartLayout()
+ const fullXAxisLabel = normalizeAxisLabel(xAxisLabel)
+ const fullYAxisLabel = normalizeAxisLabel(yAxisLabel)
+ const showXAxisTitle = !hideXAxis && !!fullXAxisLabel
+ const showYAxisTitle = !hideYAxis && !!fullYAxisLabel
+
+ if (!showXAxisTitle && !showYAxisTitle) {
+ return null
+ }
+
+ const xCenter = dimensions.plotLeft + dimensions.plotWidth / 2
+ const xBaseline = dimensions.height - X_AXIS_TITLE_BASELINE_OFFSET
+ const yCenter = dimensions.plotTop + dimensions.plotHeight / 2
+ const xTitle = fullXAxisLabel
+ ? truncateAxisTitle(fullXAxisLabel, Math.max(0, dimensions.plotWidth - TITLE_EDGE_PADDING * 2))
+ : undefined
+ const yTitle = fullYAxisLabel
+ ? truncateAxisTitle(fullYAxisLabel, Math.max(0, dimensions.plotHeight - TITLE_EDGE_PADDING * 2))
+ : undefined
+
+ return (
+ <svg aria-hidden="true" style={SVG_STYLE}>
+ {showXAxisTitle && xTitle && (
+ <text
+ data-attr="hog-chart-axis-title-x"
+ data-full-label={fullXAxisLabel}
+ x={xCenter}
+ y={xBaseline}
+ fill={axisColor}
+ textAnchor="middle"
+ style={AXIS_TITLE_STYLE}
+ >
+ {xTitle}
+ </text>
+ )}
+ {showYAxisTitle && yTitle && (
+ <text
+ data-attr="hog-chart-axis-title-y"
+ data-full-label={fullYAxisLabel}
+ x={Y_AXIS_TITLE_X}
+ y={yCenter}
+ fill={axisColor}
+ textAnchor="middle"
+ dominantBaseline="middle"
+ transform={`rotate(-90 ${Y_AXIS_TITLE_X} ${yCenter})`}
+ style={AXIS_TITLE_STYLE}
+ >
+ {yTitle}
+ </text>
+ )}
+ </svg>
+ )
+}
diff --git a/frontend/src/lib/hog-charts/testing/accessor.ts b/frontend/src/lib/hog-charts/testing/accessor.ts
index 8016ca41cd1a..f31b0c717875 100644
--- a/frontend/src/lib/hog-charts/testing/accessor.ts
+++ b/frontend/src/lib/hog-charts/testing/accessor.ts
@@ -56,6 +56,10 @@ export interface HogChart<Meta = unknown> {
yRightTicks(): string[]
/** Visible x-axis tick labels (post-collision-avoidance). */
xTicks(): string[]
+ xAxisLabel(): string | null
+ yAxisLabel(): string | null
+ xAxisLabelElement(): SVGTextElement | null
+ yAxisLabelElement(): SVGTextElement | null
/** Whether a right-y axis was rendered. */
hasRightAxis: boolean
/** All reference lines currently rendered for this chart (goal/alert/marker). */
@@ -173,6 +177,12 @@ export function getHogChart<Meta = unknown>(
Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-axis-tick-x"]')).map(
(el) => el.textContent ?? ''
),
+ xAxisLabel: () =>
+ wrapper.querySelector<HTMLElement>('[data-attr="hog-chart-axis-title-x"]')?.textContent ?? null,
+ yAxisLabel: () =>
+ wrapper.querySelector<HTMLElement>('[data-attr="hog-chart-axis-title-y"]')?.textContent ?? null,
+ xAxisLabelElement: () => wrapper.querySelector<SVGTextElement>('[data-attr="hog-chart-axis-title-x"]'),
+ yAxisLabelElement: () => wrapper.querySelector<SVGTextElement>('[data-attr="hog-chart-axis-title-y"]'),
referenceLines: () =>
Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-reference-line"]')).map(
readReferenceLine
diff --git a/frontend/src/lib/hog-charts/utils/axis-labels.ts b/frontend/src/lib/hog-charts/utils/axis-labels.ts
new file mode 100644
index 000000000000..1e5721a182d3
--- /dev/null
+++ b/frontend/src/lib/hog-charts/utils/axis-labels.ts
@@ -0,0 +1,4 @@
+export function normalizeAxisLabel(label: string | null | undefined): string | undefined {
+ const trimmed = label?.trim()
+ return trimmed ? trimmed : undefined
+}
diff --git a/frontend/src/lib/hog-charts/utils/use-axis-formatters.ts b/frontend/src/lib/hog-charts/utils/use-axis-formatters.ts
index 9d518e098349..95c623e15ebb 100644
--- a/frontend/src/lib/hog-charts/utils/use-axis-formatters.ts
+++ b/frontend/src/lib/hog-charts/utils/use-axis-formatters.ts
@@ -4,6 +4,7 @@ import { createXAxisTickCallback, type TimeInterval } from './dates'
import { buildYTickFormatter, type YFormatterConfig } from './y-formatters'
export interface XAxisConfig {
+ label?: string
/** Explicit tick formatter. When set, it wins over the auto date formatter. */
tickFormatter?: (value: string, index: number) => string | null
hide?: boolean
@@ -16,6 +17,7 @@ export interface XAxisConfig {
}
export interface YAxisConfig extends YFormatterConfig {
+ label?: string
scale?: 'linear' | 'log'
/** Custom tick formatter. When set, it wins over `format`. */
tickFormatter?: (value: number) => string
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.test.ts b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.test.ts
index 5fdfe030d71f..cf2dec7365f0 100644
--- a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.test.ts
+++ b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.test.ts
@@ -498,6 +498,8 @@ describe('filtersToQueryNode', () => {
aggregation_axis_prefix: '£',
aggregation_axis_postfix: '%',
decimal_places: 8,
+ x_axis_label: 'Signup date',
+ y_axis_label: 'Unique users',
breakdown_histogram_bin_count: 1,
formula: 'A+B',
shown_as: ShownAsValue.VOLUME,
@@ -517,6 +519,8 @@ describe('filtersToQueryNode', () => {
aggregationAxisPrefix: '£',
aggregationAxisPostfix: '%',
decimalPlaces: 8,
+ xAxisLabel: 'Signup date',
+ yAxisLabel: 'Unique users',
formula: 'A+B',
display: ChartDisplayType.ActionsAreaGraph,
showPercentStackView: true,
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
index eef72d97c887..9203e6000778 100644
--- a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
+++ b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
@@ -542,6 +542,8 @@ export const trendsFilterToQuery = (filters: Partial<TrendsFilterType>): TrendsF
aggregationAxisPrefix: filters.aggregation_axis_prefix,
aggregationAxisPostfix: filters.aggregation_axis_postfix,
decimalPlaces: filters.decimal_places,
+ xAxisLabel: filters.x_axis_label,
+ yAxisLabel: filters.y_axis_label,
formula: filters.formula,
display: filters.display,
showValuesOnSeries: filters.show_values_on_series,
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.test.ts b/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.test.ts
index 494feaf4f03a..3daa3992b9e8 100644
--- a/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.test.ts
+++ b/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.test.ts
@@ -1,5 +1,6 @@
import { FunnelLayout } from 'lib/constants'
+import { filtersToQueryNode } from '~/queries/nodes/InsightQuery/utils/filtersToQueryNode'
import { hiddenLegendItemsToKeys, queryNodeToFilter } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'
import {
FunnelsQuery,
@@ -89,6 +90,8 @@ describe('queryNodeToFilter', () => {
aggregationAxisPrefix: 'M',
aggregationAxisPostfix: '$',
decimalPlaces: 5,
+ xAxisLabel: 'Signup date',
+ yAxisLabel: 'Unique users',
showValuesOnSeries: true,
showLabelsOnSeries: true,
showPercentStackView: true,
@@ -118,6 +121,8 @@ describe('queryNodeToFilter', () => {
aggregation_axis_format: 'numeric',
aggregation_axis_prefix: 'M',
aggregation_axis_postfix: '$',
+ x_axis_label: 'Signup date',
+ y_axis_label: 'Unique users',
breakdown: '$browser',
breakdown_hide_other_aggregation: true,
breakdown_limit: 1,
@@ -133,6 +138,20 @@ describe('queryNodeToFilter', () => {
expect(result).toEqual(filters)
})
+ test('round-trips axis labels through legacy trends filters', () => {
+ const query: TrendsQuery = {
+ kind: NodeKind.TrendsQuery,
+ series: [],
+ trendsFilter: {
+ display: ChartDisplayType.ActionsLineGraph,
+ xAxisLabel: 'Signup date',
+ yAxisLabel: 'Unique users',
+ },
+ }
+
+ expect(filtersToQueryNode(queryNodeToFilter(query))).toEqual(query)
+ })
+
test('converts a funnelsFilter into filter properties', () => {
const query: FunnelsQuery = {
kind: NodeKind.FunnelsQuery,
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts b/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts
index b16512a3dcf9..84851339bc4b 100644
--- a/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts
+++ b/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts
@@ -257,6 +257,8 @@ export const queryNodeToFilter = (query: InsightQueryNode): Partial<FilterType>
camelCasedTrendsProps.aggregation_axis_format = queryCopy.trendsFilter?.aggregationAxisFormat
camelCasedTrendsProps.aggregation_axis_postfix = queryCopy.trendsFilter?.aggregationAxisPostfix
camelCasedTrendsProps.aggregation_axis_prefix = queryCopy.trendsFilter?.aggregationAxisPrefix
+ camelCasedTrendsProps.x_axis_label = queryCopy.trendsFilter?.xAxisLabel
+ camelCasedTrendsProps.y_axis_label = queryCopy.trendsFilter?.yAxisLabel
camelCasedTrendsProps.show_labels_on_series = queryCopy.trendsFilter?.showLabelsOnSeries
camelCasedTrendsProps.show_percent_stack_view = queryCopy.trendsFilter?.showPercentStackView
camelCasedTrendsProps.show_legend = queryCopy.trendsFilter?.showLegend
@@ -269,6 +271,8 @@ export const queryNodeToFilter = (query: InsightQueryNode): Partial<FilterType>
delete queryCopy.trendsFilter?.aggregationAxisFormat
delete queryCopy.trendsFilter?.aggregationAxisPostfix
delete queryCopy.trendsFilter?.aggregationAxisPrefix
+ delete queryCopy.trendsFilter?.xAxisLabel
+ delete queryCopy.trendsFilter?.yAxisLabel
delete queryCopy.trendsFilter?.showLabelsOnSeries
delete queryCopy.trendsFilter?.showPercentStackView
delete queryCopy.trendsFilter?.showLegend
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
index 31356694337a..ccad23986866 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
@@ -1,9 +1,10 @@
import '@testing-library/jest-dom'
-import { cleanup, render, screen, within } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { BindLogic, Provider } from 'kea'
+import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
@@ -19,7 +20,10 @@ import { InsightDisplayConfig } from './InsightDisplayConfig'
const Insight123 = '123' as InsightShortId
const insightProps = { dashboardItemId: Insight123 }
-function makeTrendsQuery(display?: ChartDisplayType): TrendsQuery {
+function makeTrendsQuery(
+ display?: ChartDisplayType,
+ trendsFilter: NonNullable<TrendsQuery['trendsFilter']> = {}
+): TrendsQuery {
return {
kind: NodeKind.TrendsQuery,
series: [
@@ -32,6 +36,7 @@ function makeTrendsQuery(display?: ChartDisplayType): TrendsQuery {
],
trendsFilter: {
display,
+ ...trendsFilter,
},
}
}
@@ -115,5 +120,25 @@ describe('InsightDisplayConfig', () => {
expect(screen.getByText('Y-axis scale')).toBeInTheDocument()
})
+
+ it('removes axis label option count after clearing a committed label', async () => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_TRENDS], {
+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_TRENDS]: true,
+ })
+ setupAndRender(makeTrendsQuery(ChartDisplayType.ActionsLineGraph, { xAxisLabel: 'Signup date' }))
+
+ const optionsButton = screen.getAllByRole('button', { name: /Options/ })[0]
+ expect(optionsButton).toHaveTextContent(/\(1\)/)
+
+ await openOptionsMenu()
+ const input = await screen.findByPlaceholderText('X-axis label')
+ await userEvent.clear(input)
+ expect(optionsButton).toHaveTextContent(/\(1\)/)
+
+ fireEvent.blur(input)
+ await waitFor(() => {
+ expect(optionsButton).not.toHaveTextContent(/\(1\)/)
+ })
+ })
})
})
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
index 1af1decee3b8..24f7f25832f2 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
@@ -13,11 +13,13 @@ import { SmoothingFilter } from 'lib/components/SmoothingFilter/SmoothingFilter'
import { smoothingOptions } from 'lib/components/SmoothingFilter/smoothings'
import { UnitPicker } from 'lib/components/UnitPicker/UnitPicker'
import { FEATURE_FLAGS, NON_TIME_SERIES_DISPLAY_TYPES } from 'lib/constants'
+import { normalizeAxisLabel } from 'lib/hog-charts/utils/axis-labels'
import { LemonMenu, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { DEFAULT_DECIMAL_PLACES } from 'lib/utils'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { axisLabel } from 'scenes/insights/aggregationAxisFormat'
+import { AxisLabelsFilter } from 'scenes/insights/EditorFilters/AxisLabelsFilter'
import { HideWeekendsFilter } from 'scenes/insights/EditorFilters/HideWeekendsFilter'
import { LifecycleStackingFilter } from 'scenes/insights/EditorFilters/LifecycleStackingFilter'
import { PercentStackViewFilter } from 'scenes/insights/EditorFilters/PercentStackViewFilter'
@@ -49,6 +51,28 @@ import { hasBreakdownFilter, isWebAnalyticsInsightQuery } from '~/queries/utils'
import { isTrendsQuery } from '~/queries/utils'
import { ChartDisplayType } from '~/types'
+const LINE_DISPLAYS = [
+ ChartDisplayType.ActionsLineGraph,
+ ChartDisplayType.ActionsLineGraphCumulative,
+ ChartDisplayType.ActionsAreaGraph,
+] as const
+const BAR_DISPLAYS = [
+ ChartDisplayType.ActionsBar,
+ ChartDisplayType.ActionsUnstackedBar,
+ ChartDisplayType.ActionsBarValue,
+] as const
+
+function displayMatches(display: ChartDisplayType | null | undefined, displays: readonly ChartDisplayType[]): boolean {
+ return !!display && displays.includes(display)
+}
+
+function isDefaultTrendsLineDisplay(
+ display: ChartDisplayType | null | undefined,
+ querySource: Parameters<typeof isTrendsQuery>[0]
+): boolean {
+ return !display && isTrendsQuery(querySource)
+}
+
export function InsightDisplayConfig(): JSX.Element {
const { insightProps, canEditInsight, editingDisabledReason } = useValues(insightLogic)
@@ -103,10 +127,12 @@ export function InsightDisplayConfig(): JSX.Element {
(smoothingOptions[interval]?.length ?? 0) > 0
const showMultipleYAxesConfig = (isTrends || isStickiness) && !isNonTimeSeriesDisplay
const showAlertThresholdLinesConfig = isTrends && !isNonTimeSeriesDisplay
- const isLineGraph =
- display === ChartDisplayType.ActionsLineGraph ||
- display === ChartDisplayType.ActionsAreaGraph ||
- (!display && isTrendsQuery(querySource))
+ const isLineDisplay = isDefaultTrendsLineDisplay(display, querySource) || displayMatches(display, LINE_DISPLAYS)
+ const isBarDisplay = displayMatches(display, BAR_DISPLAYS)
+ const isCumulativeLineDisplay = display === ChartDisplayType.ActionsLineGraphCumulative
+ const showAxisLabelsConfig =
+ isTrends && (isLineDisplay || isBarDisplay) && featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOG_CHARTS_TRENDS]
+ const isLineGraph = isLineDisplay && !isCumulativeLineDisplay
const isLinearScale = !yAxisScaleType || yAxisScaleType === 'linear'
const { showValuesOnSeries, mightContainFractionalNumbers, showConfidenceIntervals, showMovingAverage } = useValues(
@@ -309,6 +335,14 @@ export function InsightDisplayConfig(): JSX.Element {
]),
]
: []),
+ ...(showAxisLabelsConfig
+ ? [
+ {
+ title: 'Axis labels',
+ items: [{ label: () => <AxisLabelsFilter /> }],
+ },
+ ]
+ : []),
...(mightContainFractionalNumbers && isTrends && display !== ChartDisplayType.CalendarHeatmap
? [
{
@@ -349,6 +383,8 @@ export function InsightDisplayConfig(): JSX.Element {
: 0) +
(hasLegend && showLegend ? 1 : 0) +
(!!yAxisScaleType && yAxisScaleType !== 'linear' ? 1 : 0) +
+ (showAxisLabelsConfig && normalizeAxisLabel(trendsFilter?.xAxisLabel) ? 1 : 0) +
+ (showAxisLabelsConfig && normalizeAxisLabel(trendsFilter?.yAxisLabel) ? 1 : 0) +
(showMultipleYAxes ? 1 : 0) +
(trendsFilter?.hideWeekends && hideWeekendsEnabled ? 1 : 0)
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index d4ce801a7572..467e1de96995 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -4030,6 +4030,14 @@
"default": 1,
"description": "Smoothing intervals for the trend line."
},
+ "xAxisLabel": {
+ "description": "Custom label rendered under the X axis.",
+ "type": "string"
+ },
+ "yAxisLabel": {
+ "description": "Custom label rendered alongside the Y axis.",
+ "type": "string"
+ },
"yAxisScaleType": {
"default": "linear",
"description": "Whether to scale the y-axis.",
@@ -38520,6 +38528,14 @@
"$ref": "#/definitions/integer",
"default": 1
},
+ "xAxisLabel": {
+ "description": "Custom label rendered under the X axis.",
+ "type": "string"
+ },
+ "yAxisLabel": {
+ "description": "Custom label rendered alongside the Y axis.",
+ "type": "string"
+ },
"yAxisScaleType": {
"enum": ["log10", "linear"],
"type": "string"
@@ -38595,6 +38611,12 @@
"smoothing_intervals": {
"type": "number"
},
+ "x_axis_label": {
+ "type": "string"
+ },
+ "y_axis_label": {
+ "type": "string"
+ },
"y_axis_scale_type": {
"enum": ["log10", "linear"],
"type": "string"
diff --git a/frontend/src/queries/schema/schema-assistant-queries.ts b/frontend/src/queries/schema/schema-assistant-queries.ts
index 8d8257107313..17495281ea98 100644
--- a/frontend/src/queries/schema/schema-assistant-queries.ts
+++ b/frontend/src/queries/schema/schema-assistant-queries.ts
@@ -535,6 +535,12 @@ export interface AssistantTrendsFilter {
*/
yAxisScaleType?: TrendsFilterLegacy['y_axis_scale_type']
+ /** Custom label rendered under the X axis. */
+ xAxisLabel?: TrendsFilterLegacy['x_axis_label']
+
+ /** Custom label rendered alongside the Y axis. */
+ yAxisLabel?: TrendsFilterLegacy['y_axis_label']
+
/**
* Whether to show alert threshold lines on the chart.
* @default false
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 5d5b8ff6448f..63ff6f77b9b5 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1414,6 +1414,10 @@ export type TrendsFilter = {
/** Maximum number of decimal places shown. 1 or 2 is usually right for percentages and currency. */
decimalPlaces?: TrendsFilterLegacy['decimal_places']
minDecimalPlaces?: TrendsFilterLegacy['min_decimal_places']
+ /** Custom label rendered under the X axis. */
+ xAxisLabel?: TrendsFilterLegacy['x_axis_label']
+ /** Custom label rendered alongside the Y axis. */
+ yAxisLabel?: TrendsFilterLegacy['y_axis_label']
/** @default false */
showValuesOnSeries?: TrendsFilterLegacy['show_values_on_series']
showLabelsOnSeries?: TrendsFilterLegacy['show_labels_on_series']
diff --git a/frontend/src/scenes/insights/EditorFilters/AxisLabelsFilter.tsx b/frontend/src/scenes/insights/EditorFilters/AxisLabelsFilter.tsx
new file mode 100644
index 000000000000..c3dadc8e7950
--- /dev/null
+++ b/frontend/src/scenes/insights/EditorFilters/AxisLabelsFilter.tsx
@@ -0,0 +1,66 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { LemonInput, LemonLabel } from '@posthog/lemon-ui'
+
+import { normalizeAxisLabel } from 'lib/hog-charts/utils/axis-labels'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+
+import { insightLogic } from '../insightLogic'
+
+export function AxisLabelsFilter(): JSX.Element {
+ const { insightProps } = useValues(insightLogic)
+ const { trendsFilter } = useValues(insightVizDataLogic(insightProps))
+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))
+ const [xAxisLabelDraft, setXAxisLabelDraft] = useState(trendsFilter?.xAxisLabel ?? '')
+ const [yAxisLabelDraft, setYAxisLabelDraft] = useState(trendsFilter?.yAxisLabel ?? '')
+
+ useEffect(() => {
+ setXAxisLabelDraft(trendsFilter?.xAxisLabel ?? '')
+ }, [trendsFilter?.xAxisLabel])
+
+ useEffect(() => {
+ setYAxisLabelDraft(trendsFilter?.yAxisLabel ?? '')
+ }, [trendsFilter?.yAxisLabel])
+
+ const commitXAxisLabel = (): void => {
+ const normalized = normalizeAxisLabel(xAxisLabelDraft)
+ setXAxisLabelDraft(normalized ?? '')
+ updateInsightFilter({ xAxisLabel: normalized })
+ }
+
+ const commitYAxisLabel = (): void => {
+ const normalized = normalizeAxisLabel(yAxisLabelDraft)
+ setYAxisLabelDraft(normalized ?? '')
+ updateInsightFilter({ yAxisLabel: normalized })
+ }
+
+ return (
+ <div className="p-1 px-2 flex flex-col gap-2 w-64">
+ <div className="flex flex-col gap-1">
+ <LemonLabel>X-axis label</LemonLabel>
+ <LemonInput
+ size="small"
+ data-attr="trends-x-axis-label-input"
+ value={xAxisLabelDraft}
+ placeholder="X-axis label"
+ onChange={setXAxisLabelDraft}
+ onBlur={commitXAxisLabel}
+ onPressEnter={commitXAxisLabel}
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Y-axis label</LemonLabel>
+ <LemonInput
+ size="small"
+ data-attr="trends-y-axis-label-input"
+ value={yAxisLabelDraft}
+ placeholder="Y-axis label"
+ onChange={setYAxisLabelDraft}
+ onBlur={commitYAxisLabel}
+ onPressEnter={commitYAxisLabel}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/insights/utils/queryUtils.ts b/frontend/src/scenes/insights/utils/queryUtils.ts
index 49bb208cf200..d237c5893de1 100644
--- a/frontend/src/scenes/insights/utils/queryUtils.ts
+++ b/frontend/src/scenes/insights/utils/queryUtils.ts
@@ -232,6 +232,8 @@ export const cleanInsightQuery = (query: InsightQueryNode, opts?: CompareQueryOp
aggregationAxisPrefix: undefined,
aggregationAxisPostfix: undefined,
decimalPlaces: undefined,
+ xAxisLabel: undefined,
+ yAxisLabel: undefined,
layout: undefined,
toggledLifecycles: undefined,
showLabelsOnSeries: undefined,
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 78646f44bb29..db419e598465 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2960,6 +2960,8 @@ export interface TrendsFilterType extends FilterType {
aggregation_axis_postfix?: string // a postfix to add to the aggregation axis e.g. %
decimal_places?: number
min_decimal_places?: number
+ x_axis_label?: string
+ y_axis_label?: string
show_values_on_series?: boolean
show_labels_on_series?: boolean
show_percent_stack_view?: boolean
diff --git a/posthog/hogql_queries/legacy_compatibility/filter_to_query.py b/posthog/hogql_queries/legacy_compatibility/filter_to_query.py
index bc38ad2d5dcb..883e4c5b2b28 100644
--- a/posthog/hogql_queries/legacy_compatibility/filter_to_query.py
+++ b/posthog/hogql_queries/legacy_compatibility/filter_to_query.py
@@ -489,6 +489,8 @@ def _insight_filter(filter: dict, allow_variables: bool = False):
aggregationAxisPrefix=filter.get("aggregation_axis_prefix"),
aggregationAxisPostfix=filter.get("aggregation_axis_postfix"),
decimalPlaces=filter.get("decimal_places"),
+ xAxisLabel=filter.get("x_axis_label"),
+ yAxisLabel=filter.get("y_axis_label"),
formula=filter.get("formula"),
display=clean_display(filter.get("display")),
showValuesOnSeries=filter.get("show_values_on_series"),
diff --git a/posthog/hogql_queries/legacy_compatibility/test/test_filter_to_query.py b/posthog/hogql_queries/legacy_compatibility/test/test_filter_to_query.py
index b83b4f509171..2e7e4338b529 100644
--- a/posthog/hogql_queries/legacy_compatibility/test/test_filter_to_query.py
+++ b/posthog/hogql_queries/legacy_compatibility/test/test_filter_to_query.py
@@ -1387,6 +1387,8 @@ class TestFilterToQuery(BaseTest):
"aggregation_axis_prefix": "pre",
"aggregation_axis_postfix": "post",
"decimal_places": 5,
+ "x_axis_label": "Signup date",
+ "y_axis_label": "Unique users",
"formula": "A + B",
"shown_as": "Volume",
"display": "ActionsAreaGraph",
@@ -1407,6 +1409,8 @@ class TestFilterToQuery(BaseTest):
formula="A + B",
display=ChartDisplayType.ACTIONS_AREA_GRAPH,
decimalPlaces=5,
+ xAxisLabel="Signup date",
+ yAxisLabel="Unique users",
showLegend=True,
showPercentStackView=True,
),
diff --git a/posthog/schema.py b/posthog/schema.py
index a1b57f4dffd2..493161c5c444 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5003,6 +5003,8 @@ class TrendsFilterLegacy(BaseModel):
show_percent_stack_view: bool | None = None
show_values_on_series: bool | None = None
smoothing_intervals: float | None = None
+ x_axis_label: str | None = None
+ y_axis_label: str | None = None
y_axis_scale_type: YAxisScaleType | None = YAxisScaleType.LINEAR
@@ -6456,6 +6458,8 @@ class AssistantTrendsFilter(BaseModel):
)
showValuesOnSeries: bool | None = Field(default=False, description="Whether to show a value on each data point.")
smoothingIntervals: int | None = Field(default=1, description="Smoothing intervals for the trend line.")
+ xAxisLabel: str | None = Field(default=None, description="Custom label rendered under the X axis.")
+ yAxisLabel: str | None = Field(default=None, description="Custom label rendered alongside the Y axis.")
yAxisScaleType: YAxisScaleType | None = Field(
default=YAxisScaleType.LINEAR, description="Whether to scale the y-axis."
)
@@ -9062,6 +9066,8 @@ class TrendsFilter(BaseModel):
showTrendLines: bool | None = None
showValuesOnSeries: bool | None = False
smoothingIntervals: int | None = 1
+ xAxisLabel: str | None = Field(default=None, description="Custom label rendered under the X axis.")
+ yAxisLabel: str | None = Field(default=None, description="Custom label rendered alongside the Y axis.")
yAxisScaleType: YAxisScaleType | None = YAxisScaleType.LINEAR
diff --git a/posthog/schema_helpers.py b/posthog/schema_helpers.py
index 1e6e30774bfa..11cc7248a54e 100644
--- a/posthog/schema_helpers.py
+++ b/posthog/schema_helpers.py
@@ -90,6 +90,8 @@ def to_dict(query: BaseModel) -> dict:
"aggregationAxisPrefix",
"aggregationAxisPostfix",
"decimalPlaces",
+ "xAxisLabel",
+ "yAxisLabel",
"layout",
"toggledLifecycles",
"showLabelsOnSeries",
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 4b28f6b26233..1998dc2130e0 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -1542,6 +1542,10 @@ export interface TrendsFilterApi {
showTrendLines?: boolean | null
showValuesOnSeries?: boolean | null
smoothingIntervals?: number | null
+ /** Custom label rendered under the X axis. */
+ xAxisLabel?: string | null
+ /** Custom label rendered alongside the Y axis. */
+ yAxisLabel?: string | null
yAxisScaleType?: YAxisScaleTypeApi | null
}
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
index 4c9bfc188836..f2e67fc180d4 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
@@ -155,6 +155,28 @@ describe('TrendsBarChart (ActionsBarValue)', () => {
})
})
+ it('renders custom axis titles in horizontal aggregated mode', async () => {
+ renderInsight({
+ query: aggregatedBar({
+ trendsFilter: {
+ display: ChartDisplayType.ActionsBarValue,
+ xAxisLabel: 'Total events',
+ yAxisLabel: 'Series',
+ },
+ }),
+ featureFlags: HOG_CHARTS_FLAG,
+ })
+
+ await screen.findByRole('img', { name: /chart with/i })
+ expect(getHogChart().xAxisLabel()).toBe('Total events')
+ expect(getHogChart().yAxisLabel()).toBe('Series')
+ expect(
+ getHogChart()
+ .element.querySelector<SVGTextElement>('[data-attr="hog-chart-axis-title-y"]')
+ ?.getAttribute('transform')
+ ).toContain('rotate(-90')
+ })
+
it('emits one series per breakdown so each bar gets its own color', async () => {
renderInsight({
query: aggregatedBar({
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
index 1be1b3af1c99..c56c2cd467d1 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
@@ -152,6 +152,8 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
interval,
timezone,
allDays: currentPeriodResult?.days ?? [],
+ xAxisLabel: trendsFilter?.xAxisLabel,
+ yAxisLabel: trendsFilter?.yAxisLabel,
goalLines,
valueLabels: showValuesOnSeries ? { formatter: valueLabelFormatter } : false,
tooltip: TIME_SERIES_TOOLTIP_CONFIG,
@@ -165,6 +167,8 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
interval,
timezone,
currentPeriodResult?.days,
+ trendsFilter?.xAxisLabel,
+ trendsFilter?.yAxisLabel,
goalLines,
showValuesOnSeries,
valueLabelFormatter,
@@ -184,8 +188,10 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
axisOrientation: 'horizontal',
barLayout: 'stacked',
yTickFormatter: aggregatedYTickFormatter,
+ xAxisLabel: trendsFilter?.xAxisLabel,
+ yAxisLabel: trendsFilter?.yAxisLabel,
}),
- [yAxisScaleType, aggregatedYTickFormatter]
+ [yAxisScaleType, aggregatedYTickFormatter, trendsFilter?.xAxisLabel, trendsFilter?.yAxisLabel]
)
const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModal
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
index d3b4a8f15194..d5b86110f8a0 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts
@@ -171,12 +171,17 @@ describe('buildTrendsBarTimeSeriesConfig', () => {
{
name: 'builds the xAxis from interval/timezone/allDays',
input: { interval: 'day' as const, timezone: 'UTC', allDays: ['2024-06-10', '2024-06-11'] },
- expected: { timezone: 'UTC', interval: 'day', allDays: ['2024-06-10', '2024-06-11'] },
+ expected: {
+ label: undefined,
+ timezone: 'UTC',
+ interval: 'day',
+ allDays: ['2024-06-10', '2024-06-11'],
+ },
},
{
name: 'defaults interval to "day" and allDays to empty when omitted',
input: {},
- expected: { timezone: undefined, interval: 'day', allDays: [] },
+ expected: { label: undefined, timezone: undefined, interval: 'day', allDays: [] },
},
])('$name', ({ input, expected }) => {
const cfg = buildTrendsBarTimeSeriesConfig({ isPercentStackView: false, isGrouped: false, ...input })
@@ -222,6 +227,17 @@ describe('buildTrendsBarTimeSeriesConfig', () => {
expect(cfg.goalLines).toEqual([expect.objectContaining({ value: 50, label: 'Target' })])
})
+ it('passes custom axis labels into the chart config', () => {
+ const cfg = buildTrendsBarTimeSeriesConfig({
+ isPercentStackView: false,
+ isGrouped: false,
+ xAxisLabel: 'Signup date',
+ yAxisLabel: 'Total events',
+ })
+ expect(cfg.xAxis?.label).toBe('Signup date')
+ expect(cfg.yAxis?.label).toBe('Total events')
+ })
+
it('passes valueLabels and tooltip through unchanged', () => {
const formatter = (v: number): string => `~${v}`
const cfg = buildTrendsBarTimeSeriesConfig({
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
index b31808055362..280af74ee1ef 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts
@@ -1,4 +1,5 @@
import type { Series, TimeSeriesBarChartConfig } from 'lib/hog-charts'
+import { normalizeAxisLabel } from 'lib/hog-charts/utils/axis-labels'
import { hexToRGBA } from 'lib/utils'
import { COMPARE_PREVIOUS_DIM_OPACITY } from 'scenes/trends/viz/trendsAdapterConstants'
@@ -64,6 +65,8 @@ export interface BuildTrendsBarTimeSeriesConfigOpts {
interval?: IntervalType | null
timezone?: string
allDays?: string[]
+ xAxisLabel?: string | null
+ yAxisLabel?: string | null
goalLines?: SchemaGoalLine[] | null
valueLabels?: TimeSeriesBarChartConfig['valueLabels']
tooltip?: TimeSeriesBarChartConfig['tooltip']
@@ -77,11 +80,15 @@ export function buildTrendsBarTimeSeriesConfig(opts: BuildTrendsBarTimeSeriesCon
const goalLineConfigs = schemaGoalLinesToConfigs(opts.goalLines)
return {
xAxis: {
+ label: normalizeAxisLabel(opts.xAxisLabel),
timezone: opts.timezone,
interval: opts.interval ?? 'day',
allDays: opts.allDays ?? [],
},
- yAxis,
+ yAxis: {
+ ...yAxis,
+ label: normalizeAxisLabel(opts.yAxisLabel),
+ },
valueLabels: opts.valueLabels,
goalLines: goalLineConfigs,
barLayout: opts.isPercentStackView ? 'percent' : opts.isGrouped ? 'grouped' : 'stacked',
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx
index 6378c28c0063..05f9af059512 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx
@@ -472,6 +472,32 @@ describe('TrendsLineChart', () => {
})
})
+ describe('axis labels', () => {
+ it.each([
+ {
+ name: 'renders custom axis titles from the trends filter',
+ trendsFilter: { xAxisLabel: 'Signup date', yAxisLabel: 'Unique users' },
+ expectedX: 'Signup date',
+ expectedY: 'Unique users',
+ },
+ {
+ name: 'renders no axis titles when the trends filter omits them',
+ trendsFilter: undefined,
+ expectedX: null,
+ expectedY: null,
+ },
+ ])('$name', async ({ trendsFilter, expectedX, expectedY }) => {
+ renderInsight({
+ query: buildTrendsQuery({ trendsFilter }),
+ featureFlags: HOG_CHARTS_FLAG,
+ })
+
+ await screen.findByRole('img', { name: /chart with/i })
+ expect(getHogChart().xAxisLabel()).toBe(expectedX)
+ expect(getHogChart().yAxisLabel()).toBe(expectedY)
+ })
+ })
+
describe('multi-axis', () => {
it.each([
{ name: 'renders a right y-axis when showMultipleYAxes is true', enabled: true, expectedRight: true },
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
index ffd858dca146..3861f2ac8e05 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
@@ -128,6 +128,8 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
interval,
timezone,
allDays: currentPeriodResult?.days ?? [],
+ xAxisLabel: trendsFilter?.xAxisLabel,
+ yAxisLabel: trendsFilter?.yAxisLabel,
goalLines,
incompletenessOffsetFromEnd,
getHidden: getTrendsHidden,
@@ -150,6 +152,8 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha
interval,
timezone,
currentPeriodResult?.days,
+ trendsFilter?.xAxisLabel,
+ trendsFilter?.yAxisLabel,
goalLines,
incompletenessOffsetFromEnd,
getTrendsHidden,
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts
index 381c384d9a91..b8e2d987ef13 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts
@@ -335,7 +335,12 @@ describe('trendsChartTransforms', () => {
tooltip: TOOLTIP,
})
- expect(config.xAxis).toEqual({ timezone: 'UTC', interval: 'day', allDays: ['2024-01-01', '2024-01-02'] })
+ expect(config.xAxis).toEqual({
+ label: undefined,
+ timezone: 'UTC',
+ interval: 'day',
+ allDays: ['2024-01-01', '2024-01-02'],
+ })
expect(config.yAxis).not.toBeUndefined()
expect(config.valueLabels).toBe(false)
expect(config.goalLines).toHaveLength(1)
@@ -400,6 +405,16 @@ describe('trendsChartTransforms', () => {
expect(config.xAxis?.interval).toBe('day')
})
+ it('passes custom axis labels into the chart config', () => {
+ const config = buildTrendsLineTimeSeriesConfig({
+ ...baseOpts,
+ xAxisLabel: 'Signup date',
+ yAxisLabel: 'Unique users',
+ })
+ expect(config.xAxis?.label).toBe('Signup date')
+ expect(config.yAxis?.label).toBe('Unique users')
+ })
+
it('derives yAxis from buildTrendsYAxisConfig when isPercentStackView is true and passes through tooltip / showCrosshair', () => {
const config = buildTrendsLineTimeSeriesConfig({
...baseOpts,
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts
index 848b69ebb7cd..20732c1bccba 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts
@@ -7,6 +7,7 @@ import type {
TooltipConfig,
TrendLineConfig,
} from 'lib/hog-charts'
+import { normalizeAxisLabel } from 'lib/hog-charts/utils/axis-labels'
import { ciRanges } from 'lib/statistics'
import type { CurrencyCode, GoalLine as SchemaGoalLine, TrendsFilter } from '~/queries/schema/schema-general'
@@ -176,6 +177,8 @@ export interface BuildTrendsLineTimeSeriesConfigOpts<R extends TrendsResultLike>
interval?: IntervalType | null
timezone?: string
allDays?: string[]
+ xAxisLabel?: string | null
+ yAxisLabel?: string | null
goalLines?: SchemaGoalLine[] | null
incompletenessOffsetFromEnd?: number
getHidden?: (r: R) => boolean
@@ -212,11 +215,15 @@ export function buildTrendsLineTimeSeriesConfig<R extends TrendsResultLike>(
})
return {
xAxis: {
+ label: normalizeAxisLabel(opts.xAxisLabel),
timezone: opts.timezone,
interval: opts.interval ?? 'day',
allDays: opts.allDays ?? [],
},
- yAxis,
+ yAxis: {
+ ...yAxis,
+ label: normalizeAxisLabel(opts.yAxisLabel),
+ },
valueLabels: opts.valueLabels,
goalLines: goalLineConfigs,
...derivedConfigs,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 11dca953ae52..be41d70dde96 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2102,6 +2102,10 @@ export namespace Schemas {
showTrendLines?: boolean | null;
showValuesOnSeries?: boolean | null;
smoothingIntervals?: number | null;
+ /** Custom label rendered under the X axis. */
+ xAxisLabel?: string | null;
+ /** Custom label rendered alongside the Y axis. */
+ yAxisLabel?: string | null;
yAxisScaleType?: YAxisScaleType | null;
}
diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.ts
index 1b7a7306158b..0f1cf7404862 100644
--- a/services/mcp/src/tools/generated/query-wrappers.ts
+++ b/services/mcp/src/tools/generated/query-wrappers.ts
@@ -548,6 +548,8 @@ const AssistantTrendsFilter = z.object({
.default(false)
.optional(),
smoothingIntervals: integer.describe('Smoothing intervals for the trend line.').default(1).optional(),
+ xAxisLabel: z.string().describe('Custom label rendered under the X axis.').optional(),
+ yAxisLabel: z.string().describe('Custom label rendered alongside the Y axis.').optional(),
yAxisScaleType: z.enum(['log10', 'linear']).describe('Whether to scale the y-axis.').default('linear').optional(),
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-trends-actors.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-trends-actors.json
index 8483af46edb8..481401e076f0 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-trends-actors.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-trends-actors.json
@@ -3868,6 +3868,14 @@
"minimum": -9007199254740991,
"type": "integer"
},
+ "xAxisLabel": {
+ "description": "Custom label rendered under the X axis.",
+ "type": "string"
+ },
+ "yAxisLabel": {
+ "description": "Custom label rendered alongside the Y axis.",
+ "type": "string"
+ },
"yAxisScaleType": {
"default": "linear",
"description": "Whether to scale the y-axis.",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-trends.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-trends.json
index 7150658583f3..11a2eb918345 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-trends.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/v2/query-trends.json
@@ -3680,6 +3680,14 @@
"minimum": -9007199254740991,
"type": "integer"
},
+ "xAxisLabel": {
+ "description": "Custom label rendered under the X axis.",
+ "type": "string"
+ },
+ "yAxisLabel": {
+ "description": "Custom label rendered alongside the Y axis.",
+ "type": "string"
+ },
"yAxisScaleType": {
"default": "linear",
"description": "Whether to scale the y-axis.",