: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(trends): move annotation to correct bar for compare against in hog-charts (#57845)
Sam Penningtonc568c629ebba
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 60d7ac11f8f2..25a810d24c80 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1756,6 +1756,10 @@ snapshots:hash: v1.k794b7964.d669cc7bd939e7cd9bae4003a228e194a6c383d827feb04baf491a89dfc0b698.eD11DZ4cr8p1GMBdBaTW1doXInEVj9CIhnyMP8RNpFoinsights-insightstable--is-legend--light:hash: v1.k794b7964.d9eec920b0b2f3c9ea87c9e0d2b298bc37339217e4211d0cf1a147630f09b75d.xGcJlQO8pvoNnHyoMNZ4F58uqKh5PDg_UiGlO5bAMn8+ insights-trendsbarchart--compare--dark:+ hash: v1.k794b7964.68689d02aa245c2ccd04888b1c2bc578136eda4117f2fff911bde3f5c276b9da.svBnhEDDJ61_Vp6T3AUEjT3wlS2aamf9o-YNooKTRlw+ insights-trendsbarchart--compare--light:+ hash: v1.k794b7964.08db5d36c08b26300a7cd09fddd8f02e9ba973ffcf42e556e7f8ae01a27e907b.jN5qaeiDphtPJ90-0-bNC0jmD0MVkSCj6zjO8XzvZkIinsights-trendslinechart--breakdown--dark:hash: v1.k794b7964.4228a311a626ebf45a34acead267954b6b05686aa012ed54242b7a0c5ba298f1.MC_47zRRkXLTsrbhhq1hf2BuXmW8uRCu4fohSF303Isinsights-trendslinechart--breakdown--light:diff --git a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsxindex df791f1e1e76..740bc9624234 100644--- a/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx+++ b/frontend/src/lib/components/AnnotationsOverlay/AnnotationsOverlay.tsx@@ -69,6 +69,9 @@ export interface AnnotationsOverlayProps {chartWidth: numberchartHeight: numberdatasetIndex?: number+ /** Forwarded to the kea logic key so multiple overlays on the same insight don't+ * collide. Used by compare-against-previous bar charts to show one overlay per period. */+ kind?: string}interface AnnotationsOverlayCSSProperties extends React.CSSProperties {@@ -84,6 +87,7 @@ export const AnnotationsOverlay = React.memo(function AnnotationsOverlay({dates,insightNumericId,datasetIndex = 0,+ kind,}: AnnotationsOverlayProps): JSX.Element {const { insightProps } = useValues(insightLogic)const { tickIntervalPx, firstTickLeftPx, getDataPointX } = useAnnotationsPositioning(@@ -113,6 +117,7 @@ export const AnnotationsOverlay = React.memo(function AnnotationsOverlay({insightNumericId,dates,ticks: prevTicksRef.current,+ kind,}const logic = annotationsOverlayLogic(annotationsOverlayLogicProps)const { activeDate, tickDates, annotationBadgeDataIndices, groupedAnnotations } = useValues(logic)diff --git a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.tsindex 099f96c82b29..1dbc844bff34 100644--- a/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts+++ b/frontend/src/lib/components/AnnotationsOverlay/annotationsOverlayLogic.ts@@ -31,6 +31,11 @@ export interface AnnotationsOverlayLogicProps extends Omit<InsightLogicProps, 'dinsightNumericId: QueryBasedInsightModel['id'] | 'new'dates: string[]ticks: { value: number }[]+ /** Disambiguator for charts that mount more than one overlay against the same insight+ * (e.g. compare-against-previous renders one layer per period). Without it, both layers+ * would share the same kea instance and the second mount's `dates`/`ticks` would+ * overwrite the first. */+ kind?: string}/** Week/month charts bucket annotations by day so distinct dates don't collapse into one badge. */@@ -70,7 +75,7 @@ function hasPersonPropertyFiltersOrBreakdown(export const annotationsOverlayLogic = kea<annotationsOverlayLogicType>([path((key) => ['lib', 'components', 'Annotations', 'annotationsOverlayLogic', key]),props({ dashboardId: undefined } as AnnotationsOverlayLogicProps),- key(({ insightNumericId }) => insightNumericId),+ key(({ insightNumericId, kind }) => (kind ? `${insightNumericId}::${kind}` : insightNumericId)),connect(() => ({values: [insightLogic,diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsxindex 330ed8d70153..8344521c40da 100644--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx@@ -33,6 +33,18 @@ function bandCenter(scales: BarChartPrivate['__barChart'], label: string): numbereturn start == null ? undefined : start + scales.band.bandwidth() / 2}+/** Center of a specific series's bar within a band. Used by overlays (e.g. annotations)+ * to anchor on the current-period bar in compare-against-previous grouped layouts.+ * Returns undefined when the layout isn't grouped or the series isn't in the group scale. */+function groupedBarCenter(scales: BarChartPrivate['__barChart'], label: string, seriesKey: string): number | undefined {+ const start = scales.band(label)+ const groupOffset = scales.group?.(seriesKey)+ if (start == null || groupOffset == null) {+ return undefined+ }+ return start + groupOffset + (scales.group?.bandwidth() ?? 0) / 2+}+export interface BarChartProps<Meta = unknown> {series: Series<Meta>[]labels: string[]@@ -147,7 +159,15 @@ function BarChartInner<Meta = unknown>({// calls `scales.y(tick)` for x-pixel positioning of value ticks).// For vertical, `y` is the value scale on the y-axis.return {- x: (label: string) => bandCenter(d3Scales, label),+ x: (label: string, seriesKey?: string) => {+ if (seriesKey != null && barLayout === 'grouped') {+ const xForSeries = groupedBarCenter(d3Scales, label, seriesKey)+ if (xForSeries != null) {+ return xForSeries+ }+ }+ return bandCenter(d3Scales, label)+ },y: (value: number) => d3Scales.value(value),yTicks: () => d3Scales.value.ticks?.(yTickCount) ?? [],_private: barChartPrivate,diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.tsindex ded8cfd2d52d..01061cad5140 100644--- a/frontend/src/lib/hog-charts/core/types.ts+++ b/frontend/src/lib/hog-charts/core/types.ts@@ -231,8 +231,11 @@ export interface YAxisScale {/** Generic scale interface that Chart uses for shared overlays and interaction. */export interface ChartScales {- /** Maps a label to an x pixel coordinate. */- x: (label: string) => number | undefined+ /** Maps a label to an x pixel coordinate. For chart types where data points+ * for the same label live at different x positions (e.g. grouped bar charts+ * in compare-against-previous mode), pass `seriesKey` to anchor on a specific+ * series. Falls back to the band/point center when omitted or unknown. */+ x: (label: string, seriesKey?: string) => number | undefined/** Maps a y value to a pixel coordinate. Uses the default (left) axis. */y: (value: number) => number/** Returns tick values for the default (left) y-axis. */diff --git a/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.stories.tsx b/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.stories.tsxnew file mode 100644index 000000000000..4381eb73a660--- /dev/null+++ b/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.stories.tsx@@ -0,0 +1,226 @@+import { Meta, StoryObj } from '@storybook/react'+import { BindLogic } from 'kea'+import { useState } from 'react'++import { insightLogic } from 'scenes/insights/insightLogic'++import { mswDecorator } from '~/mocks/browser'+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import type { DataNodeLogicProps } from '~/queries/nodes/DataNode/dataNodeLogic'+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/InsightViz'+import { getCachedResults } from '~/queries/nodes/InsightViz/utils'+import type { InsightLogicProps, InsightShortId } from '~/types'++import { TrendsBarChart } from './TrendsBarChart'++type Story = StoryObj<{}>++const meta: Meta = {+ title: 'Insights/TrendsBarChart',+ component: TrendsBarChart,+ parameters: {+ layout: 'centered',+ mockDate: '2023-07-11',+ testOptions: { snapshotBrowsers: ['chromium'] },+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/annotations/': {+ count: 2,+ next: null,+ previous: null,+ results: [+ {+ id: 1,+ content: 'Pricing page redesign shipped',+ // Current-period marker. Pre-fix the badge sat between the+ // bars at band center; post-fix it sits over the right+ // (current-period) bar of band index 3 (Jul 7).+ date_marker: '2023-07-07T12:00:00Z',+ creation_type: 'USR',+ dashboard_item: null,+ created_by: {+ id: 1,+ uuid: '0188cbcf-2391-0000-1868-14fb987285c5',+ distinct_id: 'storybook-user',+ first_name: 'Story',+ email: '[email protected]',+ },+ created_at: '2023-07-07T12:00:00Z',+ updated_at: '2023-07-07T12:00:00Z',+ deleted: false,+ scope: 'project',+ },+ {+ id: 2,+ content: 'Pricing page launched (previous period)',+ // Previous-period marker, falls in the Jun 27 - Jul 3 window.+ // Jul 1 → previous-period dataIndex 4 → left bar of band 4+ // (under the "Jul 8" tick on the rendered axis).+ date_marker: '2023-07-01T12:00:00Z',+ creation_type: 'USR',+ dashboard_item: null,+ created_by: {+ id: 1,+ uuid: '0188cbcf-2391-0000-1868-14fb987285c5',+ distinct_id: 'storybook-user',+ first_name: 'Story',+ email: '[email protected]',+ },+ created_at: '2023-07-01T12:00:00Z',+ updated_at: '2023-07-01T12:00:00Z',+ deleted: false,+ scope: 'project',+ },+ ],+ },+ },+ }),+ ],+}+export default meta++let uniqueNode = 0++function Stage({ children }: { children: React.ReactNode }): JSX.Element {+ return (+ // eslint-disable-next-line react/forbid-dom-props+ <div style={{ height: 360, width: 720, display: 'flex', flexDirection: 'column' }}>{children}</div>+ )+}++function renderTrendsBarChart(insightFixture: any): JSX.Element {+ const [dashboardItemId] = useState(() => `TrendsBarChartStory.${uniqueNode++}` as InsightShortId)+ const cachedInsight = { ...insightFixture, short_id: dashboardItemId }++ const insightProps: InsightLogicProps = { dashboardItemId, doNotLoad: true, cachedInsight }+ const dataNodeLogicProps: DataNodeLogicProps = {+ query: cachedInsight.query.source,+ key: insightVizDataNodeKey(insightProps),+ cachedResults: getCachedResults(cachedInsight, cachedInsight.query.source),+ doNotLoad: true,+ }++ return (+ <BindLogic logic={insightLogic} props={insightProps}>+ <BindLogic logic={dataNodeLogic} props={dataNodeLogicProps}>+ <Stage>+ <TrendsBarChart />+ </Stage>+ </BindLogic>+ </BindLogic>+ )+}++const CURRENT_DAYS = ['2023-07-04', '2023-07-05', '2023-07-06', '2023-07-07', '2023-07-08', '2023-07-09', '2023-07-10']+const CURRENT_LABELS = [+ '4-Jul-2023',+ '5-Jul-2023',+ '6-Jul-2023',+ '7-Jul-2023',+ '8-Jul-2023',+ '9-Jul-2023',+ '10-Jul-2023',+]+const PREVIOUS_DAYS = ['2023-06-27', '2023-06-28', '2023-06-29', '2023-06-30', '2023-07-01', '2023-07-02', '2023-07-03']+const PREVIOUS_LABELS = [+ '27-Jun-2023',+ '28-Jun-2023',+ '29-Jun-2023',+ '30-Jun-2023',+ '1-Jul-2023',+ '2-Jul-2023',+ '3-Jul-2023',+]++const ACTION = {+ id: '$pageview',+ type: 'events',+ order: 0,+ name: '$pageview',+ custom_name: null,+ math: 'total',+ math_property: null,+ math_hogql: null,+ math_group_type_index: null,+ properties: {},+}++// Compare-against-previous in unstacked-bar mode renders two bars per band (previous, current).+// Pre-fix, annotations anchored to the band center landed on the previous-period bar.+// The numbers below are intentionally distinct so the snapshot diffs the tall current bars+// from the shorter previous bars and the annotation sits over the current one.+const COMPARE_BAR_INSIGHT = {+ id: 200,+ short_id: 'barCompare',+ name: 'Pageviews compare',+ derived_name: 'Pageview count',+ filters: {},+ last_refresh: '2023-07-11T12:00:00Z',+ refreshing: false,+ saved: true,+ is_sample: false,+ description: '',+ tags: [],+ favorited: false,+ created_at: '2023-07-11T12:00:00Z',+ updated_at: '2023-07-11T12:00:00Z',+ last_modified_at: '2023-07-11T12:00:00Z',+ dashboards: [],+ dashboard_tiles: [],+ result: [+ {+ action: ACTION,+ label: '$pageview',+ count: 700,+ data: [120, 95, 110, 130, 140, 80, 125],+ labels: CURRENT_LABELS,+ days: CURRENT_DAYS,+ compare: true,+ compare_label: 'current',+ filter: {+ date_from: '2023-07-04T00:00:00Z',+ date_to: '2023-07-10T23:59:59Z',+ display: 'ActionsUnstackedBar',+ insight: 'TRENDS',+ interval: 'day',+ },+ },+ {+ action: ACTION,+ label: '$pageview',+ count: 420,+ data: [70, 60, 65, 75, 80, 50, 70],+ labels: PREVIOUS_LABELS,+ days: PREVIOUS_DAYS,+ compare: true,+ compare_label: 'previous',+ filter: {+ date_from: '2023-06-27T00:00:00Z',+ date_to: '2023-07-03T23:59:59Z',+ display: 'ActionsUnstackedBar',+ insight: 'TRENDS',+ interval: 'day',+ },+ },+ ],+ query: {+ kind: 'InsightVizNode',+ source: {+ dateRange: { date_from: '2023-07-04', date_to: '2023-07-10' },+ filterTestAccounts: false,+ interval: 'day',+ kind: 'TrendsQuery',+ series: [{ event: '$pageview', kind: 'EventsNode', math: 'total', name: '$pageview' }],+ trendsFilter: { display: 'ActionsUnstackedBar' },+ compareFilter: { compare: true },+ version: 2,+ },+ full: true,+ },+}++export const Compare: Story = {+ render: () => renderTrendsBarChart(COMPARE_BAR_INSIGHT),+}diff --git a/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.tsx b/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.tsxindex 0bd2169afc51..31a12f205d9a 100644--- a/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.tsx+++ b/frontend/src/scenes/trends/viz/trends-bar-chart/TrendsBarChart.tsx@@ -284,6 +284,14 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart// layouts (vertical bars). The horizontal aggregated layout has categorical labels.const showAnnotations = !inSharedMode && !isAggregatedconst annotationsDates = currentPeriodResult?.days ?? []+ // In compare-against-previous grouped layouts each band holds two bars (previous, current).+ // Anchor each period's annotations on its matching bar so they line up with what they describe.+ const currentSeriesKey = isGrouped ? series.find((s) => s.meta?.compare_label === 'current')?.key : undefined+ const previousSeriesKey = isGrouped ? series.find((s) => s.meta?.compare_label === 'previous')?.key : undefined+ const previousPeriodResult = isGrouped+ ? indexedResults?.find((r: IndexedTrendResult) => r.compare_label === 'previous')+ : undefined+ const annotationsPreviousDates = previousPeriodResult?.daysreturn (<BarChart<TrendsSeriesMeta>@@ -310,7 +318,15 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart/>)}{showValuesOnSeries && <ValueLabels valueFormatter={valueLabelFormatter} />}- {showAnnotations && <AnnotationsLayer insightNumericId={insight.id || 'new'} dates={annotationsDates} />}+ {showAnnotations && (+ <AnnotationsLayer+ insightNumericId={insight.id || 'new'}+ dates={annotationsDates}+ seriesKey={currentSeriesKey}+ previousDates={annotationsPreviousDates}+ previousSeriesKey={previousSeriesKey}+ />+ )}</BarChart>)}diff --git a/frontend/src/scenes/trends/viz/trends-line-chart/AnnotationsLayer.tsx b/frontend/src/scenes/trends/viz/trends-line-chart/AnnotationsLayer.tsxindex 6548886dc872..6a9541b6b611 100644--- a/frontend/src/scenes/trends/viz/trends-line-chart/AnnotationsLayer.tsx+++ b/frontend/src/scenes/trends/viz/trends-line-chart/AnnotationsLayer.tsx@@ -9,6 +9,17 @@ interface AnnotationsLayerProps {insightNumericId: number | 'new'/** Per-data-point date strings; used for grouping annotations. */dates: string[]+ /** Series key whose bar should anchor annotations in compare-against-previous grouped+ * bar layouts. Without it, annotations land on the band center (between current+ * and previous bars) instead of the current-period bar. */+ seriesKey?: string+ /** Per-data-point date strings for the previous period in compare-against-previous+ * layouts. When provided alongside `previousSeriesKey`, a second overlay renders+ * previous-period annotations anchored on the previous-period bar. */+ previousDates?: string[]+ /** Series key for the previous-period bar. Required for previous-period annotations+ * to anchor on the correct bar within each band. */+ previousSeriesKey?: string}const WRAPPER_STYLE: React.CSSProperties = {@@ -22,13 +33,19 @@ const stopPointerPropagation = (e: React.MouseEvent<HTMLDivElement>): void => {e.stopPropagation()}-export function AnnotationsLayer({ insightNumericId, dates }: AnnotationsLayerProps): React.ReactElement | null {+export function AnnotationsLayer({+ insightNumericId,+ dates,+ seriesKey,+ previousDates,+ previousSeriesKey,+}: AnnotationsLayerProps): React.ReactElement | null {const { scales, dimensions, labels, axis } = useChartLayout()const xTickFormatter = axis.xTickFormatter- const chartLike = useMemo(() => {+ const currentChartLike = useMemo(() => {const visibleXLabels = computeVisibleXLabels(labels, scales.x, xTickFormatter)- const points = labels.map((label) => ({ x: scales.x(label) ?? 0, y: 0 }))+ const points = labels.map((label) => ({ x: scales.x(label, seriesKey) ?? 0, y: 0 }))const ticks = visibleXLabels.map((v) => ({ value: v.index }))return {scales: {@@ -40,9 +57,41 @@ export function AnnotationsLayer({ insightNumericId, dates }: AnnotationsLayerPr},_metasets: [{ data: points }],}- }, [labels, scales.x, dimensions.plotLeft, dimensions.plotTop, dimensions.plotHeight, xTickFormatter])+ // eslint-disable-next-line react-hooks/exhaustive-deps -- only `scales.x` is read; `scales` itself is unused.+ }, [labels, scales.x, seriesKey, dimensions.plotLeft, dimensions.plotTop, dimensions.plotHeight, xTickFormatter])- if (chartLike.scales.x.ticks.length < 2) {+ const previousChartLike = useMemo(() => {+ if (!previousDates || !previousSeriesKey) {+ return null+ }+ const visibleXLabels = computeVisibleXLabels(labels, scales.x, xTickFormatter)+ // Anchor on the previous-period bar (left bar in each band) but reuse the current+ // labels — only the x positions matter, not the labels themselves.+ const points = labels.map((label) => ({ x: scales.x(label, previousSeriesKey) ?? 0, y: 0 }))+ const ticks = visibleXLabels.map((v) => ({ value: v.index }))+ return {+ scales: {+ x: {+ ticks,+ left: dimensions.plotLeft,+ top: dimensions.plotTop + dimensions.plotHeight,+ },+ },+ _metasets: [{ data: points }],+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps -- only `scales.x` is read; `scales` itself is unused.+ }, [+ labels,+ scales.x,+ previousSeriesKey,+ previousDates,+ dimensions.plotLeft,+ dimensions.plotTop,+ dimensions.plotHeight,+ xTickFormatter,+ ])++ if (currentChartLike.scales.x.ticks.length < 2) {return null}@@ -55,12 +104,22 @@ export function AnnotationsLayer({ insightNumericId, dates }: AnnotationsLayerPronMouseDown={stopPointerPropagation}><AnnotationsOverlay- chart={chartLike as unknown as Chart}+ chart={currentChartLike as unknown as Chart}dates={dates}chartWidth={dimensions.width}chartHeight={dimensions.height}insightNumericId={insightNumericId}/>+ {previousChartLike && previousDates && (+ <AnnotationsOverlay+ chart={previousChartLike as unknown as Chart}+ dates={previousDates}+ chartWidth={dimensions.width}+ chartHeight={dimensions.height}+ insightNumericId={insightNumericId}+ kind="previous"+ />+ )}</div>)}