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(insights): add TimeSeriesBarChart to hog-charts (#58026)

Sam Pennington8cbff4497219
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
new file mode 100644
index 000000000000..fcf047782604
--- /dev/null
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
@@ -0,0 +1,287 @@
+import { useChartLayout } from '../../core/chart-context'
+import type { ChartTheme, Series } from '../../core/types'
+import { renderHogChart } from '../../testing'
+import { TimeSeriesBarChart } from './TimeSeriesBarChart'
+
+const THEME: ChartTheme = { colors: ['#111', '#222', '#333'], backgroundColor: '#ffffff' }
+const LABELS = ['Mon', 'Tue', 'Wed']
+const SERIES: Series[] = [{ key: 'a', label: 'A', data: [1, 2, 3] }]
+
+describe('TimeSeriesBarChart', () => {
+ describe('config.xAxis', () => {
+ it('hides x-axis ticks when xAxis.hide is true', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart series={SERIES} labels={LABELS} theme={THEME} config={{ xAxis: { hide: true } }} />
+ )
+ expect(chart.xTicks()).toHaveLength(0)
+ })
+
+ it('forwards an explicit xAxis.tickFormatter to the chart', () => {
+ const explicit = (_v: string, i: number): string => `tick-${i}`
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={['14:00', '15:00', '16:00']}
+ theme={THEME}
+ config={{ xAxis: { tickFormatter: explicit } }}
+ />
+ )
+ expect(chart.xTicks()).toEqual(['tick-0', 'tick-1', 'tick-2'])
+ })
+
+ it('builds an auto date formatter from xAxis.timezone + xAxis.interval', () => {
+ const labels = ['2024-06-10', '2024-06-11', '2024-06-12']
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={labels}
+ theme={THEME}
+ config={{ xAxis: { timezone: 'UTC', interval: 'day' } }}
+ />
+ )
+ const ticks = chart.xTicks()
+ expect(ticks.length).toBeGreaterThan(0)
+ expect(ticks.some((t) => /Jun \d+/.test(t))).toBe(true)
+ })
+
+ it('explicit xAxis.tickFormatter wins over the auto date formatter', () => {
+ const explicit = (_v: string, i: number): string => `tick-${i}`
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={['2024-06-10', '2024-06-11', '2024-06-12']}
+ theme={THEME}
+ config={{
+ xAxis: { tickFormatter: explicit, timezone: 'UTC', interval: 'day' },
+ }}
+ />
+ )
+ expect(chart.xTicks()).toEqual(['tick-0', 'tick-1', 'tick-2'])
+ })
+
+ it('exposes the resolved formatter to children via ChartLayoutContext', () => {
+ let observed: ((value: string, index: number) => string | null) | undefined
+ function Probe(): null {
+ observed = useChartLayout().axis.xTickFormatter
+ return null
+ }
+ renderHogChart(
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={['2024-06-10', '2024-06-11', '2024-06-12']}
+ theme={THEME}
+ config={{ xAxis: { timezone: 'UTC', interval: 'day' } }}
+ >
+ <Probe />
+ </TimeSeriesBarChart>
+ )
+ expect(observed).not.toBeUndefined()
+ expect(observed?.('2024-06-10', 0)).toMatch(/Jun \d+|June/)
+ })
+ })
+
+ describe('config.yAxis', () => {
+ it('hides y-axis ticks when yAxis.hide is true', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart series={SERIES} labels={LABELS} theme={THEME} config={{ yAxis: { hide: true } }} />
+ )
+ expect(chart.yTicks()).toHaveLength(0)
+ })
+
+ it.each([
+ [{ format: 'percentage' as const }, /\d+%$/],
+ [{ prefix: '$', suffix: ' req' }, /^\$.* req$/],
+ ])('builds a y-axis tick formatter from yAxis %p', (yAxis, pattern) => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart series={SERIES} labels={LABELS} theme={THEME} config={{ yAxis }} />
+ )
+ expect(chart.yTicks().some((t) => pattern.test(t))).toBe(true)
+ })
+
+ it('explicit yAxis.tickFormatter wins over yAxis.format', () => {
+ const explicit = (v: number): string => `y:${v}`
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ yAxis: { tickFormatter: explicit, format: 'percentage' } }}
+ />
+ )
+ expect(chart.yTicks().every((t) => t.startsWith('y:'))).toBe(true)
+ })
+ })
+
+ describe('config.valueLabels', () => {
+ it.each([
+ ['omitted', undefined],
+ ['false', false as const],
+ ])('does not render value labels when %s', (_, valueLabels) => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={valueLabels === undefined ? undefined : { valueLabels }}
+ />
+ )
+ expect(chart.valueLabels()).toHaveLength(0)
+ })
+
+ it('renders one value label per visible point when valueLabels=true', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart series={SERIES} labels={LABELS} theme={THEME} config={{ valueLabels: true }} />
+ )
+ expect(chart.valueLabels()).toHaveLength(SERIES[0].data.length)
+ })
+
+ it('forwards an explicit formatter', () => {
+ const formatter = (v: number): string => `~${v}`
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ valueLabels: { formatter } }}
+ />
+ )
+ expect(chart.valueLabels().map((l) => l.text)).toEqual(['~1', '~2', '~3'])
+ })
+
+ it('falls back to a yAxis-driven formatter when no explicit formatter is provided', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={[{ key: 'a', label: 'A', data: [50] }]}
+ labels={['Mon']}
+ theme={THEME}
+ config={{ yAxis: { format: 'percentage' }, valueLabels: true }}
+ />
+ )
+ expect(chart.valueLabels().map((l) => l.text)).toEqual(['50%'])
+ })
+
+ it('reuses an explicit yAxis.tickFormatter as the default', () => {
+ const explicit = (v: number): string => `y:${v}`
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ yAxis: { tickFormatter: explicit }, valueLabels: true }}
+ />
+ )
+ expect(chart.valueLabels().map((l) => l.text)).toEqual(['y:1', 'y:2', 'y:3'])
+ })
+
+ it('hides labels for series excluded via seriesKeys', () => {
+ const series: Series[] = [
+ { key: 'a', label: 'A', data: [1, 2, 3] },
+ { key: 'b', label: 'B', data: [4, 5, 6] },
+ ]
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={series}
+ labels={LABELS}
+ theme={THEME}
+ config={{ valueLabels: { seriesKeys: ['a'] } }}
+ />
+ )
+ expect(chart.valueLabels()).toHaveLength(3)
+ })
+ })
+
+ describe('config.goalLines', () => {
+ it.each([
+ ['omitted', undefined],
+ ['empty', [] as never[]],
+ ])('does not render reference lines when goalLines is %s', (_, goalLines) => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={goalLines === undefined ? undefined : { goalLines }}
+ />
+ )
+ expect(chart.referenceLines()).toHaveLength(0)
+ })
+
+ it('renders horizontal goal lines with their label', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={[{ key: 'a', label: 'A', data: [10, 20, 100] }]}
+ labels={LABELS}
+ theme={THEME}
+ config={{ goalLines: [{ value: 50, label: 'Target' }] }}
+ />
+ )
+ const lines = chart.referenceLines()
+ expect(lines).toHaveLength(1)
+ expect(lines[0].orientation).toBe('horizontal')
+ expect(lines[0].label).toBe('Target')
+ })
+ })
+
+ describe('config.barLayout', () => {
+ it.each(['stacked', 'grouped', 'percent'] as const)('renders ticks for %s layout', (barLayout) => {
+ const series: Series[] = [
+ { key: 'a', label: 'A', data: [10, 20, 30] },
+ { key: 'b', label: 'B', data: [5, 15, 25] },
+ ]
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart series={series} labels={LABELS} theme={THEME} config={{ barLayout }} />
+ )
+ expect(chart.yTicks().length).toBeGreaterThan(0)
+ })
+
+ it('applies a default percent formatter when barLayout=percent and no yAxis.format is given', () => {
+ const series: Series[] = [
+ { key: 'a', label: 'A', data: [10, 20, 30] },
+ { key: 'b', label: 'B', data: [5, 15, 25] },
+ ]
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart series={series} labels={LABELS} theme={THEME} config={{ barLayout: 'percent' }} />
+ )
+ expect(chart.yTicks().some((t) => /\d+%/.test(t))).toBe(true)
+ })
+
+ it('formats value labels as percentages when yAxis.format=percentage_scaled with 0-1 data', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={[{ key: 'a', label: 'A', data: [0.1, 0.2, 0.3] }]}
+ labels={LABELS}
+ theme={THEME}
+ config={{
+ barLayout: 'percent',
+ yAxis: { format: 'percentage_scaled' },
+ valueLabels: true,
+ }}
+ />
+ )
+ expect(chart.valueLabels().map((l) => l.text)).toEqual(['10%', '20%', '30%'])
+ })
+ })
+
+ describe('config.axisOrientation', () => {
+ it('renders ticks on the x-axis when axisOrientation=horizontal', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ axisOrientation: 'horizontal' }}
+ />
+ )
+ expect(chart.xTicks().length).toBeGreaterThan(0)
+ })
+ })
+
+ it('forwards children alongside built-in overlays', () => {
+ const { container } = renderHogChart(
+ <TimeSeriesBarChart series={SERIES} labels={LABELS} theme={THEME}>
+ <div data-attr="custom-overlay" />
+ </TimeSeriesBarChart>
+ )
+ expect(container.querySelector('[data-attr="custom-overlay"]')).not.toBeNull()
+ })
+})
diff --git a/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
new file mode 100644
index 000000000000..2c9cb02181ec
--- /dev/null
+++ b/frontend/src/lib/hog-charts/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -0,0 +1,156 @@
+import React, { useMemo } from 'react'
+
+import type {
+ BarChartConfig,
+ ChartTheme,
+ PointClickData,
+ Series,
+ TooltipConfig,
+ TooltipContext,
+} from '../../core/types'
+import { ReferenceLines } from '../../overlays/ReferenceLine'
+import { ValueLabels } from '../../overlays/ValueLabels'
+import { buildGoalLineReferenceLines, type GoalLineConfig } from '../../utils/goal-lines'
+import {
+ useXTickFormatter,
+ useYTickFormatter,
+ type XAxisConfig,
+ type YAxisConfig,
+} from '../../utils/use-axis-formatters'
+import { BarChart } from '../BarChart/BarChart'
+
+export interface ValueLabelsConfig {
+ seriesKeys?: string[]
+ formatter?: (value: number) => string
+}
+
+export interface TimeSeriesBarChartConfig {
+ xAxis?: XAxisConfig
+ yAxis?: YAxisConfig
+ valueLabels?: boolean | ValueLabelsConfig
+ goalLines?: GoalLineConfig[]
+ /** Defaults to `stacked`. */
+ barLayout?: BarChartConfig['barLayout']
+ /** Defaults to `vertical`. */
+ axisOrientation?: BarChartConfig['axisOrientation']
+ /** Stacked bars only round the topmost segment. */
+ barCornerRadius?: number
+ /** Show a vertical crosshair line that follows the cursor. */
+ showCrosshair?: boolean
+ /** Tooltip behaviour (pinning, placement). Tooltip *content* is the `tooltip` render prop. */
+ tooltip?: TooltipConfig
+}
+
+export interface TimeSeriesBarChartProps<Meta = unknown> {
+ series: Series<Meta>[]
+ labels: string[]
+ theme: ChartTheme
+ config?: TimeSeriesBarChartConfig
+ tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
+ onPointClick?: (data: PointClickData<Meta>) => void
+ dataAttr?: string
+ className?: string
+ children?: React.ReactNode
+ onError?: (error: Error, info: React.ErrorInfo) => void
+}
+
+function resolveValueLabelsConfig(valueLabels: TimeSeriesBarChartConfig['valueLabels']): ValueLabelsConfig | null {
+ if (valueLabels === undefined || valueLabels === false) {
+ return null
+ }
+ if (valueLabels === true) {
+ return {}
+ }
+ return valueLabels
+}
+
+export function TimeSeriesBarChart<Meta = unknown>({
+ series,
+ labels,
+ theme,
+ config,
+ tooltip,
+ onPointClick,
+ dataAttr,
+ className,
+ children,
+ onError,
+}: TimeSeriesBarChartProps<Meta>): React.ReactElement {
+ const {
+ xAxis,
+ yAxis,
+ valueLabels,
+ goalLines,
+ barLayout,
+ axisOrientation,
+ barCornerRadius,
+ showCrosshair,
+ tooltip: tooltipConfig,
+ } = config ?? {}
+ const xTickFormatter = useXTickFormatter(xAxis, labels)
+ const yTickFormatter = useYTickFormatter(yAxis)
+
+ const valueLabelsConfig = resolveValueLabelsConfig(valueLabels)
+
+ // Stable primitive key so callers can pass `valueLabels: { seriesKeys: ['a'] }` inline
+ // without re-running the transform on every render.
+ const seriesKeysSignature = valueLabelsConfig?.seriesKeys?.join(' ')
+ const seriesAfterValueLabels = useMemo(() => {
+ const seriesKeys = valueLabelsConfig?.seriesKeys
+ if (!seriesKeys) {
+ return series
+ }
+ const allowed = new Set(seriesKeys)
+ return series.map((s) =>
+ allowed.has(s.key) ? s : { ...s, visibility: { ...s.visibility, valueLabel: false } }
+ )
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [series, seriesKeysSignature])
+
+ const valueLabelFormatter = valueLabelsConfig ? (valueLabelsConfig.formatter ?? yTickFormatter) : undefined
+
+ const referenceLines = useMemo(
+ () => buildGoalLineReferenceLines(goalLines, seriesAfterValueLabels),
+ [goalLines, seriesAfterValueLabels]
+ )
+
+ const orientedReferenceLines = useMemo(
+ () =>
+ axisOrientation === 'horizontal'
+ ? referenceLines.map((line) => ({ ...line, axisOrientation: 'horizontal' as const }))
+ : referenceLines,
+ [referenceLines, axisOrientation]
+ )
+
+ const barChartConfig: BarChartConfig = {
+ yScaleType: yAxis?.scale,
+ xTickFormatter,
+ yTickFormatter,
+ hideXAxis: xAxis?.hide,
+ hideYAxis: yAxis?.hide,
+ showGrid: yAxis?.showGrid,
+ barLayout,
+ barCornerRadius,
+ axisOrientation,
+ showCrosshair,
+ tooltip: tooltipConfig,
+ }
+
+ return (
+ <BarChart
+ series={seriesAfterValueLabels}
+ labels={labels}
+ config={barChartConfig}
+ theme={theme}
+ tooltip={tooltip}
+ onPointClick={onPointClick}
+ className={className}
+ dataAttr={dataAttr}
+ onError={onError}
+ >
+ {orientedReferenceLines.length > 0 && <ReferenceLines lines={orientedReferenceLines} />}
+ {valueLabelsConfig && <ValueLabels valueFormatter={valueLabelFormatter} />}
+ {children}
+ </BarChart>
+ )
+}
diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.ts
index d82225c05195..20318ced360a 100644
--- a/frontend/src/lib/hog-charts/index.ts
+++ b/frontend/src/lib/hog-charts/index.ts
@@ -12,6 +12,8 @@ export type {
TrendLineConfig,
ValueLabelsConfig,
} from './charts/TimeSeriesLineChart/TimeSeriesLineChart'
+export { TimeSeriesBarChart } from './charts/TimeSeriesBarChart/TimeSeriesBarChart'
+export type { TimeSeriesBarChartConfig, TimeSeriesBarChartProps } from './charts/TimeSeriesBarChart/TimeSeriesBarChart'
// Base chart (for building new chart types)
export { Chart } from './core/Chart'