Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(insights): sort slope graph tooltip by value descending (#64124)

Paul D'Ambra5d9b75e1baf9
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 7353b7db44b1..d5c992e6815c 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -67,7 +67,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).
- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original.
- `Legend` is presentational: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change).
-- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
+- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order); pass your own `tooltip` to override. Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.
## Maintenance
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
index 0c20307d1776..8500af389f2e 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
@@ -1,6 +1,6 @@
-import type { ChartTheme, Series } from '../../core/types'
+import type { ChartTheme, Series, TooltipContext } from '../../core/types'
import { renderHogChart } from '../../testing'
-import type { SlopeSeriesMeta } from './slope-data'
+import { sortSlopeTooltipRows, type SlopeSeriesMeta } from './slope-data'
import { SlopeChart } from './SlopeChart'
const THEME: ChartTheme = {
@@ -151,6 +151,19 @@ describe('SlopeChart', () => {
)
expect(chart.slopeLegendItems().map((i) => i.secondaryLabel)).toEqual(['↑80', '↓60'])
})
+
+ it('orders rows biggest-to-smallest by end value', () => {
+ // Input order (A, B, C) differs from descending end values (B 90, C 60, A 30).
+ const series: Series<SlopeSeriesMeta>[] = [
+ { key: 'a', label: 'A', data: [0, 30] },
+ { key: 'b', label: 'B', data: [0, 90] },
+ { key: 'c', label: 'C', data: [0, 60] },
+ ]
+ const { chart } = renderHogChart(
+ <SlopeChart series={series} labels={LABELS} config={{ legend: { show: true } }} theme={THEME} />
+ )
+ expect(chart.slopeLegendItems().map((i) => i.label)).toEqual(['B', 'C', 'A'])
+ })
})
describe('incompleteEnd', () => {
@@ -215,6 +228,29 @@ describe('SlopeChart', () => {
})
})
+ describe('tooltip row sorting', () => {
+ const row = (key: string, value: number): TooltipContext['seriesData'][number] => ({
+ series: { key, label: key.toUpperCase(), data: [] },
+ value,
+ color: '#000',
+ })
+
+ it.each([
+ ['unsorted input', [row('a', 30), row('b', 90), row('c', 60)], [90, 60, 30]],
+ ['already sorted descending', [row('a', 90), row('b', 60), row('c', 30)], [90, 60, 30]],
+ ['already sorted ascending', [row('a', 30), row('b', 60), row('c', 90)], [90, 60, 30]],
+ ['single element', [row('a', 42)], [42]],
+ ] as const)('orders rows biggest-to-smallest by value (%s)', (_label, input, expected) => {
+ expect(sortSlopeTooltipRows([...input]).map((r) => r.value)).toEqual([...expected])
+ })
+
+ it('does not mutate the input array', () => {
+ const input = [row('a', 30), row('b', 90)]
+ sortSlopeTooltipRows(input)
+ expect(input.map((r) => r.value)).toEqual([30, 90])
+ })
+ })
+
it('forwards dataAttr to the chart wrapper', () => {
const { chart } = renderHogChart(
<SlopeChart series={SERIES} labels={LABELS} theme={THEME} dataAttr="slope-instance" />
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
index bfb12a1e0748..50635ab3dd00 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
@@ -12,6 +12,7 @@ import type {
TooltipContext,
ValueDomain,
} from '../../core/types'
+import { DefaultTooltip } from '../../overlays/DefaultTooltip'
import { AXIS_LABEL_FONT, FONT_FAMILY, measureLabelWidth } from '../../utils/text-measure'
import { LineChart } from '../LineChart/LineChart'
import {
@@ -20,6 +21,7 @@ import {
slopeEnd,
slopeLabelVisible,
slopeStart,
+ sortSlopeTooltipRows,
type SlopeSeriesMeta,
} from './slope-data'
import { slopeLegendItems } from './slope-legend'
@@ -186,6 +188,14 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
const legendItems = useMemo(() => slopeLegendItems(series, theme, deltaFormatter), [series, theme, deltaFormatter])
+ // A caller-supplied tooltip takes precedence; otherwise sort the default rows (see helper).
+ const sortedTooltip = useCallback(
+ (ctx: TooltipContext<Meta>): React.ReactNode => (
+ <DefaultTooltip {...ctx} seriesData={sortSlopeTooltipRows(ctx.seriesData)} />
+ ),
+ []
+ )
+
return (
<ChartLegend
show={legend?.show ?? false}
@@ -200,7 +210,7 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
labels={slopeLabels}
config={lineConfig}
theme={theme}
- tooltip={tooltip}
+ tooltip={tooltip ?? sortedTooltip}
onPointClick={onPointClick}
className={className}
dataAttr={dataAttr}
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/slope-data.ts b/packages/quill/packages/charts/src/charts/SlopeChart/slope-data.ts
index 5da5f8d41197..d14d9d97b4d3 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/slope-data.ts
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/slope-data.ts
@@ -1,4 +1,4 @@
-import type { Series } from '../../core/types'
+import type { Series, TooltipContext } from '../../core/types'
/** Per-series options read from `Series.meta` by the slope chart. Lets a consumer toggle the
* start/end value labels for an individual series without touching the shared `Series` type. */
@@ -44,6 +44,15 @@ export function slopeDelta(series: Pick<Series, 'data'>): number {
return slopeEnd(series) - slopeStart(series)
}
+/** Slope tooltips list one row per series; with many breakdowns an unsorted list is unreadable.
+ * Order rows biggest-to-smallest by the hovered point's value so they match the lines' vertical
+ * order at that x. */
+export function sortSlopeTooltipRows<Meta>(
+ rows: TooltipContext<Meta>['seriesData']
+): TooltipContext<Meta>['seriesData'] {
+ return [...rows].sort((a, b) => b.value - a.value)
+}
+
export function defaultValueFormatter(value: number): string {
return value.toLocaleString()
}
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/slope-legend.ts b/packages/quill/packages/charts/src/charts/SlopeChart/slope-legend.ts
index cd66c7071964..2dcdbd430d8b 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/slope-legend.ts
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/slope-legend.ts
@@ -1,18 +1,24 @@
import type { LegendItem } from '../../components/Legend/Legend'
import { legendItemsFromSeries } from '../../components/Legend/legendItemsFromSeries'
import type { ChartTheme, ResolvedSeries, Series } from '../../core/types'
-import { slopeDelta } from './slope-data'
+import { slopeDelta, slopeEnd } from './slope-data'
/** Legend items for a slope chart — `legendItemsFromSeries` plus a per-series change
- * (`end − start`, formatted) carried as each row's `secondaryLabel`. */
+ * (`end − start`, formatted) carried as each row's `secondaryLabel`. Rows are ordered
+ * biggest-to-smallest by end value so the legend matches the lines' vertical order at
+ * the right edge (and the tooltip's ordering). Sorting the built items rather than the
+ * input series keeps each swatch's colour — `legendItemsFromSeries` assigns palette
+ * colours by input index — matched to its line. */
export function slopeLegendItems(
series: ReadonlyArray<Series | ResolvedSeries>,
theme: ChartTheme,
deltaFormatter: (delta: number) => string
): LegendItem[] {
const byKey = new Map(series.map((s) => [s.key, s]))
- return legendItemsFromSeries(series, theme).map((item) => ({
- ...item,
- secondaryLabel: deltaFormatter(slopeDelta(byKey.get(item.key)!)),
- }))
+ return legendItemsFromSeries(series, theme)
+ .map((item) => ({
+ ...item,
+ secondaryLabel: deltaFormatter(slopeDelta(byKey.get(item.key)!)),
+ }))
+ .sort((a, b) => slopeEnd(byKey.get(b.key)!) - slopeEnd(byKey.get(a.key)!))
}